Merge approved-review wakes into the shared approval writer

The retention slice already owns approval write transactions. Publish formal-review notifications there so both queues observe the same commit without an additional facade transaction.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-26 16:56:28 -05:00
commit e19f689e08
7 files changed
+345 -19

No files matched your search

@@ -121,6 +121,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
@@ -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));
@@ -38,11 +38,13 @@ 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";
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";
@@ -317,7 +319,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]);
}
async function testRequest(provider: NonNullable<ToolGatewayServiceOptions["remoteHttpRequest"]>) {
async function testRequest(provider: NonNullable<ToolGatewayServiceOptions["remoteHttpRequest"]>, 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);
@@ -325,6 +327,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" } });
@@ -667,6 +672,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();
@@ -681,6 +702,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<void>(resolve => { release = resolve; });
const ready = new Promise<void>(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({
@@ -743,6 +883,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);
@@ -755,6 +909,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);
@@ -1225,9 +1391,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 });
@@ -1,3 +1,4 @@
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
import type { Db } from "@paperclipai/db";
import type { AttentionSourceKind } from "@paperclipai/shared";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
@@ -9,6 +10,9 @@ export async function notifyRetentionWork(transaction: object, kind: AttentionSo
export function writeApprovalChange<T>(db: Db, write: (transaction: Db) => Promise<T>): Promise<T> {
return db.transaction(async tx => {
await notifyRetentionWork(tx, "approval");
// Formal decisions also release parked tool reviews. Share the existing
// approval write transaction rather than nesting another facade wrapper.
await notifyToolReviewChange(tx);
return write(tx as unknown as Db);
});
}
+9 -2
View File
@@ -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
+19 -12
View File
@@ -2,7 +2,7 @@ import { writeApprovalChange } from "./retention-work-notifications.js";
import { toolReviewProjectionService } from "./tool-review-projection.js";
import { toolReviewInterruptionService } from "./tool-review-interruption.js";
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";
@@ -7660,7 +7660,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);
}
@@ -8102,7 +8105,9 @@ export function createToolGatewayService(
session,
tool,
parameters: signedPayload.arguments,
consumeRateLimit: false,
}),
{ admittedInvocationId: invocation.id },
);
if (
!currentAccess.allowed &&
@@ -9665,24 +9670,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;
}
});
@@ -9927,7 +9932,9 @@ export function createToolGatewayService(
session,
tool,
parameters: signedPayload.arguments,
consumeRateLimit: false,
}),
{ admittedInvocationId: invocation.id },
);
if (!access.allowed && access.decision !== "require_approval")
throw new ToolGatewayHttpError(
+89 -1
View File
@@ -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;