feat: add individual agent interaction permissions (#20411)

Add eleven sparse incoming and outgoing restrictions, human CLI/API administration, shared mutation enforcement, and pending-delivery checks. Preserve existing defaults, agent settings, and existing authorization boundaries.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-09 20:34:04 -06:00
1 parent 4158799d1b
commit 5bad074baa
97 files changed
+3590 -433

No files matched your search

@@ -3,9 +3,10 @@ import type { AutomaticCompletionReviewScope } from "../automatic-completion-rev
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
import { and, asc, eq, gt, inArray, isNull, sql } from "drizzle-orm";
import { and, asc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
import {
completionContracts,
heartbeatRuns,
issueThreadInteractions,
issues,
nativeRunFinalizations,
@@ -52,6 +53,11 @@ function findAutomaticReviewCandidates(db: Db, options: { issueId?: string; comp
eq(statusDecisions.runId, issueThreadInteractions.sourceRunId),
),
)
.innerJoin(
heartbeatRuns,
and(eq(heartbeatRuns.id, issueThreadInteractions.sourceRunId),
eq(heartbeatRuns.companyId, issueThreadInteractions.companyId)),
)
.innerJoin(
workAssessments,
and(
@@ -72,7 +78,8 @@ function findAutomaticReviewCandidates(db: Db, options: { issueId?: string; comp
and(
eq(issueThreadInteractions.status, "pending"),
eq(issueThreadInteractions.kind, "request_confirmation"),
isNull(issueThreadInteractions.createdByAgentId),
or(isNull(issueThreadInteractions.createdByAgentId),
eq(issueThreadInteractions.createdByAgentId, heartbeatRuns.agentId)),
isNull(issueThreadInteractions.createdByUserId),
eq(statusDecisions.applicationState, "applied"),
eq(statusDecisions.toStatus, "in_review"),
@@ -162,7 +169,10 @@ async function dismissCandidates(db: Db, candidates: Awaited<ReturnType<typeof f
eq(issueThreadInteractions.kind, interaction.kind),
eq(issueThreadInteractions.sourceRunId, decision.runId),
eq(issueThreadInteractions.idempotencyKey, interaction.idempotencyKey!),
isNull(issueThreadInteractions.createdByAgentId), isNull(issueThreadInteractions.createdByUserId),
interaction.createdByAgentId
? eq(issueThreadInteractions.createdByAgentId, interaction.createdByAgentId)
: isNull(issueThreadInteractions.createdByAgentId),
isNull(issueThreadInteractions.createdByUserId),
),
)
.returning();
@@ -2952,7 +2952,7 @@ describe("native external-chat response wait", () => {
expect(gate).toMatchObject({
kind: "request_confirmation",
status: "pending",
createdByAgentId: null,
createdByAgentId: fixture.agentId,
createdByUserId: null,
});
await db
@@ -3629,11 +3629,19 @@ describe("native external-chat response wait", () => {
} finally { await coordinator.stop(); vi.useRealTimers(); }
});
it.each(["telegram", "discord"] as const)(
"presents the exact %s response without resolving a pre-existing native completion review",
async (provider) => {
it.each([
["telegram", "agent"],
["discord", "agent"],
["telegram", "legacy_system"],
] as const)(
"presents the exact %s response without resolving a pre-existing native completion review with %s provenance",
async (provider, provenance) => {
const fixture = await seedWaitTurn(provider);
const gate = await seedPriorCompletionReview(fixture);
if (provenance === "legacy_system") {
await db.update(issueThreadInteractions).set({ createdByAgentId: null })
.where(eq(issueThreadInteractions.id, gate.id));
}
const selectedComment = await issueService(db).addComment(
fixture.issueId,
"Prepared exactly these files for this chat response.",
@@ -3796,9 +3804,14 @@ describe("native external-chat response wait", () => {
approvalId: approval!.id,
});
} else if (kind === "agent_gate") {
const [otherAgent] = await db.insert(agents).values({
companyId: fixture.companyId,
name: "Unrelated review author",
adapterType: "process",
}).returning();
await db
.update(issueThreadInteractions)
.set({ createdByAgentId: fixture.agentId })
.set({ createdByAgentId: otherAgent!.id })
.where(eq(issueThreadInteractions.id, gate.id));
} else if (kind === "new_attention") {
await db.insert(issueThreadInteractions).values({
@@ -181,7 +181,6 @@ async function reviewPresentationEvidence(
if (
!gate ||
gate.kind !== "request_confirmation" ||
gate.createdByAgentId ||
gate.createdByUserId ||
!gate.sourceRunId ||
gate.sourceRunId === run.id ||
@@ -197,8 +196,16 @@ async function reviewPresentationEvidence(
return null;
const [origin, competingInteraction, competingApproval] = await Promise.all([
db
.select({ id: statusDecisions.id, decisionJson: statusDecisions.decisionJson })
.select({ id: statusDecisions.id, decisionJson: statusDecisions.decisionJson, agentId: heartbeatRuns.agentId })
.from(statusDecisions)
.innerJoin(
heartbeatRuns,
and(
eq(heartbeatRuns.id, statusDecisions.runId),
eq(heartbeatRuns.companyId, input.companyId),
eq(heartbeatRuns.nativeIssueId, input.issueId),
),
)
.innerJoin(
statusDecisionEffects,
and(
@@ -255,7 +262,8 @@ async function reviewPresentationEvidence(
.limit(1)
.then((rows) => rows[0]),
]);
if (!origin || competingInteraction || competingApproval) return null;
if (!origin || competingInteraction || competingApproval
|| (gate.createdByAgentId !== null && gate.createdByAgentId !== origin.agentId)) return null;
const reviewEffects = Array.isArray(origin.decisionJson.effects) ? origin.decisionJson.effects : [];
const matchesReviewRequest = reviewEffects.some((value) => {
const effect = record(value);
@@ -2,12 +2,13 @@ import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, completionContracts, createDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, pluginManagedResources, plugins, routineRuns, routines, workAssessments } from "@paperclipai/db";
import { agentWakeupRequests, agents, companies, completionContracts, createDb, heartbeatRuns, issueComments, issueRelations, issueThreadInteractions, issues, nativeRunFinalizations, nativeRunResults, pluginManagedResources, plugins, routineRuns, routines, statusDecisionEffects, statusDecisions, workAssessments } from "@paperclipai/db";
import type { Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { routineService } from "../routines.js";
import { commitNativeStatusDecision } from "./status-decision-committer.js";
import { NATIVE_STATUS_ARBITER_POLICY_VERSION, type NativeStatusDecision } from "./status-arbiter.js";
import { INTERACTION_DELIVERY_DENIED } from "../agent-interaction-delivery.js";
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_NATIVE_ROUTINE_STATUS_TEST_DATABASE_URL");
const support = external ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport();
@@ -73,6 +74,66 @@ if (!support.supported) console.warn(`Skipping native routine status tests: ${su
const replay = await commit(f, status); expect(replay.replayed).toBe(true); expect(replay.decision.id).toBe(first.decision.id);
expect((await db.select().from(routineRuns).where(eq(routineRuns.id, f.invocationId)))[0]).toEqual(saved);
});
it("retains the native decision author when requesting a protected agent reviewer", async () => {
const f = await seed(), reviewer = randomUUID();
await db.insert(agents).values({ id: reviewer, companyId, name: "Protected reviewer", adapterType: "process", status: "active",
permissions: { interactions: { canReceiveAssignmentsFromAgents: false } } });
const requestReview = () => commitNativeStatusDecision({ db, companyId, issueId: f.issueId, runId: f.runId, assessmentId: f.assessmentId,
priorStatus: "in_progress", priorStatusVersion: f.priorStatusVersion, priorDecisionId: f.priorDecisionId,
decision: { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, statusAction: "preserve", toStatus: "in_progress",
reasonCode: "review_requested", unblockDescriptor: null, effects: [{ kind: "bind_reviewer", ownerAgentId: reviewer,
ownerUserId: null, prompt: "Review this work" }] },
});
await expect(requestReview()).rejects.toMatchObject({ status: 403, details: expect.objectContaining({ actorAgentId: agentId,
permission: "canReceiveAssignmentsFromAgents" }) });
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, f.issueId))).toEqual([]);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, reviewer))).toEqual([]);
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.issueId, f.issueId))).toEqual([]);
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].status).toBe("in_progress");
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0])
.toMatchObject({ phase: "terminal_failure", failureCode: "agent_interaction_denied", nextAttemptAt: null });
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].status).toBe("running");
await db.update(agents).set({ permissions: {} }).where(eq(agents.id, reviewer));
await expect(requestReview()).rejects.toMatchObject({ status: 403,
details: expect.objectContaining({ permission: "canReceiveAssignmentsFromAgents" }) });
});
it.each([false, true])("commits child completion while permanently refusing its protected parent report (dependency: %s)", async dependency => {
const f = await seed(), parentId = randomUUID(), parentAgentId = randomUUID();
const report = "PRIVATE_REPORT_TEXT: agent-authored completion instructions";
await db.insert(agents).values({ id: parentAgentId, companyId, name: "Protected parent", adapterType: "process", status: "active",
permissions: { interactions: { canReceiveCommentsFromAgents: false } } });
await db.insert(issues).values({ id: parentId, companyId, title: "Parent task", status: dependency ? "blocked" : "in_progress", assigneeAgentId: parentAgentId });
await db.update(issues).set({ parentId }).where(eq(issues.id, f.issueId));
await db.update(nativeRunResults).set({ resultJson: { result: { summary: report } } }).where(eq(nativeRunResults.runId, f.runId));
if (dependency) await db.insert(issueRelations).values({ companyId, issueId: f.issueId, relatedIssueId: parentId, type: "blocks" });
const completed = await commit(f, "done");
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].status).toBe("done");
expect((await db.select().from(routineRuns).where(eq(routineRuns.id, f.invocationId)))[0].status).toBe("completed");
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0])
.toMatchObject({ phase: "committed", failureCode: null, nextAttemptAt: null });
expect((await db.select().from(issues).where(eq(issues.id, parentId)))[0].status).toBe(dependency ? "blocked" : "in_progress");
expect(await db.select().from(issueComments).where(eq(issueComments.issueId, parentId))).toEqual([]);
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, parentAgentId)).orderBy(agentWakeupRequests.id);
const reportWake = wakes.find(wake => wake.reason === "issue_children_completed");
expect(reportWake).toMatchObject({ status: "skipped", error: INTERACTION_DELIVERY_DENIED, finishedAt: expect.any(Date), runId: null,
payload: { interactionOrigin: { actorType: "agent", actorId: agentId, operation: "comment" },
interactionPermissionDenials: { assignment: { permission: "canReceiveCommentsFromAgents", targetAgentId: parentAgentId } } } });
expect(JSON.stringify(wakes)).not.toContain(report);
expect(wakes).toHaveLength(dependency ? 2 : 1);
const dependencyWake = wakes.find(wake => wake.reason === "issue_blockers_resolved");
if (dependency) expect(dependencyWake).toMatchObject({ status: "queued", requestedByActorType: "system", error: null,
payload: { resolvedBlockerIssueId: f.issueId, blockerIssueIds: [f.issueId], interactionOrigin: { actorType: "system" } } });
const effects = await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.decisionId, completed.decision.id));
const reportEffect = effects.find(effect => effect.targetId === reportWake!.id);
expect(reportEffect).toMatchObject({ deliveryState: "skipped", lastError: INTERACTION_DELIVERY_DENIED, deliveredAt: null, nextAttemptAt: null });
expect(JSON.stringify(reportEffect)).not.toContain(report);
await db.update(agents).set({ permissions: {} }).where(eq(agents.id, parentAgentId));
expect((await commit(f, "done")).replayed).toBe(true);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, parentAgentId)).orderBy(agentWakeupRequests.id)).toEqual(wakes);
});
it.each(["ordinary", "wrong-invocation", "wrong-issue", "foreign-company"])("does not settle an invocation with %s custody", async mode => {
const f = await seed(mode); const [before] = await db.select().from(routineRuns).where(eq(routineRuns.id, f.invocationId));
await commit(f, "done");
@@ -2,9 +2,9 @@ import type { ObsoletePolicyReviewScope } from "../obsolete-policy-review-notifi
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
import { and, asc, eq, gt, inArray, isNull, sql } from "drizzle-orm";
import { and, asc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
import {
approvals, issueApprovals, issueThreadInteractions, issues,
approvals, heartbeatRuns, issueApprovals, issueThreadInteractions, issues,
nativeRunFinalizations, statusDecisionEffects, statusDecisions, workAssessments,
type Db,
} from "@paperclipai/db";
@@ -37,6 +37,8 @@ function findObsoletePolicyReviews(db: Db, options: { runIds?: string[]; scope?:
eq(statusDecisions.issueId, issueThreadInteractions.issueId),
eq(statusDecisions.runId, issueThreadInteractions.sourceRunId),
))
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, issueThreadInteractions.sourceRunId),
eq(heartbeatRuns.companyId, issueThreadInteractions.companyId)))
.innerJoin(workAssessments, and(
eq(workAssessments.id, statusDecisions.assessmentId),
eq(workAssessments.companyId, statusDecisions.companyId),
@@ -45,7 +47,8 @@ function findObsoletePolicyReviews(db: Db, options: { runIds?: string[]; scope?:
.where(and(
eq(issueThreadInteractions.status, "pending"),
eq(issueThreadInteractions.kind, "request_confirmation"),
isNull(issueThreadInteractions.createdByAgentId),
or(isNull(issueThreadInteractions.createdByAgentId),
eq(issueThreadInteractions.createdByAgentId, heartbeatRuns.agentId)),
isNull(issueThreadInteractions.createdByUserId),
eq(statusDecisions.applicationState, "applied"),
eq(statusDecisions.reasonCode, "completion_review_required"),
@@ -97,7 +100,10 @@ async function dismissCandidates(db: Db, candidates: Awaited<ReturnType<typeof f
eq(issueThreadInteractions.kind, interaction.kind),
eq(issueThreadInteractions.sourceRunId, decision.runId),
eq(issueThreadInteractions.idempotencyKey, interaction.idempotencyKey!),
isNull(issueThreadInteractions.createdByAgentId), isNull(issueThreadInteractions.createdByUserId),
interaction.createdByAgentId
? eq(issueThreadInteractions.createdByAgentId, interaction.createdByAgentId)
: isNull(issueThreadInteractions.createdByAgentId),
isNull(issueThreadInteractions.createdByUserId),
)).returning({ id: issueThreadInteractions.id });
if (!cancelled) return;
const terminalInteraction = await issueThreadInteractionService(tx as unknown as Db).getById(cancelled.id);
@@ -1945,6 +1945,13 @@ describe("PaperclipControlPlanePort conformance", () => {
const agentReview = (await db.select().from(issueThreadInteractions)
.where(eq(issueThreadInteractions.issueId, issueId)))
.find((entry) => entry.addresseeAgentId === reviewerAgentId)!;
await issueThreadInteractionService(db).sweepSupersededPendingRequestConfirmations();
expect(await db.select({ status: issueThreadInteractions.status, createdByAgentId: issueThreadInteractions.createdByAgentId })
.from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId)))
.toEqual([
{ status: "pending", createdByAgentId: identity.agentId },
{ status: "pending", createdByAgentId: identity.agentId },
]);
expect(reviewWakes[0]).toMatchObject({
companyId: identity.companyId, status: "queued", reason: "native_completion_review",
payload: { issueId, nativeReviewInteractionId: agentReview.id },
@@ -1,3 +1,5 @@
import { assertAgentInteraction } from "../agent-interaction-policy.js";
import { authorizationDeniedDetails } from "../authorization.js";
import { budgetServiceInTransaction } from "../budgets.js";
import { resolveTaskWatchdogMutationScope, taskWatchdogScopeAllowsIssueMutation } from "../task-watchdog-scope.js";
import { resolveNewTaskParent } from "../issue-hierarchy.js";
@@ -1215,7 +1217,7 @@ export class PaperclipRunnerToolAuthority {
if (!this.definitions().some(tool => tool.name === DOWNLOAD_ARTIFACT) || current.issue.workMode !== "standard") throw forbidden("Artifact installation is unavailable to this run or provider");
const decision = await authorizationService(this.db).decide({ actor: this.#privacyActor(current.run), action: "issue:mutate",
resource: { type: "issue", companyId: this.binding.companyId, issueId: current.issue.id } });
if (!decision.allowed) throw forbidden(decision.explanation);
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
const freshAsset = await assetService(this.db).getById(input.artifactId);
if (!freshAsset || freshAsset.companyId !== asset.companyId || freshAsset.objectKey !== asset.objectKey || freshAsset.byteSize !== input.byteSize || freshAsset.sha256 !== input.sha256
|| !(await canActorReadAssetContent(this.db, { ...this.#privacyActor(current.run), keyScope: this.#apiScope(current) }, freshAsset))) throw forbidden("Artifact is not available to this actor");
@@ -1279,7 +1281,7 @@ export class PaperclipRunnerToolAuthority {
if (!this.#imageGenerationAdvertised(current.issue.workMode)) throw forbidden("Image generation is unavailable to this run or provider");
const decision = await authorizationService(this.db).decide({ actor: this.#privacyActor(current.run), action: "issue:mutate",
resource: { type: "issue", companyId: this.binding.companyId, issueId: current.issue.id } });
if (!decision.allowed) throw forbidden(decision.explanation);
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
// #boundContext checks company and agent budgets; spending also needs the task's project.
if (current.issue.projectId && await budgetServiceInTransaction(this.db).getInvocationBlock(this.binding.companyId, this.binding.agentId,
{ issueId: current.issue.id, projectId: current.issue.projectId })) throw forbidden("Company or budget authority unavailable");
@@ -1940,7 +1942,10 @@ export class PaperclipRunnerToolAuthority {
type: "issue", companyId: this.binding.companyId, issueId: parent.id, projectId: parent.projectId,
parentIssueId: parent.parentId, assigneeAgentId: parent.assigneeAgentId, assigneeUserId: parent.assigneeUserId, status: parent.status,
}, scope: { issueId: parent.id, projectId: parent.projectId, parentIssueId: parent.parentId } });
if (!decision.allowed) return decision.explanation;
if (!decision.allowed) {
if (decision.interactionDenial) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
return decision.explanation;
}
}
return null;
};
@@ -2014,7 +2019,7 @@ export class PaperclipRunnerToolAuthority {
resource: { type: "issue", companyId: this.binding.companyId, ...scope },
scope,
});
if (!decision.allowed) throw forbidden(decision.explanation);
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
if (assigneeAgentId) await assertAssignableAgent(tx, this.binding.companyId, assigneeAgentId, { kind: "work" });
if (assigneeUserId) await this.#assertCompanyPerson(tx, assigneeUserId);
const project = projectId
@@ -2231,7 +2236,7 @@ export class PaperclipRunnerToolAuthority {
parentIssueId: target.parentId, assigneeAgentId: action === "tasks:assign" ? assigneeAgentId : target.assigneeAgentId,
assigneeUserId: action === "tasks:assign" ? assigneeUserId : target.assigneeUserId, status: target.status,
}, scope: { issueId: taskId, projectId: target.projectId, parentIssueId: target.parentId, assigneeAgentId, assigneeUserId } });
if (!decision.allowed) throw forbidden(decision.explanation);
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
if (assigneeAgentId) await assertAssignableAgent(tx, this.binding.companyId, assigneeAgentId, { kind: "work" });
if (assigneeUserId) await this.#assertCompanyPerson(tx, assigneeUserId);
@@ -2250,6 +2255,13 @@ export class PaperclipRunnerToolAuthority {
throw new Error("paperclip_runner_reassignment_conflict: refresh search_tasks before deciding again");
}
};
const assertReassignmentComment = async (tx: Db, target: typeof issues.$inferSelect) => {
if (target.assigneeAgentId === assigneeAgentId && target.assigneeUserId === assigneeUserId) return;
await assertAgentInteraction(tx, { companyId: this.binding.companyId, actorAgentId: this.binding.agentId,
operation: "comment", issueId: taskId, texts: [reason], lock: true });
await assertAgentInteraction(tx, { companyId: this.binding.companyId, actorAgentId: this.binding.agentId,
operation: "comment", targetAgentId: assigneeAgentId, delivery: true, lock: true });
};
// Stop outside row locks: the runtime needs those locks to acknowledge cancellation.
// A second locked check below prevents any intervening ownership/version change.
const prepared = receiptOnly ? null : await this.db.transaction(async (tx) => {
@@ -2258,6 +2270,7 @@ export class PaperclipRunnerToolAuthority {
const target = await authorize(tx as unknown as Db, context.run);
if (await priorReceipt(tx as unknown as Db)) return null;
validate(target);
await assertReassignmentComment(tx as unknown as Db, target);
return target;
});
// Cancellation and ownership commit cannot share locks. If the second
@@ -2319,6 +2332,7 @@ export class PaperclipRunnerToolAuthority {
if (run && ["running", "queued", "scheduled_retry"].includes(run.status)) throw new Error("paperclip_runner_reassignment_stop_unconfirmed");
}
const changed = target.assigneeAgentId !== assigneeAgentId || target.assigneeUserId !== assigneeUserId;
await assertReassignmentComment(tx, target);
const updated = changed ? await issueService(tx).update(taskId, {
companyGuard: this.binding.companyId, assigneeAgentId, assigneeUserId,
status: target.status === "in_progress" ? "todo" : target.status,
@@ -2420,7 +2434,7 @@ export class PaperclipRunnerToolAuthority {
type: "issue", companyId: this.binding.companyId, issueId: target.id,
status: target.status, assigneeAgentId: target.assigneeAgentId, assigneeUserId: target.assigneeUserId,
} });
if (!decision.allowed) throw forbidden(decision.explanation);
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
await assertCanManageIssueMonitor(access, { actor }, target.companyId, target.assigneeAgentId, true);
if (target.assigneeAgentId !== this.binding.agentId || target.assigneeUserId ||
@@ -3070,6 +3084,7 @@ export class PaperclipRunnerToolAuthority {
};
return this.db.transaction(async tx => {
if (operationId === "create_task") {
await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, this.binding.companyId)).for("no key update");
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`issue-privacy-tree:${this.binding.companyId}`}, 0))`);
}
return mutate(tx);
@@ -3133,7 +3148,7 @@ export class PaperclipRunnerToolAuthority {
projectId: context.issue.projectId, parentIssueId: context.issue.parentId,
status: context.issue.status, assigneeAgentId: context.issue.assigneeAgentId, assigneeUserId: context.issue.assigneeUserId },
});
if (!decision.allowed) throw forbidden(decision.explanation);
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
await this.binding.assertBridgeAuthority?.(tx);
}
await assertNoCaseHandoffMutation(tx, this.binding.runId, this.binding.issueId);
@@ -1,4 +1,7 @@
import { notifyNativeStatusWakeWork } from "../deferred-execution-notifications.js";
import { assertAgentInteraction } from "../agent-interaction-policy.js";
import { forbidden, HttpError } from "../../errors.js";
import { agentInteractionDeliveryDenial, agentWakeInteractionTexts, INTERACTION_DELIVERY_DENIED, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js";
import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js";
import { lockCurrentNativeWorkAssessmentEvidence } from "./work-assessments.js";
import { hasNativeWorkspaceFinalizationOwner } from "./native-workspace-finalization-recovery-state.js";
@@ -25,7 +28,7 @@ import { readNativePlanWait, type NativePlanWaitSource } from "./native-plan-wai
import { activeIssueInteractionCondition } from "../issue-question-context.js";
import { isConversation } from "../agent-conversations.js";
import { hasPendingNativeChildCompletion, type NativeChildCompletionRecipient } from "./native-child-completion-delivery.js";
import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm";
import { and, asc, desc, eq, inArray, notInArray, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import type { CreateIssueThreadInteraction } from "@paperclipai/shared";
import {
@@ -208,6 +211,7 @@ export type NativeMaterializedStatusEffect = {
targetType: string;
targetId: string | null;
payload: Record<string, unknown>;
deliveryState?: "skipped";
};
function record(value: unknown): Record<string, unknown> {
@@ -463,6 +467,8 @@ async function enqueueWake(input: {
idempotencyKey: string;
payload: Record<string, unknown>;
contextSnapshot?: Record<string, unknown>;
originRunId?: string;
originOperation?: "assign" | "comment";
}) {
const existing = await input.tx
.select({ id: agentWakeupRequests.id })
@@ -471,18 +477,32 @@ async function enqueueWake(input: {
and(
eq(agentWakeupRequests.companyId, input.companyId),
eq(agentWakeupRequests.idempotencyKey, input.idempotencyKey),
inArray(agentWakeupRequests.status, [
or(inArray(agentWakeupRequests.status, [
"queued",
"deferred_issue_execution",
"claimed",
"completed",
]),
]), eq(agentWakeupRequests.error, INTERACTION_DELIVERY_DENIED)),
),
)
.limit(1)
.then((rows) => rows[0] ?? null);
if (existing) return existing.id;
await notifyNativeStatusWakeWork(input.tx, { companyId: input.companyId });
const [origin] = input.originRunId ? await input.tx.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, input.originRunId), eq(heartbeatRuns.companyId, input.companyId))) : [];
const actorType = origin ? "agent" : "system";
const actorId = origin?.agentId ?? "native-status-committer";
const originPayload = withInteractionDeliveryOrigin({}, actorType, actorId, { actorType, actorId });
if (originPayload.interactionOrigin) {
originPayload.interactionOrigin = { ...record(originPayload.interactionOrigin), operation: input.originOperation ?? "assign" };
}
const denial = origin ? await agentInteractionDeliveryDenial(input.tx, {
companyId: input.companyId, actorAgentId: origin.agentId, targetAgentId: input.agentId, issueId: input.issueId,
operation: input.originOperation ?? "assign", texts: agentWakeInteractionTexts(input.payload), delivery: true, lock: true,
}) : null;
const refusedParentReport = denial && input.reason === "issue_children_completed" && input.originOperation === "comment";
if (denial && !refusedParentReport) throw forbidden("Agent interaction is not permitted.", denial);
if (!denial) await notifyNativeStatusWakeWork(input.tx, { companyId: input.companyId });
const inserted = await input.tx
.insert(agentWakeupRequests)
.values({
@@ -491,10 +511,18 @@ async function enqueueWake(input: {
source: "automation",
triggerDetail: "system",
reason: input.reason,
payload: {
...(denial ? { status: "skipped", error: INTERACTION_DELIVERY_DENIED, finishedAt: new Date() } : {}),
payload: denial ? {
issueId: input.issueId,
taskId: input.issueId,
sourceRunId: input.originRunId,
...originPayload,
interactionPermissionDenials: { assignment: denial },
} : {
issueId: input.issueId,
taskId: input.issueId,
...input.payload,
...originPayload,
_paperclipWakeContext: {
issueId: input.issueId,
taskId: input.issueId,
@@ -514,6 +542,13 @@ async function enqueueWake(input: {
return inserted.id;
}
async function refusedWakePolicy(tx: Db, companyId: string, wakeId: string) {
const [wake] = await tx.select({ error: agentWakeupRequests.error, payload: agentWakeupRequests.payload })
.from(agentWakeupRequests).where(and(eq(agentWakeupRequests.id, wakeId), eq(agentWakeupRequests.companyId, companyId)));
return wake?.error === INTERACTION_DELIVERY_DENIED
? record(record(wake.payload).interactionPermissionDenials).assignment : null;
}
async function validateGovernanceGate(
tx: Db,
input: {
@@ -578,6 +613,7 @@ async function materializeDecisionEffect(input: {
companyId: string;
issue: typeof issues.$inferSelect;
runId: string;
actorAgentId: string | null;
decisionId: string;
effect: NativeStatusEffect;
failpoint?: NativeStatusCommitFailpoint;
@@ -625,7 +661,7 @@ async function materializeDecisionEffect(input: {
],
},
},
{ systemId: "native-status-committer", runId: input.runId },
{ agentId: input.actorAgentId, systemId: "native-status-committer", runId: input.runId },
);
return {
effectKind: effect.kind,
@@ -673,7 +709,8 @@ async function materializeDecisionEffect(input: {
const interaction = await issueThreadInteractionService(input.tx).create(
input.issue,
reviewInput,
{ systemId: "native-status-committer", runId: input.runId },
{ agentId: input.actorAgentId, systemId: "native-status-committer", runId: input.runId },
{ supersedePendingSiblingInteractions: false },
);
// The card and its next actor commit together. The post-commit dispatcher
// revalidates this exact review before granting a scoped reviewer run.
@@ -684,6 +721,7 @@ async function materializeDecisionEffect(input: {
const reviewerWakeId = effect.ownerAgentId && interaction.effectiveResolverPolicy !== "human_only"
? await enqueueWake({
tx: input.tx,
originRunId: input.runId,
companyId: input.companyId,
issueId: input.issue.id,
agentId: effect.ownerAgentId,
@@ -709,6 +747,7 @@ async function materializeDecisionEffect(input: {
if (effect.kind === "notify_owner") {
const wakeId = await enqueueWake({
tx: input.tx,
originRunId: input.runId,
companyId: input.companyId,
issueId: input.issue.id,
agentId: effect.agentId,
@@ -736,7 +775,7 @@ async function materializeDecisionEffect(input: {
status: "todo",
priority: input.issue.priority,
assigneeAgentId: effect.agentId,
createdByAgentId: input.issue.assigneeAgentId,
createdByAgentId: input.actorAgentId,
workMode: "standard",
idempotencyKey: `native-delegation:${input.decisionId}`,
inheritExecutionWorkspaceFromIssueId: input.issue.id,
@@ -786,6 +825,7 @@ async function materializeDecisionEffect(input: {
if (effect.continuationKind === "monitor") throw new Error("Monitor delivery belongs to the issue monitor scheduler");
const wakeId = await enqueueWake({
tx: input.tx,
originRunId: input.runId,
companyId: input.companyId,
issueId: input.issue.id,
agentId: effect.agentId,
@@ -810,6 +850,9 @@ async function materializeDecisionEffect(input: {
}
if (effect.kind === "bind_blocker") {
failAt("blocker_materialization", input.failpoint);
await assertAgentInteraction(input.tx, { companyId: input.companyId, actorAgentId: input.actorAgentId,
operation: "assign", issueId: input.issue.id, targetAgentId: typeof effect.owner === "object" ? effect.owner.agentId : null,
texts: [effect.action], lock: true });
const [bound] = await input.tx
.update(issues)
.set({
@@ -828,6 +871,7 @@ async function materializeDecisionEffect(input: {
if (effect.owner !== "board") {
wakeId = await enqueueWake({
tx: input.tx,
originRunId: input.runId,
companyId: input.companyId,
issueId: input.issue.id,
agentId: effect.owner.agentId,
@@ -863,6 +907,7 @@ async function materializeDecisionEffect(input: {
agentId: effect.agentId,
reason: "issue_status_changed",
idempotencyKey: `native-status:${input.decisionId}:retry`,
originRunId: input.runId,
payload: {
nativeDecisionId: input.decisionId,
retryCause: effect.cause,
@@ -1677,6 +1722,10 @@ export async function commitNativeStatusDecision(input: {
.then((rows) => rows[0] ?? null);
if (!coordinator)
throw new Error("native_finalization_coordinator_missing");
if (coordinator.failureCode === "agent_interaction_denied") {
throw forbidden("This native interaction was permanently refused by agent permissions.",
record(record(coordinator.failureDetail).interactionDenial));
}
const issue = await tx
.select()
.from(issues)
@@ -1690,6 +1739,8 @@ export async function commitNativeStatusDecision(input: {
.limit(1)
.then((rows) => rows[0] ?? null);
if (!issue) throw new NativeStatusRaceError();
const [originRun] = await tx.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)));
if (input.requireReassessmentSource) {
const expected = input.requireReassessmentSource;
const now = Date.now();
@@ -2260,6 +2311,7 @@ export async function commitNativeStatusDecision(input: {
issue,
runId: input.runId,
decisionId: decisionRow.id,
actorAgentId: originRun?.agentId ?? null,
effect,
failpoint: input.failpoint,
preMaterializedEffects,
@@ -2291,7 +2343,7 @@ export async function commitNativeStatusDecision(input: {
statusVersion: input.priorStatusVersion + 1,
lastStatusDecisionId: decisionRow.id,
unblockDescriptor: input.decision.unblockDescriptor,
actorAgentId: null,
actorAgentId: originRun?.agentId ?? null,
actorUserId: null,
},
tx,
@@ -2400,6 +2452,8 @@ export async function commitNativeStatusDecision(input: {
: null;
const wakeId = await enqueueWake({
tx: tx as unknown as Db,
originRunId: isCompletedChildParent ? input.runId : undefined,
originOperation: isCompletedChildParent ? "comment" : undefined,
companyId: input.companyId,
issueId: dependent.id,
agentId: dependent.assigneeAgentId,
@@ -2414,22 +2468,35 @@ export async function commitNativeStatusDecision(input: {
},
contextSnapshot: childCompletionContext ?? undefined,
});
const reportDenial = isCompletedChildParent ? await refusedWakePolicy(tx as unknown as Db, input.companyId, wakeId) : null;
materialized.push({
effectKind: isCompletedChildParent
? "parent_dependency_wake"
: "dependency_wake",
targetType: "agent_wakeup_request",
targetId: wakeId,
...(reportDenial ? { deliveryState: "skipped" as const } : {}),
payload: {
dependentIssueId: dependent.id,
resolvedBlockerIssueId: input.issueId,
...(childCompletionContext ?? {}),
...(reportDenial ? { interactionPermissionDenials: { assignment: reportDenial } } : childCompletionContext ?? {}),
},
});
if (reportDenial) {
const dependencyWakeId = await enqueueWake({ tx: tx as unknown as Db, companyId: input.companyId,
issueId: dependent.id, agentId: dependent.assigneeAgentId, reason: "issue_blockers_resolved",
idempotencyKey: buildIssueBlockersResolvedWakeIdempotencyKey({ dependentIssueId: dependent.id, resolvedBlockerIssueId: input.issueId }),
payload: { resolvedBlockerIssueId: input.issueId, blockerIssueIds: dependent.blockerIssueIds },
});
materialized.push({ effectKind: "dependency_wake", targetType: "agent_wakeup_request", targetId: dependencyWakeId,
payload: { dependentIssueId: dependent.id, resolvedBlockerIssueId: input.issueId } });
}
}
if (parent && !parentIsDependent) {
const wakeId = await enqueueWake({
tx: tx as unknown as Db,
originRunId: input.runId,
originOperation: "comment",
companyId: input.companyId,
issueId: parent.id,
agentId: parent.assigneeAgentId,
@@ -2452,17 +2519,21 @@ export async function commitNativeStatusDecision(input: {
childIssueSummaryTruncated: parent.childIssueSummaryTruncated,
},
});
const reportDenial = await refusedWakePolicy(tx as unknown as Db, input.companyId, wakeId);
materialized.push({
effectKind: "parent_wake",
targetType: "agent_wakeup_request",
targetId: wakeId,
...(reportDenial ? { deliveryState: "skipped" as const } : {}),
payload: {
parentIssueId: parent.id,
completedChildIssueId: input.issueId,
...childCompletionDelivery,
childIssueSummaries: parent.childIssueSummaries,
onboardingCompletion: parent.onboardingCompletion,
childIssueSummaryTruncated: parent.childIssueSummaryTruncated,
...(reportDenial ? { interactionPermissionDenials: { assignment: reportDenial } } : {
childIssueSummaries: parent.childIssueSummaries,
onboardingCompletion: parent.onboardingCompletion,
childIssueSummaryTruncated: parent.childIssueSummaryTruncated,
}),
},
});
}
@@ -2481,9 +2552,10 @@ export async function commitNativeStatusDecision(input: {
targetId: effect.targetId,
idempotencyKey: `native-status:${decisionRow.id}:${index + 1}`,
payload: effect.payload,
deliveryState: "delivered",
deliveryState: effect.deliveryState ?? "delivered",
attemptCount: 1,
deliveredAt: new Date(),
deliveredAt: effect.deliveryState === "skipped" ? null : new Date(),
lastError: effect.deliveryState === "skipped" ? INTERACTION_DELIVERY_DENIED : null,
})
.onConflictDoNothing();
}
@@ -2540,6 +2612,22 @@ export async function commitNativeStatusDecision(input: {
issue: updated,
replayed: false,
};
}).catch(async (error: unknown) => {
if (error instanceof HttpError && error.status === 403 && record(error.details).code === "agent_interaction_denied") {
await input.db.transaction(async tx => {
const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.runId, input.runId), eq(nativeRunFinalizations.companyId, input.companyId),
eq(nativeRunFinalizations.issueId, input.issueId))).for("update");
if (!coordinator || coordinator.phase === "committed" || coordinator.failureCode === "agent_interaction_denied") return;
await notifyNativeFinalizationWork(tx, { companyId: input.companyId, runId: input.runId });
await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", failureCode: "agent_interaction_denied",
failureDetail: { ...record(coordinator.failureDetail), interactionDenial: error.details,
recoveryOwner: { kind: "none", reason: "agent_interaction_denied" } },
nextAttemptAt: null, leaseOwner: null, leaseExpiresAt: null, updatedAt: new Date() })
.where(and(eq(nativeRunFinalizations.runId, input.runId), eq(nativeRunFinalizations.companyId, input.companyId)));
});
}
throw error;
});
for (const publication of publications) publishActivity(publication);
@@ -1,5 +1,5 @@
import { notifyAttentionRetentionWork } from "../retention-work-notifications.js";
import { and, eq, isNull, ne, sql } from "drizzle-orm";
import { and, eq, isNull, ne, or, sql } from "drizzle-orm";
import { completionContracts, heartbeatRuns, issues, issueThreadInteractions, statusDecisionEffects, statusDecisions, workAssessments, type Db } from "@paperclipai/db";
import { hasPublishedGitHubReview } from "../chat-channels/github/review-wait.js";
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
@@ -47,7 +47,8 @@ export async function findSupersededExternalReviewRequests(db: Db, binding: Revi
eq(issueThreadInteractions.companyId, binding.companyId), eq(issueThreadInteractions.issueId, binding.issueId),
eq(issueThreadInteractions.status, "pending"), eq(issueThreadInteractions.kind, "request_confirmation"),
ne(issueThreadInteractions.sourceRunId, binding.runId),
isNull(issueThreadInteractions.createdByAgentId), isNull(issueThreadInteractions.createdByUserId),
or(isNull(issueThreadInteractions.createdByAgentId), eq(issueThreadInteractions.createdByAgentId, heartbeatRuns.agentId)),
isNull(issueThreadInteractions.createdByUserId),
isNull(issueThreadInteractions.addresseeAgentId), eq(issueThreadInteractions.effectiveResolverPolicy, "human_only"),
sql`exists (select 1 from jsonb_array_elements(${statusDecisions.decisionJson}->'effects') effect
where effect->>'kind' = 'bind_reviewer'
@@ -2,6 +2,7 @@ import { and, asc, eq, inArray, isNotNull, or, sql } from "drizzle-orm";
import { heartbeatRunEvents, issueComments, issueThreadInteractions, type Db } from "@paperclipai/db";
import { unreadSteeredMessageIds } from "../../vendor/paperclip-runner/index.js";
import { queuedInteractionSteeringBody } from "../queued-interaction-response.js";
import { filterRunMessageInteractionDelivery } from "../agent-interaction-delivery.js";
const kind = sql<string | null>`${heartbeatRunEvents.payload}->'prpEvent'->'payload'->>'kind'`;
@@ -38,6 +39,7 @@ export async function readUnreadSteeredMessages(
if (ids.length === 0) return [];
const uuids = ids.filter((id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id));
if (uuids.length === 0) return [];
const allowedIds = await filterRunMessageInteractionDelivery(db, { ...input, commentIds: uuids });
const texts = new Map<string, string>();
const comments = await db
.select({ id: issueComments.id, body: issueComments.body })
@@ -62,6 +64,7 @@ export async function readUnreadSteeredMessages(
for (const interaction of interactions) texts.set(interaction.id, queuedInteractionSteeringBody(interaction));
}
return ids.flatMap((id) => {
if (!allowedIds.has(id)) return [];
const text = texts.get(id);
return text === undefined ? [] : [{ id, text }];
});