From cd516fdc2bd46367bc9d148e3b7a3ef109b5e0c6 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 16:54:57 -0500 Subject: [PATCH] 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;