From fb7e906a27d7d18389c71954e239e7b2be3011e4 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 16:41:07 -0500 Subject: [PATCH 1/2] Retain admitted rate slots while tool actions await approval Reuse the durable admission only for the same bound invocation and unchanged rate rule. Keep approval, current permissions, policy changes, and execution claims with their existing owners. Cover agent and Test-tab foreground/recovery paths, approval-policy preservation, and invalid invocation states. All 139 gateway/policy cases and server typechecking pass. Co-Authored-By: Paperclip --- .../tool-access-policy-service.test.ts | 16 ++++++++- .../__tests__/tool-gateway-service.test.ts | 36 ++++++++++++++++++- server/src/services/tool-access-policy.ts | 11 ++++-- server/src/services/tool-gateway.ts | 9 ++++- 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/server/src/__tests__/tool-access-policy-service.test.ts b/server/src/__tests__/tool-access-policy-service.test.ts index 525f05db57d..c013e8e6c5a 100644 --- a/server/src/__tests__/tool-access-policy-service.test.ts +++ b/server/src/__tests__/tool-access-policy-service.test.ts @@ -1119,6 +1119,19 @@ describeEmbeddedPostgres("tool access policy service", () => { .toMatchObject({ decision: "rate_limited" }); }); + it.each(["pending", "approved"] as const)("retains a waiting invocation's consumed slot without bypassing %s approval policy", async approvalState => { + const { company, input, invocation, svc } = await admittedRateLimitedInvocation(); + await db.update(toolInvocations).set({ status: "awaiting_approval", policyDecision: "require_approval", approvalState }) + .where(eq(toolInvocations.id, invocation.id)); + await db.insert(toolPolicies).values({ companyId: company.id, name: "Review admitted sends", + policyType: "require_approval", priority: 2, selectors: { toolName: "send_email" } }); + const counters = await db.select().from(toolRateLimitCounters); + expect(await svc.decide(input, { admittedInvocationId: invocation.id })) + .toMatchObject({ allowed: false, decision: "require_approval" }); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect(await svc.decide(input)).toMatchObject({ decision: "rate_limited" }); + }); + it("rechecks a newly added rate policy rather than borrowing an older policy's consumed slot", async () => { const { company, input, invocation, svc } = await admittedRateLimitedInvocation(); await svc.createPolicy(company.id, { name: "New send limit", policyType: "rate_limit", priority: 0, @@ -1169,7 +1182,8 @@ describeEmbeddedPostgres("tool access policy service", () => { { actorType: "system" }, { actorId: randomUUID() }, { agentId: null }, { runId: null }, { issueId: null }, { gatewayId: null }, { applicationId: null }, { connectionId: null }, { catalogEntryId: null }, { toolName: "different_tool" }, { providerType: null }, { applicationKey: null }, { upstreamToolName: null }, { argumentsHash: "different" }, - { status: "authorized" }, { policyDecision: "deny" }, { policyDecision: "require_approval", approvalState: "pending" }, + { status: "authorized" }, { status: "succeeded" }, { status: "awaiting_approval" }, + { status: "awaiting_approval", policyDecision: "require_approval", approvalState: "rejected" }, { policyDecision: "deny" }, { policyDecision: "require_approval", approvalState: "pending" }, ]; for (const mutation of mutations) { await db.update(toolInvocations).set(mutation).where(eq(toolInvocations.id, invocation.id)); diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 0e9fe4533bf..786614cc3b7 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -34,6 +34,7 @@ import { toolGatewaySessions, toolInvocations, toolPolicies, + toolRateLimitCounters, } from "@paperclipai/db"; import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js"; import type { VercelConnectClient } from "../services/vercel-connect.js"; @@ -332,6 +333,22 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); }); + it.each(["foreground", "recovery"] as const)("preserves the admitted rate slot for an agent action through %s approval", async mode => { + await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed note", + policyType: "rate_limit", priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" }, + config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + const pending = await request(); + const counters = await db.select().from(toolRateLimitCounters); + expect(counters).toHaveLength(1); expect(counters[0].remaining).toBe(0); + if (mode === "foreground") { + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await startRecovery(); + } else { await approve(pending); await startRecovery(); } + await settle(); await executed(pending); await quiet(); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + it("reconstructs a saved approved action after restart", async () => { const pending = await request(); await approve(pending); await startRecovery(); await settle(); await executed(pending); await quiet(); @@ -387,7 +404,7 @@ describeEmbeddedPostgres("tool gateway service", () => { draining = false; await settle(); await executed(pending); await quiet(); }); - async function testRequest(provider: NonNullable) { + async function testRequest(provider: NonNullable, rateLimited = false) { await db.insert(companyMemberships).values({ companyId: fixture.company.id, principalType: "user", principalId: "board", status: "active", membershipRole: "owner" }); const remote = await createRemoteMcpToolFixture(db, fixture.company.id); @@ -395,6 +412,9 @@ describeEmbeddedPostgres("tool gateway service", () => { .where(eq(toolCatalogEntries.id, remote.catalogEntry.id)); await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "Review connected writes", policyType: "require_approval", priority: 10, selectors: { connectionId: remote.connection.id } }); + if (rateLimited) await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed test call", + policyType: "rate_limit", priority: 1, selectors: { connectionId: remote.connection.id }, + config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); gateway = createTestToolGatewayService(db, { remoteHttpRequest: provider }); const result = await gateway.executeTestCall({ companyId: fixture.company.id, connectionId: remote.connection.id, agentId: fixture.agent.id, userId: "board", toolName: "needs_input", parameters: { value: "reviewed" } }); @@ -437,6 +457,20 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(remoteCall.provider).toHaveBeenCalledTimes(1); }); + it.each(["foreground", "recovery"] as const)("preserves the admitted rate slot for a Test-tab action through %s approval", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider, true); + const counters = await db.select().from(toolRateLimitCounters); + expect(counters).toHaveLength(1); expect(counters[0].remaining).toBe(0); + if (mode === "foreground") { + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await startRecovery(); + } else { await approve(pending); await startRecovery(); } + await settle(); await executed(pending); await quiet(); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }); + it("repairs completed Test-tab history without sending the request again", async () => { const remoteCall = providerFixture(); remoteCall.release(); const { pending } = await testRequest(remoteCall.provider); diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index 8ebda1efeb6..868e9693f2d 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -1371,8 +1371,15 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr status: toolInvocations.status, policyDecision: toolInvocations.policyDecision, approvalState: toolInvocations.approvalState, policyExplanation: toolInvocations.policyExplanation, }).from(toolInvocations).where(and(eq(toolInvocations.companyId, ctx.companyId), eq(toolInvocations.id, invocationId))); - const authorized = invocation && invocation.status === "executing" - && (invocation.policyDecision === "allow" || (invocation.policyDecision === "require_approval" && invocation.approvalState === "approved")) + // A parked request already spent its slot before asking for review. Reusing + // that admission only skips the same rate rule; current policy and the + // gateway's approval/claim owners still decide whether it may execute. + const authorized = invocation && ( + invocation.status === "executing" + && (invocation.policyDecision === "allow" || (invocation.policyDecision === "require_approval" && invocation.approvalState === "approved")) + || invocation.status === "awaiting_approval" && invocation.policyDecision === "require_approval" + && (invocation.approvalState === "pending" || invocation.approvalState === "approved") + ) && invocation.actorType === ctx.actorType && invocation.actorId === ctx.actorId && invocation.agentId === ctx.agentId && invocation.runId === ctx.heartbeatRunId && invocation.issueId === ctx.issueId && invocation.gatewayId === ctx.gatewayId && invocation.applicationId === ctx.applicationId && invocation.connectionId === ctx.connectionId diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 41a4d8a1103..5ebeb4e6b16 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -7652,7 +7652,10 @@ export function createToolGatewayService( if (!(await approvedManagedArgumentsRemainCurrent(session, tool, signedPayload.arguments))) { throw new ToolGatewayHttpError(409, "Approved tool action managed arguments changed after review", "approved_tool_managed_arguments_changed"); } - const access = await policyService.decide(policyInputForTool({ session, tool, parameters: signedPayload.arguments })); + const access = await policyService.decide( + policyInputForTool({ session, tool, parameters: signedPayload.arguments, consumeRateLimit: false }), + { admittedInvocationId: invocation.id }, + ); if (!access.allowed && access.decision !== "require_approval") { throw new ToolGatewayHttpError(403, access.explanation, access.reasonCode); } @@ -8094,7 +8097,9 @@ export function createToolGatewayService( session, tool, parameters: signedPayload.arguments, + consumeRateLimit: false, }), + { admittedInvocationId: invocation.id }, ); if ( !currentAccess.allowed && @@ -9996,7 +10001,9 @@ export function createToolGatewayService( session, tool, parameters: signedPayload.arguments, + consumeRateLimit: false, }), + { admittedInvocationId: invocation.id }, ); if (!access.allowed && access.decision !== "require_approval") throw new ToolGatewayHttpError( From cd516fdc2bd46367bc9d148e3b7a3ef109b5e0c6 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 16:54:57 -0500 Subject: [PATCH 2/2] Settle invalid approved reviews and park pending formal decisions Reconcile durable invocation history under the claim locks before dispatch, retain retries for configuration and dependency failures, and wake formal approval waits only from committed decisions. Co-Authored-By: Paperclip --- ...2026-10-24-recurring-server-sleep-stack.md | 32 ++++ .../__tests__/tool-gateway-service.test.ts | 144 +++++++++++++++++- server/src/services/approvals.ts | 14 +- server/src/services/tool-gateway.ts | 22 +-- server/src/services/tool-review-recovery.ts | 90 ++++++++++- 5 files changed, 285 insertions(+), 17 deletions(-) diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index ad4e1e3f1be..db0c5fc71ad 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -119,6 +119,38 @@ passed. The first acceptance command matched no files; the corrected `tool-gateway.test.ts` selection passed. Fresh PR CI/review remains required. +## Approved-review follow-up repairs (2026-10-26) + +Slice 05 preserves the rate slot admitted before a human review. Agent and +Test-tab foreground/recovery paths reuse only the exact invocation/context and +unchanged rate-policy admission while rechecking current policy. A one-call +limit must not reject the same approved operation against its own occupied slot. + +Recovery now locks and rereads invocation/request history before dispatch. +Finished records repair the request without provider replay; executing records +retain unknown-outcome recovery. Invalid signatures, unusable formal approvals, +and inconsistent invocation states settle once. Missing signing-key configuration +and temporary dependencies retain retries. Company mismatches never mutate the +foreign invocation. No new table or generic HTTP-error discard rule is introduced. + +Formal approvals awaiting human input have no recovery cadence. The existing +approval service publishes commit-aware review notifications for approve/reject +and cancellation. Its shared record owner retains the decision validation/CAS +contract; hire decisions remain with their lifecycle owner. Revision/resubmission +keeps the review parked, and startup rediscovers saved work. Budget approval writes +belong to budget incidents, not tool-gateway formal reviews. Company deletion +removes the dependent work. These exclusions come from the producer audit. + +Local evidence: the four rate-admission regressions, seven permanent-record +regressions, and four formal-approval commit/rollback regressions failed before +their respective repairs. The complete gateway, policy, approval-service and +signature suites pass (208 tests), and server typechecking passes. Configuration +failure, company boundaries, concurrent claims, provider-outcome persistence +failure, restart and paging remain covered. The paging fixture now has independent +invocations instead of 101 approvals sharing an already-expired invocation. +Full remote checks and downstream integration verification remain required; +this is not an all-stack acceptance or deployed-sleep claim. + ## Next owner audit: approved tool-action recovery The next branch is `codex/sleep-05-approved-tool-recovery`, based on pending diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 786614cc3b7..7c510832de2 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -40,6 +40,7 @@ import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js import type { VercelConnectClient } from "../services/vercel-connect.js"; import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity } from "../services/run-identity.js"; import { issueService } from "../services/issues.js"; +import { approvalService } from "../services/approvals.js"; import { commitToolActionReview } from "../services/tool-action-review.js"; import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js"; import { toolActionDeliveryService } from "../services/tool-action-delivery.js"; @@ -363,6 +364,125 @@ describeEmbeddedPostgres("tool gateway service", () => { recover.mockRestore(); await settle(); await executed(pending); await quiet(); }); + it.each([null, "unreadable-old-signature"])("settles an approved invalid signature (%s) without recurring recovery", async signedArguments => { + const pending = await request(); await approve(pending); + await db.update(toolActionRequests).set({ signedArguments }).where(eq(toolActionRequests.id, pending.id)); + const dispatch = vi.spyOn(gateway, "approveActionRequest"); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ + status: "failed", errorCode: "action_request_invalidated", + }); + expect(dispatch).not.toHaveBeenCalled(); await quiet(); + }); + + it.each(["rejected", "cancelled"])("settles a %s formal approval without recurring recovery", async status => { + const pending = await request(); await approve(pending); + const [formal] = await db.insert(approvals).values({ companyId: fixture.company.id, + type: "request_board_approval", status, payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + const dispatch = vi.spyOn(gateway, "approveActionRequest"); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ + status: "denied", errorCode: "formal_approval_unavailable", + }); + expect(dispatch).not.toHaveBeenCalled(); await quiet(); + }); + + it.each([false, true])("parks a formal approval until its decision commits (rollback %s)", async rollback => { + const pending = await request(); await approve(pending); + const [formal] = await db.insert(approvals).values({ companyId: fixture.company.id, + type: "request_board_approval", status: "pending", payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await quiet(); + let release!: () => void, staged!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const ready = new Promise(resolve => { staged = resolve; }); + const aborted = new Error("formal approval rollback fixture"); + const writing = db.transaction(async tx => { + await approvalService(tx as unknown as typeof db).approve(formal.id, "board"); + staged(); await gate; if (rollback) throw aborted; + }).catch(error => { if (error !== aborted) throw error; }); + await Promise.race([ready, writing]); + try { + await vi.advanceTimersByTimeAsync(60_000); + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations))[0].status).toBe("awaiting_approval"); + } finally { release(); } + await writing; await settle(); + if (rollback) { + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); await quiet(); + await approvalService(db).approve(formal.id, "board"); await settle(); + } + await executed(pending); await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + + it.each(["reject", "cancel"] as const)("wakes a parked revision-requested formal approval on %s", async decision => { + const pending = await request(); await approve(pending); + const [formal] = await db.insert(approvals).values({ companyId: fixture.company.id, + type: "request_board_approval", status: "revision_requested", payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await quiet(); + const service = approvalService(db); + if (decision === "cancel") await service.cancel(formal.id, "Cancelled by user"); + else await service.reject(formal.id, "board"); + await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "denied", errorCode: "formal_approval_unavailable" }); + await quiet(); + }); + + it("retains approved work when the signing key is temporarily unavailable", async () => { + const pending = await request(); await approve(pending); + vi.stubEnv("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET", ""); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "invalid-master-key"); + gateway = createToolGatewayService(db); + await startRecovery(); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations))[0].status).toBe("awaiting_approval"); + vi.stubEnv("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET", testToolActionSigningSecret); + await settle(); await executed(pending); await quiet(); + }); + + it("does not accept another company's formal approval", async () => { + const pending = await request(); await approve(pending); + const other = await createRunFixture(db); + const [formal] = await db.insert(approvals).values({ companyId: other.company.id, + type: "request_board_approval", status: "approved", payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "denied", errorCode: "formal_approval_unavailable" }); + expect((await db.select().from(approvals))[0]).toEqual(formal); + await quiet(); + }); + + it("quarantines a mismatched request without modifying another company's invocation", async () => { + const pending = await request(); await approve(pending); + const [invocation] = await db.select().from(toolInvocations); + const other = await createRunFixture(db); + await db.update(toolActionRequests).set({ companyId: other.company.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("failed"); + expect((await db.select().from(toolInvocations))[0]).toEqual(invocation); + await quiet(); + }); + + it("repairs completed agent history without executing the action again", async () => { + const pending = await request(); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await executed(pending); + const [invocation] = await db.select().from(toolInvocations); + await db.update(toolActionRequests).set({ status: "approved", signedArguments: "unreadable-old-signature" }) + .where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect((await db.select().from(toolInvocations))[0]).toEqual(invocation); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + it("keeps deliberately inert legacy approvals quiet", async () => { const pending = await request(); await db.update(toolActionRequests).set({ signedArguments: signToolArguments({ @@ -483,6 +603,18 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(remoteCall.provider).not.toHaveBeenCalled(); }); + it.each(["pending", "authorized", "cancelled"])("settles inconsistent Test-tab %s history without replay", async status => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + await db.update(toolInvocations).set({ status }).where(eq(toolInvocations.id, pending.invocationId)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe(status === "cancelled" ? "cancelled" : "failed"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject(status === "cancelled" + ? { status: "cancelled" } + : { status: "failed", errorCode: "tool_recovery_state_invalid" }); + await quiet(); expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + it("does not replay an interrupted legacy Test-tab invocation", async () => { const remoteCall = providerFixture(); remoteCall.release(); const { pending } = await testRequest(remoteCall.provider); @@ -953,9 +1085,17 @@ describeEmbeddedPostgres("tool gateway service", () => { await expect(gateway.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:update_note", parameters: { noteId: "expire" } })).rejects.toMatchObject({ reasonCode: "approval_required" }); const [request] = await db.select().from(toolActionRequests); await db.update(toolActionRequests).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(toolActionRequests.id, request.id)); - await db.insert(toolActionRequests).values(Array.from({ length: 101 }, (_, i) => ({ + const [originalInvocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, request.invocationId)); + const blockedInvocations = Array.from({ length: 101 }, (_, i) => ({ ...originalInvocation, + id: `10000000-0000-4000-8000-${String(i).padStart(12, "0")}`, approvalState: "approved", idempotencyKey: null, + })); + await db.insert(toolInvocations).values(blockedInvocations); + await db.insert(toolActionRequests).values(blockedInvocations.map((invocation, i) => ({ ...request, id: `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`, - interactionId: null, status: "approved" as const, + invocationId: invocation.id, interactionId: null, status: "approved" as const, + signedArguments: signToolArguments({ invocationId: invocation.id, toolName: invocation.toolName, + canonicalArguments: canonicalToolArguments({ noteId: "blocked" }), executionOnApprove: true, + signingSecret: testToolActionSigningSecret }), }))); const recover = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Unavailable approval dependency")); expect(await gateway.sweepActionReviews()).toEqual({ scanned: 102 }); diff --git a/server/src/services/approvals.ts b/server/src/services/approvals.ts index 290a59fdf4b..c35ed489c56 100644 --- a/server/src/services/approvals.ts +++ b/server/src/services/approvals.ts @@ -1,3 +1,4 @@ +import { writeToolReviewChange } from "./tool-review-work-notifications.js"; import { approvalResolutionRecords, resolvableApprovalStatuses as resolvableStatuses } from "../lib/approval-records.js"; import { notifyHireApproved } from "./hire-hook.js"; @@ -12,7 +13,14 @@ import { instanceSettingsService } from "./instance-settings.js"; export function approvalRecords(db: Db) { const instanceSettings = instanceSettingsService(db); - const { getExistingApproval, resolveApproval } = approvalResolutionRecords(db); + const { getExistingApproval, resolveApproval: resolveApprovalRecord } = approvalResolutionRecords(db); + + // Tool reviews waiting for a formal decision stay parked until this producer + // commits. The shared record owner retains approval validation and CAS rules. + function resolveApproval(id: string, status: "approved" | "rejected", userId: string, + note: string | null | undefined, database: Db = db) { + return writeToolReviewChange(database, tx => resolveApprovalRecord(id, status, userId, note, tx)); + } function redactApprovalComment(comment: T, censorUsernameInLogs: boolean): T { return { @@ -64,7 +72,7 @@ export function approvalRecords(db: Db) { // cleanup. Idempotent: a no-op on already-resolved approvals. cancel: async (id: string, reason?: string | null) => { const now = new Date(); - const updated = await db + const updated = await writeToolReviewChange(db, tx => tx .update(approvals) .set({ status: "cancelled", @@ -74,7 +82,7 @@ export function approvalRecords(db: Db) { }) .where(and(eq(approvals.id, id), inArray(approvals.status, resolvableStatuses))) .returning() - .then((rows) => rows[0] ?? null); + .then((rows) => rows[0] ?? null)); return updated; }, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 5ebeb4e6b16..c2a81cc1b6f 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,5 +1,5 @@ import { claimToolTestApproval, persistToolTestOutcome, startToolTestInvocation, type ToolTestApprovalClaim } from "./tool-test-approval.js"; -import { recoverApprovedToolReviews } from "./tool-review-recovery.js"; +import { prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; import { toolReviewExpiryService } from "./tool-review-expiry.js"; import { writeToolReviewChange } from "./tool-review-work-notifications.js"; import { restConnectorFor } from "./connectors/rest-registry.js"; @@ -9653,24 +9653,24 @@ export function createToolGatewayService( nextActionReviewExpiryAt: reviewExpiry.next, async recoverApprovedActionReviews() { - return recoverApprovedToolReviews(db, async ({ request, invocation }) => { + return recoverApprovedToolReviews(db, async row => { try { - if (isTestOriginInvocation(invocation) && invocation.status !== "awaiting_approval") { - await claimToolTestApproval(db, request.id, invocation.id); - const [remaining] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) - .where(eq(toolActionRequests.id, request.id)); - return remaining?.status === "approved"; + const prepared = await prepareApprovedToolReview(db, { actionRequestId: row.request.id, + invocationId: row.invocation.id, signingSecret: options.toolActionSigningSecret }); + if (prepared.kind === "skip") return false; + if (prepared.kind === "settled") { + await reflectToolActionInteractionLifecycle(prepared.projection); + return false; } - const payload = readSignedToolArgumentsPayload({ signedArguments: request.signedArguments, - invocationId: invocation.id, toolName: invocation.toolName, signingSecret: options.toolActionSigningSecret }); - if (payload && !isTestOriginInvocation(invocation) && payload.executionOnApprove !== true) return false; + const { request, invocation, payload } = prepared; + if (!isTestOriginInvocation(invocation) && payload.executionOnApprove !== true) return false; await this.approveActionRequest({ companyId: request.companyId, actionRequestId: request.id, actor: { userId: request.decidedByUserId ?? request.resolvedByUserId } }); const [remaining] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) .where(eq(toolActionRequests.id, request.id)); return remaining?.status === "approved"; } catch (err) { - logger.warn({ err, actionRequestId: request.id }, "Could not recover approved tool action"); + logger.warn({ err, actionRequestId: row.request.id }, "Could not recover approved tool action"); return true; } }); diff --git a/server/src/services/tool-review-recovery.ts b/server/src/services/tool-review-recovery.ts index 334f0538177..6521aa3d73c 100644 --- a/server/src/services/tool-review-recovery.ts +++ b/server/src/services/tool-review-recovery.ts @@ -1,5 +1,93 @@ import { and, asc, eq, gt } from "drizzle-orm"; -import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; +import { approvals, toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; + +import { readSignedToolArgumentsPayload } from "./tool-content-guards.js"; +import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; + +type ReviewProjection = { + actionRequestId: string; + status: "executed" | "executing" | "failed" | "cancelled"; + errorCode?: string | null; + errorMessage?: string | null; + resultSummary?: string | null; +}; + +/** Reconcile saved history before dispatch; never infer a safe provider replay. */ +export async function prepareApprovedToolReview(db: Db, input: { + actionRequestId: string; + invocationId: string; + signingSecret?: string; +}) { + return db.transaction(async tx => { + // Match Test-tab claims/outcome persistence. Recheck after the locks because + // a foreground approval may have claimed the row since the recovery scan. + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, input.invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.id, input.actionRequestId), + eq(toolActionRequests.invocationId, input.invocationId))).for("update"); + if (!invocation || request?.status !== "approved") return { kind: "skip" } as const; + const now = new Date(); + + async function settle(projection: ReviewProjection, failure?: { + status: "failed" | "denied"; + errorCode: string; + errorMessage: string; + }) { + await notifyToolReviewChange(tx); + if (failure) await tx.update(toolInvocations).set({ ...failure, completedAt: now, updatedAt: now }) + .where(eq(toolInvocations.id, invocation.id)); + await tx.update(toolActionRequests).set({ status: projection.status, + ...(projection.status === "executing" + ? { updatedAt: invocation.startedAt ?? invocation.updatedAt } + : { resolvedAt: invocation.completedAt ?? now, updatedAt: now }), + }).where(eq(toolActionRequests.id, request.id)); + return { kind: "settled", projection } as const; + } + function fail(status: "failed" | "cancelled", invocationStatus: "failed" | "denied", errorCode: string, errorMessage: string) { + return settle({ actionRequestId: request.id, status, errorCode, errorMessage }, + { status: invocationStatus, errorCode, errorMessage }); + } + if (invocation.companyId !== request.companyId) { + // Quarantine the request without modifying another company's invocation. + return settle({ actionRequestId: request.id, status: "failed", + errorCode: "action_context_mismatch", errorMessage: "Tool action and invocation companies do not match." }); + } + if (["succeeded", "failed", "denied", "cancelled", "timed_out", "rate_limited", "executing"].includes(invocation.status)) { + return settle({ actionRequestId: request.id, + status: invocation.status === "succeeded" ? "executed" + : invocation.status === "executing" ? "executing" + : invocation.status === "cancelled" ? "cancelled" : "failed", + errorCode: invocation.errorCode, errorMessage: invocation.errorMessage, + resultSummary: invocation.resultSummary?.summary }); + } + if (invocation.status !== "awaiting_approval") { + return fail("failed", "failed", "tool_recovery_state_invalid", + "Approved action has inconsistent invocation history. Inspect the provider before retrying; recovery did not replay it."); + } + + // Missing-key/configuration errors deliberately propagate as retryable; + // only a decoded invalid signature is a permanent request failure. + const payload = readSignedToolArgumentsPayload({ signedArguments: request.signedArguments, + invocationId: invocation.id, toolName: invocation.toolName, signingSecret: input.signingSecret }); + if (!payload) return fail("cancelled", "failed", "action_request_invalidated", + "Stored tool arguments are no longer verifiable; submit a new action for review."); + if (request.approvalId) { + const [formal] = await tx.select({ status: approvals.status }).from(approvals) + .where(and(eq(approvals.id, request.approvalId), eq(approvals.companyId, request.companyId))); + if (!formal || formal.status === "rejected" || formal.status === "cancelled") { + return fail("cancelled", "denied", "formal_approval_unavailable", + "Required formal board approval is unavailable or was declined; submit a new action for review."); + } + // Human input has no deadline. The approval owner publishes a committed + // resolution/cancellation to this queue; startup also rediscovers the row. + if (formal.status === "pending" || formal.status === "revision_requested") { + return { kind: "skip" } as const; + } + } + return { kind: "ready", request, invocation, payload } as const; + }); +} export async function recoverApprovedToolReviews(db: Db, recover: (input: { request: typeof toolActionRequests.$inferSelect;