From 280dad5e3905612cbb2109d631aa1bfa9414429d Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 20:09:34 -0500 Subject: [PATCH] Preserve agent approvals across preparation failures Share the undispatched claim-release and dispatch ownership boundary with Test-tab actions. Keep provider execution and uncertain outcomes outside preparation retry; verify real PostgreSQL timeout, competing claim, and no-replay behavior. Co-Authored-By: Paperclip --- doc/idle-approved-tool-recovery.md | 41 ++- .../__tests__/tool-gateway-service.test.ts | 111 +++++- ...approval.ts => tool-approval-execution.ts} | 17 +- server/src/services/tool-gateway.ts | 339 ++++++++---------- 4 files changed, 308 insertions(+), 200 deletions(-) rename server/src/services/{tool-test-approval.ts => tool-approval-execution.ts} (86%) diff --git a/doc/idle-approved-tool-recovery.md b/doc/idle-approved-tool-recovery.md index 5f1831a3ca2..7ac8c4f4e3b 100644 --- a/doc/idle-approved-tool-recovery.md +++ b/doc/idle-approved-tool-recovery.md @@ -124,7 +124,7 @@ and invocation were saved as failed, so approved recovery could not retry them. The preparation boundary now distinguishes explicit validation/access rejections from unexpected dependency errors and transient HTTP errors. The existing -`tool-test-approval` owner releases only its exact claim: invocation and request +`tool-approval-execution` owner releases only its exact claim: invocation and request are locked in the established order, their link/company/claim timestamp must match, and the invocation must still await approval with no recorded start. The request returns to `approved` with a transaction-aware notification. Signed @@ -148,3 +148,42 @@ All 117 gateway-service cases pass on the owning slice, including existing targe invalidation, provider-outcome persistence failures and unknown-outcome no-replay cases. Integrated consumer checks, workspace verification and remote PR gates must still be recorded after propagation. + + +## Agent-origin preparation and dispatch ownership + +Agent-origin approvals use the same pre-dispatch retry contract as Test-tab +approvals. Previously, a policy or identity dependency failure after claiming an +approved action permanently failed it; earlier issue/signing failures could +leave the claim executing. Preparation now has one owning error boundary around +issue, signature, identity, target, policy, managed-argument, and content checks. +Validation and nontransient access rejections retain their terminal handling. +Unexpected dependency failures and transient HTTP errors release only the exact, +still-undispatched claim to the existing approved queue and publish its existing +transactional work signal. No table, maintenance scan, or retry wrapper per +producer is added. + +`tool-approval-execution.ts` owns the shared claim token, release, and dispatch +transition. Its Test-tab claim/outcome functions remain specific to that consumer. +Both origins use the same invocation-then-request locks and verify invocation, +company, request linkage, claim timestamp, awaiting-approval state, and absence +of an earlier start before dispatch. An agent that loses its claim during +preparation cannot call the provider or overwrite its successor. The Test-tab +unapproved direct-call path retains its original behavior. + +Only preparation is retryable here. Recording the invocation start, provider +execution, and outcome persistence remain outside that catch. A provider error, +unknown outcome, or failed durable release does not establish replay safety. +Existing interruption handling remains the conservative fallback. Closed-issue +expiry, signature/target invalidation, identity authority, and policy rejection +remain enforced, including the final issue check before recording dispatch. + +Real PostgreSQL lock-timeout cases cover foreground approval and recovery: +observe the committed executing claim, block the policy read, then require the +same signed request to remain approved with no invocation start and zero provider +calls. Recovery after releasing the table lock executes once and becomes quiet. +A separate contention case replaces the claim while preparation is blocked and +proves the old owner cannot dispatch; the surviving approval later executes once. +A provider-error case proves that an already-started call is not requeued as a +preparation failure. The existing Test-tab timeout and ownership cases exercise +the other consumer of the shared boundary. diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index aa87ae5e671..e762f6d00c0 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -43,7 +43,7 @@ import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity import { issueService } from "../services/issues.js"; import { approvalService } from "../services/approvals.js"; import { commitToolActionReview } from "../services/tool-action-review.js"; -import { claimToolTestApproval, releaseToolTestApproval, startToolTestInvocation } from "../services/tool-test-approval.js"; +import { claimToolTestApproval, releaseToolApproval, startToolInvocation } from "../services/tool-approval-execution.js"; import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js"; import { toolActionDeliveryService } from "../services/tool-action-delivery.js"; import { secretService } from "../services/secrets.js"; @@ -675,19 +675,118 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(remoteCall.provider).toHaveBeenCalledOnce(); }, 15_000); + async function agentRequest(provider: NonNullable) { + const remote = await createRemoteMcpToolFixture(db, fixture.company.id); + await db.update(toolCatalogEntries).set({ isReadOnly: false, riskLevel: "write" }) + .where(eq(toolCatalogEntries.id, remote.catalogEntry.id)); + await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "Review agent writes", + policyType: "require_approval", selectors: { connectionId: remote.connection.id } }); + gateway = createTestToolGatewayService(db, { remoteHttpRequest: provider }); + const session = await gateway.createSession(runSessionInput(fixture.company, fixture.agent, fixture.run)); + const tool = (await gateway.listToolsForSession(session.token)).find(t => t.connectionId === remote.connection.id)!; + await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { value: "reviewed" } })) + .rejects.toMatchObject({ reasonCode: "approval_required" }); + const [pending] = await db.select().from(toolActionRequests); + return pending; + } + + it.each(["foreground", "recovery"] as const)("retries an agent-origin %s approval after a real pre-dispatch database timeout", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const pending = await agentRequest(remoteCall.provider); await approve(pending); + const preparationDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { + maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0, + }); + const preparingGateway = createTestToolGatewayService(preparationDb, { remoteHttpRequest: remoteCall.provider }); + let unlock!: () => void, locked!: () => void; + const gate = new Promise(resolve => { unlock = resolve; }); + const acquired = new Promise(resolve => { locked = resolve; }); + const lock = db.transaction(async tx => { + await tx.execute(sql`lock table tool_policies in access exclusive mode`); + locked(); await gate; + }); + await acquired; + try { + await preparationDb.execute(sql`set lock_timeout = '2s'`); + const attempting = mode === "foreground" + ? preparingGateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }) + : preparingGateway.recoverApprovedActionReviews(fixture.company.id); + // Observe the real committed claim while its subsequent policy read + // is blocked. Provider execution has not started. + void attempting.catch(() => undefined); + await vi.waitFor(async () => { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + }); + if (mode === "foreground") expect(await attempting).toMatchObject({ status: "approved" }); + else expect(await attempting).toEqual({ scanned: 1, retry: true }); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]) + .toMatchObject({ status: "approved", signedArguments: pending.signedArguments }); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "awaiting_approval", startedAt: null }); + expect(remoteCall.provider).not.toHaveBeenCalled(); + } finally { unlock(); await lock; await preparationDb.$client.end({ timeout: 1 }); } + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }, 15_000); + + it("refuses agent dispatch after preparation loses its claim", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const pending = await agentRequest(remoteCall.provider); await approve(pending); + let unlock!: () => void, locked!: () => void; + const gate = new Promise(resolve => { unlock = resolve; }); + const acquired = new Promise(resolve => { locked = resolve; }); + const lock = db.transaction(async tx => { + await tx.execute(sql`lock table tool_policies in access exclusive mode`); + locked(); await gate; + }); + await acquired; + const attempting = gateway.approveActionRequest({ companyId: fixture.company.id, + actionRequestId: pending.id, actor: { userId: "board" } }); + void attempting.catch(() => undefined); + let successor!: NonNullable>>; + try { + await vi.waitFor(async () => { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + }); + const [claimed] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)); + expect(await releaseToolApproval(db, { actionRequestId: pending.id, + invocationId: pending.invocationId, claimedAt: claimed.updatedAt })).toBe(true); + await vi.advanceTimersByTimeAsync(10); + successor = (await claimToolTestApproval(db, pending.id, pending.invocationId))!; + expect(successor).not.toBeNull(); + expect(successor.claimedAt.getTime()).toBeGreaterThan(claimed.updatedAt.getTime()); + } finally { unlock(); await lock; } + expect(await attempting).toMatchObject({ status: "executing" }); + expect(remoteCall.provider).not.toHaveBeenCalled(); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "awaiting_approval", startedAt: null }); + expect(await releaseToolApproval(db, successor)).toBe(true); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }); + + it("does not retry an agent provider error as a preparation failure", async () => { + const provider = vi.fn(async () => { throw new Error("Provider outcome is unknown"); }); + const pending = await agentRequest(provider); await approve(pending); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("failed"); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0].startedAt).not.toBeNull(); + await startRecovery(); await quiet(); + expect(provider).toHaveBeenCalledOnce(); + }); + it.each(["started", "reclaimed", "mismatched", "prior_dispatch"] as const)("refuses to release a Test-tab preparation claim with %s ownership evidence", async state => { const remoteCall = providerFixture(); remoteCall.release(); const { pending } = await testRequest(remoteCall.provider); await approve(pending); const claim = await claimToolTestApproval(db, pending.id, pending.invocationId); expect(claim).not.toBeNull(); - if (state === "started") expect(await startToolTestInvocation(db, pending.invocationId, claim!)).toBe(true); + if (state === "started") expect(await startToolInvocation(db, pending.invocationId, claim!)).toBe(true); if (state === "reclaimed") await db.update(toolActionRequests) .set({ updatedAt: new Date(claim!.claimedAt.getTime() + 1000) }).where(eq(toolActionRequests.id, pending.id)); if (state === "prior_dispatch") await db.update(toolInvocations) .set({ startedAt: new Date() }).where(eq(toolInvocations.id, pending.invocationId)); const beforeRequest = (await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]; const beforeInvocation = (await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]; - expect(await releaseToolTestApproval(db, state === "mismatched" ? { ...claim!, invocationId: randomUUID() } : claim!)).toBe(false); + expect(await releaseToolApproval(db, state === "mismatched" ? { ...claim!, invocationId: randomUUID() } : claim!)).toBe(false); expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]).toEqual(beforeRequest); expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]).toEqual(beforeInvocation); expect(remoteCall.provider).not.toHaveBeenCalled(); @@ -699,12 +798,12 @@ describeEmbeddedPostgres("tool gateway service", () => { const claim = await claimToolTestApproval(db, pending.id, pending.invocationId); expect(claim).not.toBeNull(); await expect(db.transaction(async tx => { - expect(await releaseToolTestApproval(tx as unknown as typeof db, claim!)).toBe(true); + expect(await releaseToolApproval(tx as unknown as typeof db, claim!)).toBe(true); throw new Error("release rollback"); })).rejects.toThrow("release rollback"); expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); - expect(await releaseToolTestApproval(db, claim!)).toBe(true); - expect(await startToolTestInvocation(db, pending.invocationId, claim!)).toBe(false); + expect(await releaseToolApproval(db, claim!)).toBe(true); + expect(await startToolInvocation(db, pending.invocationId, claim!)).toBe(false); await startRecovery(); await settle(); await executed(pending); await quiet(); expect(remoteCall.provider).toHaveBeenCalledOnce(); }); diff --git a/server/src/services/tool-test-approval.ts b/server/src/services/tool-approval-execution.ts similarity index 86% rename from server/src/services/tool-test-approval.ts rename to server/src/services/tool-approval-execution.ts index da78f5d722d..be0b44a34ec 100644 --- a/server/src/services/tool-test-approval.ts +++ b/server/src/services/tool-approval-execution.ts @@ -3,7 +3,7 @@ import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; import type { ToolRedactedValueSummary } from "@paperclipai/shared"; import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; -export type ToolTestApprovalClaim = { actionRequestId: string; invocationId: string; claimedAt: Date }; +export type ToolApprovalClaim = { actionRequestId: string; invocationId: string; claimedAt: Date }; export type ToolTestOutcome = { status: "succeeded" | "failed" | "timed_out" | "rate_limited"; result?: ToolRedactedValueSummary; @@ -11,7 +11,7 @@ export type ToolTestOutcome = { errorMessage?: string; }; -export async function claimToolTestApproval(db: Db, actionRequestId: string, invocationId: string): Promise { +export async function claimToolTestApproval(db: Db, actionRequestId: string, invocationId: string): Promise { return db.transaction(async tx => { const [invocation] = await tx.select().from(toolInvocations) .where(eq(toolInvocations.id, invocationId)).for("update"); @@ -37,7 +37,7 @@ export async function claimToolTestApproval(db: Db, actionRequestId: string, inv } /** Return only this still-undispatched claim to its existing approval queue. */ -export async function releaseToolTestApproval(db: Db, claim: ToolTestApprovalClaim) { +export async function releaseToolApproval(db: Db, claim: ToolApprovalClaim) { return db.transaction(async tx => { const [invocation] = await tx.select().from(toolInvocations) .where(eq(toolInvocations.id, claim.invocationId)).for("update"); @@ -54,7 +54,7 @@ export async function releaseToolTestApproval(db: Db, claim: ToolTestApprovalCla }); } -export async function startToolTestInvocation(db: Db, invocationId: string, claim?: ToolTestApprovalClaim) { +export async function startToolInvocation(db: Db, invocationId: string, claim?: ToolApprovalClaim) { const now = new Date(); if (!claim) { await db.update(toolInvocations).set({ status: "executing", startedAt: now, updatedAt: now }) @@ -62,19 +62,20 @@ export async function startToolTestInvocation(db: Db, invocationId: string, clai return true; } return db.transaction(async tx => { - const [invocation] = await tx.select({ status: toolInvocations.status }).from(toolInvocations) + const [invocation] = await tx.select().from(toolInvocations) .where(eq(toolInvocations.id, invocationId)).for("update"); const [request] = await tx.select().from(toolActionRequests) .where(eq(toolActionRequests.id, claim.actionRequestId)).for("update"); - if (invocation?.status !== "awaiting_approval" || request?.status !== "executing" || + if (invocationId !== claim.invocationId || invocation?.status !== "awaiting_approval" || invocation.startedAt !== null || + request?.status !== "executing" || request.invocationId !== invocationId || request.companyId !== invocation.companyId || request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false; - await tx.update(toolInvocations).set({ status: "executing", startedAt: now, updatedAt: now }) + await tx.update(toolInvocations).set({ status: "executing", approvalState: "approved", startedAt: now, updatedAt: now }) .where(eq(toolInvocations.id, invocationId)); return true; }); } -export async function persistToolTestOutcome(db: Db, invocationId: string, outcome: ToolTestOutcome, claim?: ToolTestApprovalClaim) { +export async function persistToolTestOutcome(db: Db, invocationId: string, outcome: ToolTestOutcome, claim?: ToolApprovalClaim) { const now = new Date(); const values = { status: outcome.status, ...(outcome.result ? { resultHash: outcome.result.sha256 ?? null, resultSummary: outcome.result, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index c24cc956df5..18bf0741338 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,4 +1,4 @@ -import { claimToolTestApproval, releaseToolTestApproval, persistToolTestOutcome, startToolTestInvocation, type ToolTestApprovalClaim } from "./tool-test-approval.js"; +import { claimToolTestApproval, releaseToolApproval, persistToolTestOutcome, startToolInvocation, type ToolApprovalClaim } from "./tool-approval-execution.js"; import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; import { toolReviewExpiryService } from "./tool-review-expiry.js"; import { writeToolReviewChange } from "./tool-review-work-notifications.js"; @@ -7418,7 +7418,7 @@ export function createToolGatewayService( matchedPolicyIds: string[]; timeoutMs?: number; signal?: AbortSignal; - approvedClaim?: ToolTestApprovalClaim; + approvedClaim?: ToolApprovalClaim; }): Promise< | { decision: "allowed"; invocationId: string; result: unknown } | { @@ -7427,7 +7427,7 @@ export function createToolGatewayService( error: { message: string; reasonCode: string }; } > { - if (!(await startToolTestInvocation(db, args.invocationId, args.approvedClaim))) { + if (!(await startToolInvocation(db, args.invocationId, args.approvedClaim))) { throw new ToolGatewayHttpError(409, "Tool action execution claim is no longer current", "action_already_consumed"); } await writeAudit({ @@ -7624,6 +7624,12 @@ export function createToolGatewayService( } + function isApprovalPreparationRejection(error: unknown) { + return error instanceof ToolContentValidationError || + error instanceof ToolGatewayHttpError && error.status >= 400 && error.status < 500 && + ![408, 425, 429].includes(error.status); + } + async function runApprovedTestInvocation( invocation: typeof toolInvocations.$inferSelect, signedPayload: NonNullable>, @@ -7665,13 +7671,10 @@ export function createToolGatewayService( companyId: invocation.companyId, agentId, userId, argumentsSummary, reasonCode: "approval_granted", approvedClaim: claim, matchedPolicyIds: invocation.matchedPolicyIds ?? [] }; } catch (err) { - const rejected = err instanceof ToolContentValidationError || - err instanceof ToolGatewayHttpError && err.status >= 400 && err.status < 500 && - ![408, 425, 429].includes(err.status); - if (!rejected) { + if (!isApprovalPreparationRejection(err)) { // Preparation has not entered runTestToolInvocation. Preserve approval // through dependency failures; the claim owner still verifies no dispatch. - await releaseToolTestApproval(db, claim); + await releaseToolApproval(db, claim); throw err; } const message = err instanceof Error ? err.message : String(err); @@ -8024,81 +8027,67 @@ export function createToolGatewayService( ); } - // Terminal-issue expiry revokes pending/approved requests, but a claim that - // committed just before the issue closed slips past that revocation. Recheck - // the issue after winning the claim so a governed action never runs external - // side effects for an issue that is already done or cancelled. - const issue = await assertIssueOpenForApprovedAction({ - claimed, - invocation, - }); - - const signedPayload = readSignedToolArgumentsPayload({ - signedArguments: claimed.signedArguments, - invocationId: invocation.id, - toolName: invocation.toolName, - signingSecret: options.toolActionSigningSecret, - }); - if (!signedPayload) { - const error = new ToolGatewayHttpError( - 409, - "Approved tool action arguments signature is invalid", - "signed_arguments_invalid", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - if (signedPayload.executionOnApprove !== true) { - const error = new ToolGatewayHttpError( - 409, - "This approval predates execute-on-approve and must remain inert", - "legacy_approved_action_inert", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - - const session: ToolGatewaySession = { - id: `approved-action:${claimed.id}`, - token: "", - companyId: invocation.companyId, - agentId: invocation.agentId, - runId: invocation.runId, - issueId: invocation.issueId, - projectId: issue?.projectId ?? null, - gatewayId: invocation.gatewayId, - gatewayPublicId: invocation.gatewayPublicId, - gatewayTokenId: invocation.gatewayTokenId, - actorType: "agent", - actorId: invocation.agentId, - createdAt: new Date(), - expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), + const claim: ToolApprovalClaim = { + actionRequestId: claimed.id, invocationId: invocation.id, claimedAt: claimed.updatedAt, }; - let tool: ToolGatewayDescriptor; - let liveApprovalSnapshot: Awaited< - ReturnType - >; - try { + const agentId = invocation.agentId; + async function prepareExecution() { + // Terminal-issue expiry revokes pending/approved requests, but a claim that + // committed just before the issue closed slips past that revocation. Recheck + // the issue after winning the claim so a governed action never runs external + // side effects for an issue that is already done or cancelled. + const issue = await assertIssueOpenForApprovedAction({ + claimed, + invocation, + }); + + const signedPayload = readSignedToolArgumentsPayload({ + signedArguments: claimed.signedArguments, + invocationId: invocation.id, + toolName: invocation.toolName, + signingSecret: options.toolActionSigningSecret, + }); + if (!signedPayload) { + const error = new ToolGatewayHttpError( + 409, + "Approved tool action arguments signature is invalid", + "signed_arguments_invalid", + ); + throw error; + } + if (signedPayload.executionOnApprove !== true) { + const error = new ToolGatewayHttpError( + 409, + "This approval predates execute-on-approve and must remain inert", + "legacy_approved_action_inert", + ); + throw error; + } + + const session: ToolGatewaySession = { + id: `approved-action:${claimed.id}`, + token: "", + companyId: invocation.companyId, + agentId, + runId: invocation.runId, + issueId: invocation.issueId, + projectId: issue?.projectId ?? null, + gatewayId: invocation.gatewayId, + gatewayPublicId: invocation.gatewayPublicId, + gatewayTokenId: invocation.gatewayTokenId, + actorType: "agent", + actorId: agentId, + createdAt: new Date(), + expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), + }; await restoreApprovedActionIdentity( session, signedPayload.identityContextId, ); session.approvedInvocationId = invocation.id; session.approvedSlackInvocationId = invocation.id; - tool = await findToolForSession(session, invocation.toolName); - liveApprovalSnapshot = await connectedRemoteApprovalSnapshot( + const tool = await findToolForSession(session, invocation.toolName); + const liveApprovalSnapshot = await connectedRemoteApprovalSnapshot( session, tool, ); @@ -8120,121 +8109,101 @@ export function createToolGatewayService( currentAccess.explanation, currentAccess.reasonCode, ); - } catch (error) { - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - if ( - !approvalSnapshotsMatch( - signedPayload.approvalSnapshot, - liveApprovalSnapshot, - ) - ) { - const error = new ToolGatewayHttpError( - 409, - "Approved tool action target changed after review", - "approved_tool_target_changed", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - const parameters = signedPayload.arguments; - const canonicalArguments = canonicalToolArguments(parameters); - if ( - ![ - toolRequestIdentityHash(parameters, options.toolActionSigningSecret), - // Historical approvals used the redacted preview hash. Their signature - // still binds the complete canonical arguments checked below. - summarizeToolValue(parameters).sha256, - ].includes(claimed.canonicalArgumentsHash) || - !verifyToolArgumentsSignature({ - signedArguments: claimed.signedArguments, - invocationId: invocation.id, - toolName: invocation.toolName, - canonicalArguments, - approvalSnapshot: signedPayload.approvalSnapshot, - executionOnApprove: true, - identityContextId: signedPayload.identityContextId, - signingSecret: options.toolActionSigningSecret, - }) - ) { - const error = new ToolGatewayHttpError( - 409, - "Approved tool action arguments do not match reviewed hash", - "signed_arguments_mismatch", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - let managedArgumentsRemainCurrent: boolean; - try { - managedArgumentsRemainCurrent = + if ( + !approvalSnapshotsMatch( + signedPayload.approvalSnapshot, + liveApprovalSnapshot, + ) + ) { + const error = new ToolGatewayHttpError( + 409, + "Approved tool action target changed after review", + "approved_tool_target_changed", + ); + throw error; + } + const parameters = signedPayload.arguments; + const canonicalArguments = canonicalToolArguments(parameters); + if ( + ![ + toolRequestIdentityHash(parameters, options.toolActionSigningSecret), + // Historical approvals used the redacted preview hash. Their signature + // still binds the complete canonical arguments checked below. + summarizeToolValue(parameters).sha256, + ].includes(claimed.canonicalArgumentsHash) || + !verifyToolArgumentsSignature({ + signedArguments: claimed.signedArguments, + invocationId: invocation.id, + toolName: invocation.toolName, + canonicalArguments, + approvalSnapshot: signedPayload.approvalSnapshot, + executionOnApprove: true, + identityContextId: signedPayload.identityContextId, + signingSecret: options.toolActionSigningSecret, + }) + ) { + const error = new ToolGatewayHttpError( + 409, + "Approved tool action arguments do not match reviewed hash", + "signed_arguments_mismatch", + ); + throw error; + } + const managedArgumentsRemainCurrent = await approvedManagedArgumentsRemainCurrent(session, tool, parameters); + if (!managedArgumentsRemainCurrent) { + throw await expireApprovedActionForManagedArgumentDrift({ + companyId: claimed.companyId, + actionRequestId: claimed.id, + invocationId: invocation.id, + toolName: invocation.toolName, + ownsExecutingClaim: true, + }); + } + + const argumentsSummary = (await validateToolContent({ + value: parameters, + direction: "arguments", + sensitiveMode: "redact", + promptInjectionMode: "ignore", + })).summary; + // Final recheck at the last DB write before dispatch: tool and snapshot + // resolution above involve network calls, so re-verify the issue is still + // open now that only the provider call remains. A close that commits after + // this read has raced an execution that was approved, claimed, and verified + // while the issue was open; that instant is irreducible for an external + // side effect gated by DB state (holding a DB lock across a remote provider + // call is not an option), and the accepted linearization is that the + // execution wins — its result still lands on the expired card via + // reflectToolActionInteractionLifecycle. + await assertIssueOpenForApprovedAction({ claimed, invocation }); + return { session, tool, parameters, argumentsSummary }; + } + let prepared: Awaited>; + try { + prepared = await prepareExecution(); } catch (error) { - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); + if (isApprovalPreparationRejection(error)) { + await markApprovedActionFailed({ + actionRequestId: claimed.id, + invocationId: invocation.id, + claimUpdatedAt: claimed.updatedAt, + expectedInvocationStatus: "awaiting_approval", + error, + }); + } else { + await releaseToolApproval(db, claim); + } throw error; } - if (!managedArgumentsRemainCurrent) { - throw await expireApprovedActionForManagedArgumentDrift({ - companyId: claimed.companyId, - actionRequestId: claimed.id, - invocationId: invocation.id, - toolName: invocation.toolName, - ownsExecutingClaim: true, - }); - } - - const argumentsSummary = (await validateToolContent({ - value: parameters, - direction: "arguments", - sensitiveMode: "redact", - promptInjectionMode: "ignore", - })).summary; - // Final recheck at the last DB write before dispatch: tool and snapshot - // resolution above involve network calls, so re-verify the issue is still - // open now that only the provider call remains. A close that commits after - // this read has raced an execution that was approved, claimed, and verified - // while the issue was open; that instant is irreducible for an external - // side effect gated by DB state (holding a DB lock across a remote provider - // call is not an option), and the accepted linearization is that the - // execution wins — its result still lands on the expired card via - // reflectToolActionInteractionLifecycle. - await assertIssueOpenForApprovedAction({ claimed, invocation }); + const { session, tool, parameters, argumentsSummary } = prepared; const startedAt = Date.now(); - await db - .update(toolInvocations) - .set({ - status: "executing", - approvalState: "approved", - startedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, invocation.id)); + // Keep dispatch and outcome persistence outside the preparation retry + // boundary. Only the still-current claim may record the provider start. + if (!(await startToolInvocation(db, invocation.id, claim))) { + throw new ToolGatewayHttpError(409, "Tool action execution claim is no longer current", "action_already_consumed"); + } await reflectToolActionInteractionLifecycle({ actionRequestId: claimed.id, status: "executing",