Merge updated parent into sleep-18-tool-connection-health

Preserve the existing PR boundary while integrating master through the sleep migration stack.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-26 18:25:26 -05:00
commit 38c96c32b7
19 files changed
+387 -109

No files matched your search

+25 -4
View File
@@ -13,9 +13,18 @@ approval can owe execution even when no agent run exists. Recovery uses the save
origin and current authorization/target checks; the scheduler sees only whether
another attempt is needed.
Recovery pages approved requests in ID order using a partial index. It does not
Startup discovers companies with saved approved requests. Committed review
signals carry the affected company ID; subsequent discovery and recovery reads
filter by that company. The shared scoped worker coalesces changes and dispatches
one company per pass with a one-second minimum spacing. A company writing reviews
does not scan or lock another company's approved backlog.
Recovery pages that company's approved requests in ID order using a partial index. It does not
let a full batch of unavailable approvals starve later work. A failed read or
unresolved executable approval retains a 30-second retry. Once a pass leaves no
unresolved executable approval retains a 30-second retry. New writes preserve
that company's retry deadline, while other companies can run independently.
A company pass still drains all its pages; this change does not cap provider
calls within that pass or alter the provider's existing execution timeout. Once a pass leaves no
such obligation, there is no recurring approved-recovery query. An empty system,
configured idle tools, completed history, and deliberately inert approvals are
quiet after reconciliation.
@@ -29,7 +38,7 @@ queue invalidation, and the gateway's approval claims and managed-argument
invalidation. The notification is awaited before SQL in the existing transaction;
caller-owned outer transactions retain commit/rollback ownership.
A pending-only change can cause one empty approved-recovery pass. It does not
A pending-only change can cause one empty company-scoped discovery read. It does not
create a periodic scan. No per-route recovery bookkeeping or database listener
is added. Signals use the existing database owner's single-active-writer model.
Independent SQL writers or another process need a separate notification contract.
@@ -57,7 +66,8 @@ replay an uncertain provider call.
The shared deadline worker coalesces notifications, preserves changes during a
pass, and retains skipped work across idle drain/resume. Startup reconstructs
saved approvals. Shutdown stops its coordinator registration. With heartbeat
saved approvals. Company deletion invalidates cached recovery and retries through
the same transactional notification boundary. Shutdown stops its coordinator registration. With heartbeat
scheduling disabled, startup keeps the existing one-off recovery behavior.
Pending expiry is owned by the preceding slice. Interrupted execution and
@@ -94,3 +104,14 @@ request to be executed and verifies exactly one provider call before asking for
a new approval. Its full 469-test suite passes. The initial local command skipped
its database cases; the suite now honors its supplied disposable database through
the standard test-database guard independently of embedded Postgres support.
Company-scoping regression: a real signed/reviewed action in company A previously
caused an unfiltered approved-request SELECT over company B's inert legacy action.
The captured-SQL test fails before this repair and passes with scoped reads. Added
lifecycle cases check retry preservation across committed writes, independent
company progress, and disarming after the real company-deletion producer. These
checks supplement the earlier execution, transaction, and paging evidence above.
After company scoping, the complete gateway-service and startup selection passes
149 tests against a disposable PostgreSQL database, and server typecheck passes.
Stack integration, workspace checks, and fresh remote CI remain separate gates.
+10 -3
View File
@@ -24,12 +24,19 @@ PostgreSQL microsecond timestamps. Before the repair, the eligible workspace was
never archived. After the repair, the full workspace service and terminal worker
selection passes all 87 tests, including bounded rotation under continuous churn,
changed rows behind the cursor, failed-page recovery, quiet workers, and shutdown.
The service suite now supports the repository's validated disposable external
PostgreSQL URL so this path executes where embedded PostgreSQL is unavailable.
The database connection closes during teardown. Server typechecking passes.
The service suite accepts the repository's validated disposable external
PostgreSQL URL. Setup applies pending migrations before opening the test client,
then clears fixture tables before the first test as well as after each test. This
supports a fresh database and reuse after an interrupted test run. The database
connection closes during teardown. Server typechecking passes.
This fixes recovery progress. It does not establish provider suspension or change
which active or unresolved resources prevent instance sleep.
Workspace-wide typechecking and the production build also pass. Full sharded CI
and fresh review remain required before this PR is ready.
Review follow-up reproduced the missing-schema failure against a newly created,
unmigrated disposable database. The setup repair migrates that same database
inside the suite; the full workspace-service selection then runs without manual
schema preparation. The production cursor implementation is unchanged.
+15 -3
View File
@@ -9,7 +9,7 @@ or change the one-hour review policy.
The tool gateway owns request signing and authorization. `toolReviewExpiryService`
owns pending-expiry selection and settlement. `registerToolReviewExpiryWork`
supplies those operations to the existing shared deadline worker. Startup wires
supplies company-scoped operations to the existing shared scoped deadline worker. Startup wires
that contract without interpreting tool or provider behavior.
The supported writers are:
@@ -27,9 +27,15 @@ The supported writers are:
- Administrative interaction resolution signals in the caller-owned transaction
before resolving linked requests. Review-queue invalidation signals before
invalidating unreadable or unsigned requests.
- Company deletion signals its company before removing saved review obligations.
- The expiry worker signals before its own settlement. A compare-and-set against
pending status and the observed update time protects concurrent resolution.
Every notification requires the company ID. Normal commits reload only that
company's saved minimum expiry; due cleanup selects only that company. Startup
reconstructs all saved company deadlines once. A company with only unsigned
null-expiry requests has no deadline.
Only the SQL mutation is wrapped. Signing, provider requests, telemetry, and
interaction publication are not moved inside an enclosing recovery transaction.
The database signal layer handles nested savepoints, outer commit/rollback, and
@@ -59,7 +65,10 @@ worker active. The concurrent index migration uses the existing top-level
executor and is safe to apply again after interruption.
The shared coordinator coalesces changes and preserves a write arriving during
reconciliation. It retries failed or unfinished reconciliation after 30 seconds.
reconciliation. Each due pass expires at most 100 rows for one company; companies
rotate between passes until the backlog drains. Failed scopes retry independently
with exponential backoff from 30 seconds to five minutes. Other companies retain
their own deadlines. New writes do not erase a failed sweep's backoff.
Once reconciliation completes with no deadline, it has no recurring SQL. Drain
retains first writes without passive database scans; resume processes overdue
reviews. Startup reconstructs persisted deadlines. Shutdown stops subscription
@@ -70,7 +79,10 @@ With heartbeat scheduling disabled, startup-only expiry remains as before.
## Verification scope
Real PostgreSQL tests exercise normal gateway signing and human decisions,
Real PostgreSQL tests record SQL to prove signing, human decisions, and due expiry
remain company-scoped. They also verify five-second and earlier replacement
deadlines, company deletion, and bounded multi-pass draining. Existing cases cover
normal gateway signing and human decisions,
configured idle and terminal history, outer commit/rollback, startup/restart,
drain/resume, concurrent producer/read, unsigned rows, multi-page expiry, and
injected invocation-write failure with atomic rollback and retry. Existing
@@ -12,6 +12,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest
import { eq, inArray, sql } from "drizzle-orm";
import {
activityLog,
applyPendingMigrations,
agents,
companies,
createDb,
@@ -260,8 +261,10 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
}>();
beforeAll(async () => {
if (!externalUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-execution-workspaces-service-");
if (externalUrl) await applyPendingMigrations(externalUrl);
else tempDb = await startEmbeddedPostgresTestDatabase("paperclip-execution-workspaces-service-");
db = createDb(externalUrl ?? tempDb!.connectionString);
await resetDatabase();
svc = executionWorkspaceService(db, {
resolvePullRequestDetails: vi.fn(async (companyId, reference) =>
pullRequestDetailsByKey.get(`${companyId}:${reference.number}`)
@@ -274,7 +277,7 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
});
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterEach(async () => {
async function resetDatabase() {
await db.delete(workspaceRuntimeServices);
await db.delete(activityLog);
await db.delete(issueRecoveryActions);
@@ -288,6 +291,10 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
}
afterEach(async () => {
await resetDatabase();
pullRequestDetailsByKey.clear();
for (const dir of tempDirs) {
@@ -73,9 +73,12 @@ const {
nextActionReviewInterruptionAt: vi.fn(async () => null),
recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })),
repairActionReviewProjections: vi.fn(async () => ({ scanned: 0, retry: false })),
approvedActionReviewCompanies: vi.fn(async () => []),
sweepActionReviews: vi.fn(async () => ({ scanned: 0 })),
sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })),
nextActionReviewExpiryAt: vi.fn(async () => null),
actionReviewExpiryDeadlines: vi.fn(async () => []),
sweepExpiredActionReviewsForCompany: vi.fn(async () => ({ scanned: 0 })),
cleanupExpiredSessions: vi.fn(async () => ({ deletedCount: 0 })),
nextCredentialExpiryAt: vi.fn(async () => null),
},
+181 -10
View File
@@ -2,6 +2,7 @@ import { registerToolReviewProjectionWork } from "../services/tool-review-projec
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { registerToolReviewInterruptionWork } from "../services/tool-review-interruption-work.js";
import { writeToolReviewChange } from "../services/tool-review-work-notifications.js";
import { deleteCompany } from "../services/company-deletion.js";
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { randomUUID } from "node:crypto";
@@ -303,12 +304,15 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(selects).not.toHaveBeenCalled(); expect(executes).not.toHaveBeenCalled();
selects.mockRestore(); executes.mockRestore();
}
async function request(service = gateway, source = db) {
const session = await service.createSession(runSessionInput(fixture.company, fixture.agent, fixture.run));
async function request(service = gateway, source = db, context = fixture) {
const before = new Set((await source.select({ id: toolActionRequests.id }).from(toolActionRequests)
.where(eq(toolActionRequests.companyId, context.company.id))).map(row => row.id));
const session = await service.createSession(runSessionInput(context.company, context.agent, context.run));
const noteId = randomUUID();
await expect(service.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:update_note",
parameters: { noteId, body: "Awaiting a human" } })).rejects.toMatchObject({ reasonCode: "approval_required" });
const rows = await source.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, fixture.company.id));
const rows = (await source.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, context.company.id)))
.filter(row => !before.has(row.id));
expect(rows).toHaveLength(1);
return rows[0];
}
@@ -359,7 +363,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
}
async function savedOutcome(pending: Awaited<ReturnType<typeof request>>, source = db,
status: "executed" | "failed" | "expired" | "cancelled" = "executed") {
await writeToolReviewChange(source, async tx => {
await writeToolReviewChange(source, pending.companyId, async tx => {
await tx.update(toolInvocations).set({ status: status === "executed" ? "succeeded" : "failed",
errorCode: status === "executed" ? null : "saved_failure", errorMessage: null,
resultSummary: { summary: "Durable result" }, completedAt: new Date() })
@@ -509,7 +513,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
async function savedClaim(source = db, age = 0) {
const pending = await request();
const claimedAt = new Date(Date.now() - age);
await writeToolReviewChange(source, async tx => {
await writeToolReviewChange(source, fixture.company.id, async tx => {
await tx.update(toolInvocations).set({ status: "executing", startedAt: claimedAt, updatedAt: claimedAt })
.where(eq(toolInvocations.id, pending.invocationId));
await tx.update(toolActionRequests).set({ status: "executing", updatedAt: claimedAt })
@@ -579,7 +583,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
const gate = new Promise<void>(resolve => { release = resolve; });
const aborted = new Error("fixture rollback");
const running = db.transaction(async tx => {
await writeToolReviewChange(tx as unknown as typeof db, async nested => {
await writeToolReviewChange(tx as unknown as typeof db, fixture.company.id, async nested => {
await nested.update(toolActionRequests).set({ status: "executing", updatedAt: new Date() })
.where(eq(toolActionRequests.id, pending.id));
});
@@ -632,7 +636,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
await ready;
const updatedAt = new Date();
try {
await writeToolReviewChange(db, tx => tx.update(toolActionRequests).set({ updatedAt })
await writeToolReviewChange(db, fixture.company.id, tx => tx.update(toolActionRequests).set({ updatedAt })
.where(eq(toolActionRequests.id, pending.id)));
} finally { release(); }
await sweep; intercepted.mockRestore();
@@ -672,6 +676,43 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1);
});
it("does not scan another company's approved backlog after review writes", async () => {
const other = await createRunFixture(db);
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
const foreign = await request(gateway, db, other);
await db.update(toolActionRequests).set({ signedArguments: signToolArguments({
invocationId: foreign.invocationId, toolName: "mcp-remote-fixture:update_note",
canonicalArguments: canonicalToolArguments({ noteId: "legacy", body: "inert" }),
signingSecret: testToolActionSigningSecret,
}) }).where(eq(toolActionRequests.id, foreign.id));
await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id,
decision: "approved", actor: { userId: "board" } });
await startRecovery(); await quiet();
const reads: Array<{ query: string; params: unknown[] }> = [];
const debug = db.$client.options.debug;
db.$client.options.debug = (_id, query, params) => {
if (/^select/i.test(query) && query.includes('"tool_action_requests"') &&
query.includes('"tool_action_requests"."status" =') && params.includes("approved"))
reads.push({ query, params: [...params] });
};
try {
for (let index = 0; index < 3; index++) {
const pending = await request(); await settle(1500);
await approve(pending); await settle(1500); await executed(pending);
}
} finally { db.$client.options.debug = debug; }
expect(reads.length).toBeGreaterThan(0);
for (const read of reads) {
expect(read.query).toContain('"tool_action_requests"."company_id" =');
expect(read.params).toContain(fixture.company.id);
expect(read.params).not.toContain(other.company.id);
}
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("approved");
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, foreign.invocationId)))[0].status).toBe("awaiting_approval");
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3);
await quiet();
});
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" },
@@ -702,6 +743,45 @@ describeEmbeddedPostgres("tool gateway service", () => {
recover.mockRestore(); await settle(); await executed(pending); await quiet();
});
it("preserves a failed company's retry across writes while another company executes", async () => {
const pending = await request(); await approve(pending);
const original = gateway.approveActionRequest.bind(gateway);
const dispatch = vi.spyOn(gateway, "approveActionRequest").mockImplementation(async input => {
if (input.companyId === fixture.company.id) throw new Error("Company dependency unavailable");
return original(input);
});
await startRecovery();
expect(dispatch).toHaveBeenCalledTimes(1);
const retryAt = coordinator!.nextWakeAt();
expect(retryAt).not.toBeNull();
const later = await request(); await approve(later);
const other = await createRunFixture(db);
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
const foreign = await request(gateway, db, other);
await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id,
decision: "approved", actor: { userId: "board" } });
await settle(5000); await executed(foreign);
expect(dispatch.mock.calls.filter(([input]) => input.companyId === fixture.company.id)).toHaveLength(1);
expect(coordinator!.nextWakeAt()).toBe(retryAt);
dispatch.mockRestore();
await settle(); await executed(pending); await executed(later); await quiet();
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3);
});
it("disarms a failed company's recovery after company deletion commits", async () => {
const pending = await request(); await approve(pending);
const dispatch = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Company dependency unavailable"));
await startRecovery(); expect(coordinator!.nextWakeAt()).not.toBeNull();
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, fixture.run.id));
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" })
.where(eq(agents.id, fixture.agent.id));
await deleteCompany(db, fixture.company.id);
await settle(1500);
expect(coordinator!.nextWakeAt()).toBeNull();
expect(dispatch).toHaveBeenCalledTimes(1); 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));
@@ -974,6 +1054,92 @@ describeEmbeddedPostgres("tool gateway service", () => {
});
});
async function requestWithExpiry(expiresAt: Date, context = fixture) {
return db.transaction(async tx => {
const source = tx as unknown as typeof db;
const pending = await request(createTestToolGatewayService(source), source, context);
const [saved] = await tx.update(toolActionRequests).set({ expiresAt })
.where(eq(toolActionRequests.id, pending.id)).returning();
return saved;
});
}
it("keeps signing and human resolution reads scoped to their company", async () => {
const other = await createRunFixture(db);
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
const foreign = await request(gateway, db, other);
await start(); await settle(1);
const reads: Array<{ query: string; params: unknown[] }> = [];
const debug = db.$client.options.debug;
db.$client.options.debug = (_id, query, params) => {
if (/^select/i.test(query) && query.includes('"tool_action_requests"') &&
(query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] });
};
try {
for (let index = 0; index < 3; index++) {
const pending = await request(); await settle(1000);
await commitToolActionReview(db, { companyId: fixture.company.id, actionRequestId: pending.id,
decision: "rejected", actor: { userId: "reviewer" } });
await settle(1000);
}
} finally { db.$client.options.debug = debug; }
expect(reads.length).toBeGreaterThan(0);
for (const read of reads) {
expect(read.query).toContain('"tool_action_requests"."company_id" =');
expect(read.params).toContain(fixture.company.id);
expect(read.params).not.toContain(other.company.id);
}
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("pending");
expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime());
});
it("preserves a five-second deadline and an earlier committed replacement", async () => {
await start(); await quiet();
const later = await requestWithExpiry(new Date(Date.now() + 120_000)); await settle(1);
expect(coordinator!.nextWakeAt()).toBe(later.expiresAt!.getTime());
const earlier = await requestWithExpiry(new Date(Date.now() + 5000)); await settle(1);
expect(coordinator!.nextWakeAt()).toBe(earlier.expiresAt!.getTime());
await settle(6000); await expectExpired(earlier.id, earlier.invocationId);
expect(coordinator!.nextWakeAt()).toBe(later.expiresAt!.getTime());
await settle(120_000); await expectExpired(later.id, later.invocationId); await quiet();
});
it("limits due expiry reads to the company whose deadline arrived", async () => {
const other = await createRunFixture(db);
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
const foreign = await request(gateway, db, other);
const due = await requestWithExpiry(new Date(Date.now() + 5000));
await start(); await settle(1);
const reads: Array<{ query: string; params: unknown[] }> = [];
const debug = db.$client.options.debug;
db.$client.options.debug = (_id, query, params) => {
if (/^select/i.test(query) && query.includes('"tool_action_requests"') &&
(query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] });
};
try { await settle(6000); } finally { db.$client.options.debug = debug; }
expect(reads.some(read => read.query.includes('"expires_at" <='))).toBe(true);
for (const read of reads) {
expect(read.query).toContain('"tool_action_requests"."company_id" =');
expect(read.params).toContain(fixture.company.id);
expect(read.params).not.toContain(other.company.id);
}
await expectExpired(due.id, due.invocationId);
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("pending");
expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime());
});
it("removes cached review deadlines after company deletion commits", async () => {
await request(); await start(); await settle(1);
expect(coordinator!.nextWakeAt()).not.toBeNull();
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, fixture.run.id));
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" })
.where(eq(agents.id, fixture.agent.id));
expect(await deleteCompany(db, fixture.company.id)).toMatchObject({ id: fixture.company.id });
await quiet();
expect(await gateway.actionReviewExpiryDeadlines()).toEqual([]);
});
it("is quiet when configured idle, wakes on signing, expires the review and card, then stays quiet with history", async () => {
await start(); await quiet();
const pending = await request();
@@ -1044,8 +1210,8 @@ describeEmbeddedPostgres("tool gateway service", () => {
let release!: () => void, reading!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const ready = new Promise<void>(resolve => { reading = resolve; });
const actual = gateway.nextActionReviewExpiryAt.bind(gateway);
vi.spyOn(gateway, "nextActionReviewExpiryAt").mockImplementationOnce(async () => {
const actual = gateway.actionReviewExpiryDeadlines.bind(gateway);
vi.spyOn(gateway, "actionReviewExpiryDeadlines").mockImplementationOnce(async () => {
const deadline = await actual(); reading(); await gate; return deadline;
});
const starting = start(); await ready;
@@ -1070,7 +1236,11 @@ describeEmbeddedPostgres("tool gateway service", () => {
await db.insert(toolActionRequests).values(Array.from({ length: 101 }, () => ({
...pending, id: randomUUID(), interactionId: null, expiresAt: past,
})));
const passes = vi.spyOn(gateway, "sweepExpiredActionReviewsForCompany");
await start(); await quiet();
const results = await Promise.all(passes.mock.results.map(result => result.value));
expect(results.length).toBeGreaterThan(1);
expect(results.every(result => result.scanned <= 100)).toBe(true);
const rows = await db.select().from(toolActionRequests);
expect(rows).toHaveLength(102);
expect(rows.every(row => row.status === "expired")).toBe(true);
@@ -1087,7 +1257,8 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("pending");
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0].status).toBe("awaiting_approval");
await db.execute(sql`drop trigger sleep_review_fail on tool_invocations`);
expect(errors.every(error => (error as { cause?: Error }).cause?.message === "expiry settlement fixture failure")).toBe(true);
expect(errors.every(error => error instanceof AggregateError && error.errors.every(
failure => (failure as { cause?: Error }).cause?.message === "expiry settlement fixture failure"))).toBe(true);
errors.length = 0;
await settle(); await expectExpired(pending.id, pending.invocationId); await quiet();
});
@@ -8,7 +8,7 @@ export async function notifyApprovalWork(transaction: object, companyId: string)
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.approvalRetention);
await notifyApprovalQueueWork(transaction, companyId);
// Formal decisions release parked tool reviews on the same outer commit.
await notifyToolReviewChange(transaction);
await notifyToolReviewChange(transaction, companyId);
}
export function writeApprovalChange<T>(db: Db, companyId: string, write: (transaction: Db) => Promise<T>): Promise<T> {
+2
View File
@@ -1,6 +1,7 @@
import { notifyToolConnectionHealth } from "./tool-connection-health-notifications.js";
import { notifyCompanyRetentionWork } from "./retention-work-notifications.js";
import { notifyDecisionTargetWork } from "./decision-target-work.js";
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { agentObservabilityService } from "./agent-observability.js";
import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
@@ -65,6 +66,7 @@ export async function deleteCompany(db: Db, id: string) {
if (!existing) return null;
await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id);
await notifyToolReviewChange(tx, id);
await agentObservabilityService(tx as unknown as Db).removeForCompanyDeletion(id);
// Finance can reference costs and both can reference runs. Incidents
// reference policies and approvals; delete these dependents first.
@@ -1084,7 +1084,7 @@ async function resolveLinkedToolActionRequests(
},
) {
if (interaction.kind !== "request_confirmation") return;
await notifyToolReviewChange(db);
await notifyToolReviewChange(db, interaction.companyId);
await db
.update(toolActionRequests)
.set({
@@ -87,7 +87,7 @@ listActionRequests: async (
if (!readable) invalidRequestIds.push(request.id);
}
if (invalidRequestIds.length > 0) {
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, companyId, tx => tx
.update(toolActionRequests)
.set({
status: "cancelled",
+1 -1
View File
@@ -141,7 +141,7 @@ export async function commitToolActionReview(
throw conflict("This review has already been resolved");
}
const now = new Date();
await notifyToolReviewChange(tx);
await notifyToolReviewChange(tx, current.companyId);
const [updated] = await tx
.update(toolActionRequests)
.set({
+30 -21
View File
@@ -3,9 +3,9 @@ import { writeApprovalChange } from "./approval-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 { prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.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";
import { notifyToolReviewChange, writeToolReviewChange } from "./tool-review-work-notifications.js";
import { restConnectorFor } from "./connectors/rest-registry.js";
import type { runPromptInjectionProvider } from "./prompt-injection-provider.js";
import { promptInjectionPreventionService } from "./prompt-injection-prevention.js";
@@ -2519,7 +2519,7 @@ export function createToolGatewayService(
signingSecret: options.toolActionSigningSecret,
});
} catch (error) {
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "cancelled",
@@ -2679,7 +2679,7 @@ export function createToolGatewayService(
// an expired row. When the guard matches no row, the row is already resolved.
// Do not emit an approval card for a dead row; throw a retriable conflict so
// the retry finds the live request or creates a fresh, signable one.
const signedRows = await writeToolReviewChange(db, tx => tx
const signedRows = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
interactionId: interaction.id,
@@ -7777,7 +7777,7 @@ export function createToolGatewayService(
const message =
input.error instanceof Error ? input.error.message : String(input.error);
const now = new Date();
const settled = await writeToolReviewChange(db, async (tx) => {
const settled = await db.transaction(async (tx) => {
// Lock in the same invocation -> request order used by the normal
// execution settlement path. The claim timestamp is the ownership token:
// a consumer that merely read an approved row cannot settle another
@@ -7793,6 +7793,7 @@ export function createToolGatewayService(
const [actionRequest] = await tx
.select({
companyId: toolActionRequests.companyId,
status: toolActionRequests.status,
updatedAt: toolActionRequests.updatedAt,
})
@@ -7807,6 +7808,7 @@ export function createToolGatewayService(
return false;
}
await notifyToolReviewChange(tx, actionRequest.companyId);
await tx
.update(toolInvocations)
.set({
@@ -7851,6 +7853,7 @@ export function createToolGatewayService(
}
async function expireApprovedActionForManagedArgumentDrift(input: {
companyId: string;
actionRequestId: string;
invocationId: string;
toolName: string;
@@ -7868,7 +7871,7 @@ export function createToolGatewayService(
);
const now = new Date();
await options.beforeManagedArgumentDriftExpiry?.();
const [expired] = await writeToolReviewChange(db, tx => tx
const [expired] = await writeToolReviewChange(db, input.companyId, tx => tx
.update(toolActionRequests)
.set({ status: "expired", resolvedAt: now, updatedAt: now })
.where(
@@ -7928,7 +7931,7 @@ export function createToolGatewayService(
return { projectId: issue.projectId };
}
const expiredAt = new Date();
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, claimed.companyId, tx => tx
.update(toolActionRequests)
.set({ status: "expired", resolvedAt: expiredAt, updatedAt: expiredAt })
.where(eq(toolActionRequests.id, claimed.id)));
@@ -7988,7 +7991,7 @@ export function createToolGatewayService(
);
}
const [claimed] = await writeToolReviewChange(db, tx => tx
const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({ status: "executing", updatedAt: new Date() })
.where(
@@ -8199,6 +8202,7 @@ export function createToolGatewayService(
}
if (!managedArgumentsRemainCurrent) {
throw await expireApprovedActionForManagedArgumentDrift({
companyId: claimed.companyId,
actionRequestId: claimed.id,
invocationId: invocation.id,
toolName: invocation.toolName,
@@ -8298,7 +8302,7 @@ export function createToolGatewayService(
})
.where(eq(toolInvocations.id, invocation.id));
void emitConnectionInvoked(db, invocation.id);
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, claimed.companyId, tx => tx
.update(toolActionRequests)
.set({ status: "executed", resolvedAt: now, updatedAt: now })
.where(eq(toolActionRequests.id, claimed.id)));
@@ -8429,7 +8433,7 @@ export function createToolGatewayService(
pendingRequest.expiresAt.getTime() <= Date.now();
if (pendingUnsigned || pendingExpired) {
const now = new Date();
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, pendingRequest.companyId, tx => tx
.update(toolActionRequests)
.set({ status: "expired", resolvedAt: now, updatedAt: now })
.where(
@@ -9470,7 +9474,7 @@ export function createToolGatewayService(
signingSecret: options.toolActionSigningSecret,
});
} catch (error) {
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, pendingActionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "cancelled",
@@ -9511,7 +9515,7 @@ export function createToolGatewayService(
tool,
argumentsSummary: argumentValidation.summary,
});
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, pendingActionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
canonicalArgumentsHash,
@@ -9669,8 +9673,12 @@ export function createToolGatewayService(
nextActionReviewInterruptionAt: reviewInterruption.next,
sweepExpiredActionReviews: reviewExpiry.sweep,
nextActionReviewExpiryAt: reviewExpiry.next,
actionReviewExpiryDeadlines: reviewExpiry.deadlines,
sweepExpiredActionReviewsForCompany: reviewExpiry.sweepForCompany,
async recoverApprovedActionReviews() {
approvedActionReviewCompanies: (companyId?: string) => approvedToolReviewCompanies(db, companyId),
async recoverApprovedActionReviews(companyId?: string) {
return recoverApprovedToolReviews(db, async row => {
try {
const prepared = await prepareApprovedToolReview(db, { actionRequestId: row.request.id,
@@ -9691,7 +9699,7 @@ export function createToolGatewayService(
logger.warn({ err, actionRequestId: row.request.id }, "Could not recover approved tool action");
return true;
}
});
}, companyId);
},
async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean; includeInterrupted?: boolean } = {}) {
@@ -9804,7 +9812,7 @@ export function createToolGatewayService(
}
if (!signedPayload) {
if (actionRequest.status === "pending") {
await writeToolReviewChange(db, tx => tx
await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "cancelled",
@@ -10377,7 +10385,7 @@ export function createToolGatewayService(
actionRequest.expiresAt.getTime() <= Date.now()
) {
const expiredAt = new Date();
const [expired] = await writeToolReviewChange(db, tx => tx
const [expired] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "expired",
@@ -10425,7 +10433,7 @@ export function createToolGatewayService(
interaction?.kind === "request_confirmation" &&
interaction.status === "accepted"
) {
const [approved] = await writeToolReviewChange(db, tx => tx
const [approved] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "approved",
@@ -10521,7 +10529,7 @@ export function createToolGatewayService(
);
await options.beforeLegacyApprovedActionClaim?.();
const claimedAt = new Date();
const [claimed] = await writeToolReviewChange(db, tx => tx
const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "executing",
@@ -10614,13 +10622,14 @@ export function createToolGatewayService(
))
) {
throw await expireApprovedActionForManagedArgumentDrift({
companyId: actionRequest.companyId,
actionRequestId: actionRequest.id,
invocationId: storedInvocation.id,
toolName: storedInvocation.toolName,
});
}
const claimedAt = new Date();
const [claimed] = await writeToolReviewChange(db, tx => tx
const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "executing",
@@ -10899,7 +10908,7 @@ export function createToolGatewayService(
.where(eq(toolInvocations.id, invocationId));
if (input.approvedActionRequestId) {
const actionRequestId = input.approvedActionRequestId;
const [executedRequest] = await writeToolReviewChange(db, tx => tx
const [executedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "executed",
@@ -11033,7 +11042,7 @@ export function createToolGatewayService(
void emitConnectionInvoked(db, invocationId);
if (input.approvedActionRequestId) {
const actionRequestId = input.approvedActionRequestId;
const [failedRequest] = await writeToolReviewChange(db, tx => tx
const [failedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx
.update(toolActionRequests)
.set({
status: "failed",
+16 -7
View File
@@ -1,16 +1,25 @@
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { registerDeadlineWork } from "./deadline-work.js";
import { registerScopedDeadlineWork } from "./scoped-deadline-work.js";
import type { createToolGatewayService } from "./tool-gateway.js";
export function registerToolReviewExpiryWork(
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
gateway: Pick<ReturnType<typeof createToolGatewayService>, "sweepExpiredActionReviews" | "nextActionReviewExpiryAt">,
gateway: Pick<ReturnType<typeof createToolGatewayService>, "sweepExpiredActionReviewsForCompany" | "actionReviewExpiryDeadlines">,
canRun: () => boolean,
) {
return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewExpiry, {
retryMs: 30_000, canRun,
run: () => gateway.sweepExpiredActionReviews(),
next: () => gateway.nextActionReviewExpiryAt(),
});
return registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.toolReviewExpiry,
batchSize: 1,
minimumPassIntervalMs: 0,
decodeScope: hint => hint === "*" ? undefined : hint,
matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId,
load: async (companyId?: string) => (await gateway.actionReviewExpiryDeadlines(companyId))
.map(row => ({ ...row, id: row.companyId })),
check: async entry => {
await gateway.sweepExpiredActionReviewsForCompany(entry.companyId);
const [next] = await gateway.actionReviewExpiryDeadlines(entry.companyId);
return next ? { ...next, id: next.companyId } : null;
},
}, canRun);
}
+43 -31
View File
@@ -1,4 +1,4 @@
import { and, asc, eq, gt, lte, sql } from "drizzle-orm";
import { and, asc, eq, gt, isNotNull, lte, sql } from "drizzle-orm";
import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db";
import { writeToolReviewChange } from "./tool-review-work-notifications.js";
@@ -15,36 +15,48 @@ export function toolReviewExpiryService(db: Db, onExpired: (input: {
.from(toolActionRequests).where(eq(toolActionRequests.status, "pending"));
return row?.at == null ? null : new Date(row.at).getTime();
},
async sweep(now = new Date()) {
let cursor: string | undefined;
let scanned = 0;
for (;;) {
const rows = await db.select().from(toolActionRequests).where(and(
eq(toolActionRequests.status, "pending"), lte(toolActionRequests.expiresAt, now),
cursor ? gt(toolActionRequests.id, cursor) : undefined,
)).orderBy(asc(toolActionRequests.id)).limit(100);
for (const row of rows) {
const errorCode = "action_expired";
const errorMessage = "The approval request expired before a decision.";
const changed = await writeToolReviewChange(db, async tx => {
const [updated] = await tx.update(toolActionRequests)
.set({ status: "expired", resolvedAt: now, updatedAt: now }).where(and(
eq(toolActionRequests.id, row.id), eq(toolActionRequests.status, "pending"),
eq(toolActionRequests.updatedAt, row.updatedAt),
)).returning({ id: toolActionRequests.id });
if (!updated) return false;
await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage,
completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId));
return true;
});
if (changed) await onExpired({ actionRequestId: row.id, invocationId: row.invocationId,
status: "expired", errorCode, errorMessage });
}
scanned += rows.length;
if (rows.length < 100) break;
cursor = rows[rows.length - 1].id;
}
return { scanned };
sweep,
sweepForCompany: (companyId: string) => sweep(new Date(), companyId, 1),
async deadlines(companyId?: string) {
const rows = await db.select({ companyId: toolActionRequests.companyId,
at: sql<string | Date>`min(${toolActionRequests.expiresAt})` })
.from(toolActionRequests).where(and(eq(toolActionRequests.status, "pending"),
isNotNull(toolActionRequests.expiresAt),
companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId)))
.groupBy(toolActionRequests.companyId);
return rows.map(row => ({ companyId: row.companyId, dueAt: new Date(row.at).getTime() }));
},
};
async function sweep(now = new Date(), companyId?: string, maxPages = Infinity) {
let cursor: string | undefined;
let scanned = 0;
for (let page = 0; page < maxPages; page++) {
const rows = await db.select().from(toolActionRequests).where(and(
eq(toolActionRequests.status, "pending"), lte(toolActionRequests.expiresAt, now),
cursor ? gt(toolActionRequests.id, cursor) : undefined,
companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId),
)).orderBy(asc(toolActionRequests.id)).limit(100);
for (const row of rows) {
const errorCode = "action_expired";
const errorMessage = "The approval request expired before a decision.";
const changed = await writeToolReviewChange(db, row.companyId, async tx => {
const [updated] = await tx.update(toolActionRequests)
.set({ status: "expired", resolvedAt: now, updatedAt: now }).where(and(
eq(toolActionRequests.id, row.id), eq(toolActionRequests.status, "pending"),
eq(toolActionRequests.updatedAt, row.updatedAt),
)).returning({ id: toolActionRequests.id });
if (!updated) return false;
await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage,
completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId));
return true;
});
if (changed) await onExpired({ actionRequestId: row.id, invocationId: row.invocationId,
status: "expired", errorCode, errorMessage });
}
scanned += rows.length;
if (rows.length < 100) break;
cursor = rows[rows.length - 1].id;
}
return { scanned };
}
}
@@ -28,7 +28,7 @@ export function toolReviewInterruptionService(db: Db, onSettled: (input: {
cursor ? gt(toolActionRequests.id, cursor) : undefined,
)).orderBy(asc(toolActionRequests.id)).limit(100);
for (const row of rows) {
const settled = await writeToolReviewChange(db, async tx => {
const settled = await writeToolReviewChange(db, row.companyId, async tx => {
const [invocation] = await tx.select().from(toolInvocations)
.where(eq(toolInvocations.id, row.invocationId)).for("update");
const [request] = await tx.select().from(toolActionRequests)
@@ -1,20 +1,33 @@
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { registerDeadlineWork } from "./deadline-work.js";
import { registerScopedDeadlineWork } from "./scoped-deadline-work.js";
import type { createToolGatewayService } from "./tool-gateway.js";
export function registerToolReviewRecoveryWork(
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
gateway: Pick<ReturnType<typeof createToolGatewayService>, "recoverApprovedActionReviews">,
gateway: Pick<ReturnType<typeof createToolGatewayService>, "recoverApprovedActionReviews" | "approvedActionReviewCompanies">,
canRun: () => boolean,
) {
let next: number | null = null;
return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewRecovery, {
retryMs: 30_000, canRun,
run: async () => {
const result = await gateway.recoverApprovedActionReviews();
next = result.retry ? Date.now() + 30_000 : null;
// Dispatch failures are reported by the domain owner, not thrown. Preserve
// their retry deadline when another write reloads the same company's work.
const retries = new Map<string, number>();
return registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.toolReviewRecovery,
batchSize: 1,
decodeScope: hint => hint === "*" ? undefined : hint,
matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId,
load: async (companyId?: string) => {
const rows = await gateway.approvedActionReviewCompanies(companyId);
const retained = new Set(rows.map(row => row.companyId));
for (const id of retries.keys()) if ((companyId === undefined || id === companyId) && !retained.has(id)) retries.delete(id);
return rows.map(row => ({ ...row, id: row.companyId, dueAt: retries.get(row.companyId) ?? Date.now() }));
},
next: async () => next,
});
check: async entry => {
const result = await gateway.recoverApprovedActionReviews(entry.companyId);
if (!result.retry) { retries.delete(entry.companyId); return null; }
const dueAt = Date.now() + 30_000;
retries.set(entry.companyId, dueAt);
return { ...entry, dueAt };
},
}, canRun);
}
+13 -3
View File
@@ -34,7 +34,7 @@ export async function prepareApprovedToolReview(db: Db, input: {
errorCode: string;
errorMessage: string;
}) {
await notifyToolReviewChange(tx);
await notifyToolReviewChange(tx, request.companyId);
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,
@@ -89,16 +89,26 @@ export async function prepareApprovedToolReview(db: Db, input: {
});
}
export function approvedToolReviewCompanies(db: Db, companyId?: string) {
return db.select({ companyId: toolActionRequests.companyId }).from(toolActionRequests)
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
.where(and(eq(toolActionRequests.status, "approved"),
companyId ? eq(toolActionRequests.companyId, companyId) : undefined))
.groupBy(toolActionRequests.companyId);
}
export async function recoverApprovedToolReviews(db: Db, recover: (input: {
request: typeof toolActionRequests.$inferSelect;
invocation: typeof toolInvocations.$inferSelect;
}) => Promise<boolean>) {
}) => Promise<boolean>, companyId?: string) {
let cursor: string | undefined;
let scanned = 0, retry = false;
for (;;) {
const rows = await db.select({ request: toolActionRequests, invocation: toolInvocations })
.from(toolActionRequests).innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
.where(and(eq(toolActionRequests.status, "approved"), cursor ? gt(toolActionRequests.id, cursor) : undefined))
.where(and(eq(toolActionRequests.status, "approved"),
companyId ? eq(toolActionRequests.companyId, companyId) : undefined,
cursor ? gt(toolActionRequests.id, cursor) : undefined))
.orderBy(asc(toolActionRequests.id)).limit(100);
for (const row of rows) retry = await recover(row) || retry;
scanned += rows.length;
@@ -1,16 +1,16 @@
import type { Db } from "@paperclipai/db";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
export async function notifyToolReviewChange(transaction: object) {
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewInterruption);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewProjection);
export async function notifyToolReviewChange(transaction: object, companyId: string) {
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery, companyId);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewInterruption, companyId);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewProjection, companyId);
}
export function writeToolReviewChange<T>(db: Db, write: (transaction: Db) => Promise<T>): Promise<T> {
export function writeToolReviewChange<T>(db: Db, companyId: string, write: (transaction: Db) => Promise<T>): Promise<T> {
return db.transaction(async transaction => {
await notifyToolReviewChange(transaction);
await notifyToolReviewChange(transaction, companyId);
return write(transaction as unknown as Db);
});
}
+5 -3
View File
@@ -1,7 +1,7 @@
import { and, eq } from "drizzle-orm";
import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db";
import type { ToolRedactedValueSummary } from "@paperclipai/shared";
import { writeToolReviewChange } from "./tool-review-work-notifications.js";
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
export type ToolTestApprovalClaim = { actionRequestId: string; invocationId: string; claimedAt: Date };
export type ToolTestOutcome = {
@@ -12,12 +12,13 @@ export type ToolTestOutcome = {
};
export async function claimToolTestApproval(db: Db, actionRequestId: string, invocationId: string): Promise<ToolTestApprovalClaim | null> {
return writeToolReviewChange(db, async tx => {
return db.transaction(async tx => {
const [invocation] = await tx.select().from(toolInvocations)
.where(eq(toolInvocations.id, invocationId)).for("update");
const [request] = await tx.select().from(toolActionRequests)
.where(and(eq(toolActionRequests.id, actionRequestId), eq(toolActionRequests.invocationId, invocationId))).for("update");
if (!invocation || request?.status !== "approved") return null;
await notifyToolReviewChange(tx, request.companyId);
const now = new Date();
if (invocation.status !== "awaiting_approval") {
if (["succeeded", "failed", "denied", "timed_out", "rate_limited"].includes(invocation.status)) {
@@ -65,13 +66,14 @@ export async function persistToolTestOutcome(db: Db, invocationId: string, outco
await db.update(toolInvocations).set(values).where(eq(toolInvocations.id, invocationId));
return true;
}
return writeToolReviewChange(db, async tx => {
return db.transaction(async tx => {
const [invocation] = await tx.select({ status: toolInvocations.status }).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 || !["awaiting_approval", "executing"].includes(invocation.status) ||
request?.status !== "executing" || request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false;
await notifyToolReviewChange(tx, request.companyId);
await tx.update(toolInvocations).set(values).where(eq(toolInvocations.id, invocationId));
await tx.update(toolActionRequests).set({ status: outcome.status === "succeeded" ? "executed" : "failed",
resolvedAt: now, updatedAt: now }).where(eq(toolActionRequests.id, claim.actionRequestId));