Merge origin/master into feat/antigravity-swarm-command

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* origin/master:
  refactor(plugin-sdk): remove archivedState from the resume result (#22443)
  refactor(runner): let the provider decide whether a released Runner relaunches (#22442)
  fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793)
  fix(ui): defer the Connectors announcement until a return visit (#22790)
  fix(connections): show only the privacy policy link in the Google Workspace picker (#22795)
  Add count, newest-first and lean run reads to customer-success inspection (#22781)
  fix(connections): keep a finished setup checklist on screen when the app refreshes queries (#22715)
  perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
  fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732)
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 13:21:12 -06:00
commit 3cbfa500f4
142 files changed
+5552 -11636

No files matched your search

@@ -154,6 +154,18 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
transactionReads++;
return registry.getCustomerSuccessAccount(id);
},
getStacks: async (ids: readonly string[]) => {
await client.query("SELECT 1");
transactionReads++;
return (await Promise.all(ids.map((id) => registry.getStack(id)))).filter(Boolean);
},
getAccounts: async (ids: readonly string[]) => {
await client.query("SELECT 1");
transactionReads++;
return (
await Promise.all(ids.map((id) => registry.getCustomerSuccessAccount(id)))
).filter(Boolean);
},
listStackIds: async () => registry.listCustomerSuccessStackIds(),
});
const store = new PostgresInspectionStore(pool, registryForClient);
@@ -272,7 +284,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
const grant=await call('grant',{stackId:'qualification-stack'});
const tasks=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
const file=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'files.download',companyId:${JSON.stringify(customer.id)},resourceId:${JSON.stringify(task.id)},context:{projectId:${JSON.stringify(project.id)},workspaceId:${JSON.stringify(workspace.id)}},path:'result.bin',range:{start:2,end:5}}});
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')]}));
const taskCount=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'count',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
const latestRuns=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'runs',companyId:${JSON.stringify(customer.id)},order:'newest',view:'summary',limit:1}});
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')],taskCount,latestRuns}));
`;
const programFile = join(directory, "qualify.mjs");
await writeFile(programFile, program);
@@ -298,6 +312,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
expect(result.exitCode, [...output, ...serverErrors].join("\n")).toBe(0);
expect(output.join("")).toContain("First successful task");
expect(output.join("")).toContain('"fileBytes":[2,3,4,5]');
// Count and newest-first summary reads travel the extended tenant path.
expect(output.join("")).toContain('"taskCount":{"total":1,"byStatus":{');
expect(output.join("")).toContain('"latestRuns":{"items":[],"nextOffset":null}');
expect((await stat(filePath)).mtimeMs).toBe(fileBefore.mtimeMs);
expect(await readFile(filePath)).toEqual(Buffer.from([0, 1, 2, 3, 4, 5]));
const audit = await pool.query(
@@ -13,6 +13,7 @@ import {
INSPECTION_HEADER,
INSPECTION_PERMIT_TYPE,
INSPECTION_RESOURCES,
inspectionReadPath,
parseInspectionQuery,
type InspectionQuery,
type InspectionPermit,
@@ -21,6 +22,8 @@ import { customerSuccessRunAuthority } from "../services/customer-success-author
import {
readCustomerSuccessResource,
inspectionReaders,
RUN_SUMMARY_COLUMNS,
primaryKeyColumns,
} from "../services/customer-success-inspection.js";
import {
customerSuccessRoutes,
@@ -438,6 +441,29 @@ describe("customer-success read authority", () => {
expect((await request(app).post("/api/customer-success/v1/unknown").send({})).status).toEqual(
404,
);
// Count, order and view live only on the extended path, so a tenant that
// predates them answers 404 there and Cloud fails closed.
const countQuery: InspectionQuery = { operation: "count", resource: "tasks", companyId };
const countToken = () => token({ ...claims, jti: randomUUID(), query: countQuery });
expect(
(
await request(app)
.post("/api/customer-success/v1/read")
.set(INSPECTION_HEADER, countToken())
.send(countQuery)
).status,
).toEqual(403);
const counted = await request(app)
.post("/api/customer-success/v1/read-v2")
.set(INSPECTION_HEADER, countToken())
.send(countQuery);
expect(counted.status).toEqual(200);
expect(counted.body).toEqual({ total: expect.any(Number), byStatus: expect.any(Object) });
const original = await request(app)
.post("/api/customer-success/v1/read-v2")
.set(INSPECTION_HEADER, token())
.send(query);
expect(original.status).toEqual(200);
fetcher.mockResolvedValue(new Response("", { status: 503 }));
expect(
(
@@ -692,6 +718,153 @@ describe("customer-success read authority", () => {
})) as { items: unknown[] };
expect(versions.items).toHaveLength(1);
});
it("counts by status, orders newest first, and returns lean run summaries, company scoped", async () => {
const [company, other] = await db
.insert(schema.companies)
.values([
{ name: "Counted", issuePrefix: "CNT" },
{ name: "Elsewhere", issuePrefix: "ELS" },
])
.returning();
const [countedAgent] = await db
.insert(schema.agents)
.values({ companyId: company.id, name: "Counted agent", adapterType: "process" })
.returning();
const [otherAgent] = await db
.insert(schema.agents)
.values({ companyId: other.id, name: "Other agent", adapterType: "process" })
.returning();
const heavy = { transcript: "x".repeat(200_000) };
const at = (minutes: number) => new Date(Date.UTC(2026, 0, 1, 0, minutes));
const runs = await db
.insert(schema.heartbeatRuns)
.values([
{ companyId: company.id, agentId: countedAgent.id, status: "succeeded", createdAt: at(1), startedAt: at(1), finishedAt: at(3), resultJson: heavy, contextSnapshot: heavy },
{ companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(5), startedAt: at(5), finishedAt: at(6), errorCode: "adapter_failed", resultJson: heavy },
{ companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(9), startedAt: at(9), resultJson: heavy },
{ companyId: other.id, agentId: otherAgent.id, status: "failed", createdAt: at(20) },
])
.returning();
await db.insert(schema.issues).values([
{ companyId: company.id, title: "Open", status: "todo" },
{ companyId: company.id, title: "Shipped", status: "done" },
{ companyId: other.id, title: "Not ours", status: "done" },
]);
expect(
await readCustomerSuccessResource(db, storage, { operation: "count", resource: "runs", companyId: company.id }),
).toEqual({ total: 3, byStatus: { succeeded: 1, failed: 2 } });
expect(
await readCustomerSuccessResource(db, storage, { operation: "count", resource: "tasks", companyId: company.id }),
).toEqual({ total: 2, byStatus: { todo: 1, done: 1 } });
expect(
await readCustomerSuccessResource(db, storage, {
operation: "count",
resource: "comments",
companyId: company.id,
}),
).toEqual({ total: 0, byStatus: null });
const latest = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "runs",
companyId: company.id,
order: "newest",
view: "summary",
limit: 1,
})) as { items: Array<Record<string, unknown>>; nextOffset: number | null };
expect(latest.items.map((r) => r.id)).toEqual([runs[2].id]);
expect(latest.nextOffset).toEqual(1);
expect(Object.keys(latest.items[0]).sort()).toEqual([...RUN_SUMMARY_COLUMNS, "durationMs"].sort());
expect(latest.items[0].durationMs).toBeNull();
expect(JSON.stringify(latest).length).toBeLessThan(2_000);
const page = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "runs",
companyId: company.id,
order: "newest",
view: "summary",
limit: 2,
offset: 1,
})) as { items: Array<Record<string, unknown>> };
expect(page.items.map((r) => [r.id, r.durationMs])).toEqual([
[runs[1].id, 60_000],
[runs[0].id, 120_000],
]);
const oldest = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "runs",
companyId: company.id,
order: "oldest",
limit: 1,
})) as { items: Array<Record<string, unknown>> };
expect(oldest.items[0].id).toEqual(runs[0].id);
expect(oldest.items[0]).toHaveProperty("resultJson");
const one = (await readCustomerSuccessResource(db, storage, {
operation: "get",
resource: "runs",
companyId: company.id,
resourceId: runs[1].id,
view: "summary",
})) as Record<string, unknown>;
expect(one).toMatchObject({ id: runs[1].id, status: "failed", errorCode: "adapter_failed", durationMs: 60_000 });
expect(one).not.toHaveProperty("resultJson");
expect(one).not.toHaveProperty("contextSnapshot");
});
it("ordered pages cover rows that share a creation time exactly once", async () => {
for (const resource of INSPECTION_RESOURCES)
expect(primaryKeyColumns(inspectionReaders[resource].table).length, resource).toBeGreaterThan(0);
const [company] = await db
.insert(schema.companies)
.values({ name: "Labelled", issuePrefix: "LBL" })
.returning();
const [issue] = await db.insert(schema.issues).values({ companyId: company.id, title: "Tagged" }).returning();
const labels = await db
.insert(schema.labels)
.values(Array.from({ length: 5 }, (_, i) => ({ companyId: company.id, name: `label-${i}`, color: "#000000" })))
.returning();
const createdAt = new Date(Date.UTC(2026, 0, 2));
await db
.insert(schema.issueLabels)
.values(labels.map((label) => ({ companyId: company.id, issueId: issue.id, labelId: label.id, createdAt })));
for (const order of ["newest", "oldest"] as const) {
const seen: string[] = [];
for (let offset = 0; offset < labels.length; offset += 2) {
const page = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "taskLabels",
companyId: company.id,
order,
limit: 2,
offset,
})) as { items: Array<{ labelId: string }> };
seen.push(...page.items.map((row) => row.labelId));
}
expect(seen.sort()).toEqual(labels.map((label) => label.id).sort());
}
});
it("count, order and view are bounded and take the extended read path", () => {
expect(inspectionReadPath(parseInspectionQuery({ operation: "list", resource: "runs", companyId }))).toEqual("/read");
for (const value of [
{ operation: "count", resource: "runs", companyId },
{ operation: "list", resource: "runs", companyId, order: "newest" },
{ operation: "get", resource: "runs", companyId, resourceId: agentId, view: "summary" },
])
expect(inspectionReadPath(parseInspectionQuery(value))).toEqual("/read-v2");
for (const value of [
{ operation: "count", companyId },
{ operation: "count", resource: "runs" },
{ operation: "count", resource: "runs", companyId, resourceId: agentId },
{ operation: "get", resource: "runs", companyId, resourceId: agentId, order: "newest" },
{ operation: "list", resource: "runs", companyId, order: "random" },
{ operation: "list", resource: "tasks", companyId, view: "summary" },
{ operation: "list", resource: "runs", companyId, view: "full" },
{ operation: "runs.log", companyId, resourceId: agentId, view: "summary" },
])
expect(() => parseInspectionQuery(value)).toThrow();
});
it("the operation contract has no writes, credentials or unknown parameters", () => {
for (const value of [
{ operation: "write", companyId },
@@ -280,6 +280,7 @@ const support = await getEmbeddedPostgresTestSupport();
const audit = await db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, f.company.id), eq(toolAccessAuditEvents.action, "call_completed")));
expect(audit).toHaveLength(1);
expect(JSON.stringify(audit[0])).toContain("Google Workspace REST");
expect(JSON.stringify(audit[0])).not.toContain("mcpMethod");
expect(JSON.stringify([invocation, audit])).not.toContain("workspace-access-1");
});
@@ -0,0 +1,206 @@
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { and, eq } from "drizzle-orm";
import {
agents,
agentWakeupRequests,
companies,
completionContracts,
createDb,
heartbeatRuns,
issueThreadInteractions,
issues,
statusDecisions,
workspaceOperations,
} from "@paperclipai/db";
import { CONTROL_PLANE_CONFORMANCE_OPEN } from "../vendor/paperclip-runner/testing.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
import { documentService } from "../services/documents.js";
import { recoveryService } from "../services/recovery/service.js";
const cardFailure = vi.hoisted(() => ({ next: false }));
vi.mock("../services/native-runtime/native-plan-review-card.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-review-card.js")>();
return {
...actual,
ensureNativePlanReviewCard: async (...args: Parameters<typeof actual.ensureNativePlanReviewCard>) => {
if (cardFailure.next) {
cardFailure.next = false;
throw new Error("connection reset while opening the card");
}
return actual.ensureNativePlanReviewCard(...args);
},
};
});
const committedPlanWait = vi.hoisted(() => ({ runIds: new Set<string>() }));
vi.mock("../services/native-runtime/native-plan-wait.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-wait.js")>();
return {
...actual,
hasCommittedNativePlanWait: async (...args: Parameters<typeof actual.hasCommittedNativePlanWait>) =>
committedPlanWait.runIds.has(args[1].runId) || actual.hasCommittedNativePlanWait(...args),
};
});
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_FINALIZER_TEST_DATABASE_URL");
// The live failure: the Antigravity process was killed mid Plan-mode run; the
// automatic continuation wrote a new plan revision and yielded "waiting for
// plan review" without opening the Approve / Request changes card. The task
// sat in progress with nothing for the user to act on.
describe("Plan-mode run settle opens the plan review", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const companyId = "72300000-0000-4000-8000-000000000001";
const agentId = "72300000-0000-4000-8000-000000000002";
let seq = 0;
beforeAll(async () => {
if (!external) temporary = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-finalizer-");
db = createDb(external ?? temporary.connectionString);
await db.insert(companies).values({ id: companyId, name: "Plan review", issuePrefix: "PRF" });
await db.insert(agents).values({ id: agentId, companyId, name: "Gemma Antigravity", adapterType: "antigravity_local", status: "running" });
}, 30_000);
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await temporary?.cleanup();
});
const yielded = {
schema: "paperclip.run_result.v1" as const,
reportedWorkDisposition: "yielded" as const,
summary: "Saved the plan. Waiting for plan review before executing.",
completionClaim: {
contractRevision: "plan-v1", objectiveSatisfied: false,
criteria: [{ criterionId: "objective", status: "unknown" as const, evidenceRefs: [] }],
remainingWork: [],
},
evidence: [], verification: [], attentionRequests: [], artifacts: [],
continuation: { kind: "response_wake" as const, summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
};
async function settleRun(options: { workMode: "planning" | "standard"; writePlan: boolean }) {
seq += 1;
const id = (n: number) => `72300000-0000-4000-8${String(seq).padStart(3, "0")}-${String(n).padStart(12, "0")}`;
const issueId = id(1), contractId = id(2), runId = id(3);
await db.insert(issues).values({ id: issueId, companyId, title: `Plan ${seq}`, status: "in_progress",
assigneeAgentId: agentId, workMode: options.workMode });
await db.insert(completionContracts).values({
id: contractId, companyId, issueId, revision: 1,
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v1", risk: "standard",
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",
contractJson: { revision: "plan-v1", objective: "Plan the file",
criteria: [{ id: "objective", requirement: "The plan is approved" }] },
canonicalSha256: `plan-contract-${seq}`, createdByActorType: "system", createdByActorId: "test",
});
await db.insert(heartbeatRuns).values({
id: runId, companyId, agentId, status: "running", runtimeMode: "native",
runtimeModeReason: "persisted_before_kill_switch", nativeIssueId: issueId, nativeSessionId: runId,
runnerInstanceId: contractId, completionContractId: contractId,
completionContractSha256: `plan-contract-${seq}`, contextSnapshot: { issueId },
});
if (options.writePlan) {
await documentService(db).upsertIssueDocument({ issueId, key: "plan", title: "Plan", format: "markdown",
body: "# Create crash-proof.txt\n\n1. Write CRASH.", createdByAgentId: agentId, createdByRunId: runId });
}
const port = new PaperclipControlPlanePort(db, {
companyId, issueId, runId, agentId, sessionId: runId, completionContractId: contractId,
completionContractSha256: `plan-contract-${seq}`, sourceInstanceId: contractId,
controlPlaneSourceInstanceId: `plan-control-${seq}`,
});
await port.openRun({ ...CONTROL_PLANE_CONFORMANCE_OPEN,
identity: { companyId, issueId, runId, agentId, sessionId: runId }, sourceInstanceId: contractId });
await port.completeRun({ result: yielded, terminal: { schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "yielded" },
callerResultId: `plan-result-${seq}` });
await db.insert(workspaceOperations).values({ companyId, heartbeatRunId: runId, issueId,
phase: "workspace_finalize", status: "succeeded" });
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, issue!.lastStatusDecisionId!));
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId));
const wakes = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
eq(agentWakeupRequests.agentId, agentId)));
return { issueId, runId, issue: issue!, decision: decision!, cards,
wakes: wakes.filter(wake => JSON.stringify(wake.payload ?? {}).includes(issueId)) };
}
it("opens one review card for the new plan revision and waits on it", async () => {
const settled = await settleRun({ workMode: "planning", writePlan: true });
expect(settled.cards).toHaveLength(1);
expect(settled.cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending", sourceRunId: settled.runId });
expect(settled.cards[0]!.payload).toMatchObject({ target: { type: "issue_document", key: "plan", revisionNumber: 1 } });
expect(settled.issue.status).toBe("in_review");
expect(settled.decision.reasonCode).toBe("governed_response_waiting");
});
it("asks the agent for its plan when a Plan-mode run yields with none", async () => {
const settled = await settleRun({ workMode: "planning", writePlan: false });
expect(settled.cards).toHaveLength(0);
expect(settled.decision.reasonCode).toBe("plan_mode_plan_not_produced");
expect(settled.wakes.some(wake => JSON.stringify(wake.payload).includes("Plan mode"))).toBe(true);
});
it("gives a task left without its card by an older release one on the next recovery pass", async () => {
const settled = await settleRun({ workMode: "planning", writePlan: true });
// The state an older release left: settled, waiting, no card.
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
const enqueueWakeup = vi.fn(async () => null);
const recovery = recoveryService(db, { enqueueWakeup });
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
expect(cards).toHaveLength(1);
expect(cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending" });
expect(enqueueWakeup).not.toHaveBeenCalled();
});
it("settles the run when opening the card fails, and the next recovery pass opens it", async () => {
cardFailure.next = true;
const settled = await settleRun({ workMode: "planning", writePlan: true });
expect(settled.cards).toHaveLength(0);
expect(settled.issue.status).toBe("in_progress");
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
expect(run).toMatchObject({ status: "succeeded" });
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
expect(cards).toEqual([expect.objectContaining({ kind: "request_confirmation", status: "pending" })]);
});
it.each(["finalization reason", "committed plan wait"])("never opens a second card for a plan the user already accepted (%s)", async (proof) => {
const settled = await settleRun({ workMode: "planning", writePlan: true });
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
if (proof === "finalization reason") {
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
await db.update(heartbeatRuns).set({ resultJson: { ...(run!.resultJson as Record<string, unknown>),
finalizationReasonCode: "native_plan_accepted_waiting_for_continuation" } }).where(eq(heartbeatRuns.id, settled.runId));
} else committedPlanWait.runIds.add(settled.runId);
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId))).toHaveLength(0);
});
it("leaves a Standard-mode response wait unchanged", async () => {
const settled = await settleRun({ workMode: "standard", writePlan: true });
expect(settled.cards).toHaveLength(0);
expect(settled.issue.status).toBe("in_progress");
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
});
});
@@ -0,0 +1,543 @@
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
companies,
createDb,
documentRevisions,
documents,
goals,
heartbeatRuns,
issueComments,
issueDocuments,
issueThreadInteractions,
issues,
} from "@paperclipai/db";
import { ensureNativePlanReviewCard, planReviewCardIdempotencyKey } from "../services/native-runtime/native-plan-review-card.js";
import { synchronizeCompletedProviderPlan } from "../services/native-runtime/native-session-executor.js";
import { documentService } from "../services/documents.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
// Lets a test hand the card function the document as it was read before a
// newer revision landed: the window a delayed settle runs in.
const staleRead = vi.hoisted(() => ({ next: null as unknown }));
vi.mock("../services/documents.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/documents.js")>();
return {
...actual,
documentService: (db: Parameters<typeof actual.documentService>[0]) => {
const service = actual.documentService(db);
return {
...service,
getIssueDocumentByKey: async (...args: Parameters<typeof service.getIssueDocumentByKey>) => {
if (staleRead.next) {
const snapshot = staleRead.next;
staleRead.next = null;
return snapshot as Awaited<ReturnType<typeof service.getIssueDocumentByKey>>;
}
return service.getIssueDocumentByKey(...args);
},
};
},
};
});
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_CARD_TEST_DATABASE_URL");
const embeddedPostgresSupport = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const PLAN = "# Create crash-proof.txt\n\n1. Write the file.\n2. Verify it.";
// Harnesses without a provider plan event (Antigravity and other ACPX agents)
// write the Plan document with a tool. A Plan-mode run that settles without
// opening the review card — for example a run recovered after its process was
// killed — must not leave the task waiting on a review nobody can give.
describeEmbeddedPostgres("Plan-mode review card on settle", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-card-");
db = createDb(external ?? tempDb!.connectionString, { maxConnections: 6 });
}, 20_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(issueComments);
await db.delete(issueThreadInteractions);
await db.delete(issueDocuments);
await db.delete(documentRevisions);
await db.delete(documents);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(goals);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
let prefix = 0;
async function seed(workMode: "standard" | "planning" = "planning", options: { conversation?: boolean } = {}) {
const companyId = randomUUID();
const goalId = randomUUID();
const issueId = randomUUID();
const agentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: `PRC${++prefix}`, requireBoardApprovalForNewAgents: false });
await db.insert(goals).values({ id: goalId, companyId, title: "Ship", level: "task", status: "active" });
await db.insert(agents).values({
id: agentId, companyId, name: "Gemma", role: "engineer", status: "active",
adapterType: "antigravity_local", adapterConfig: {}, runtimeConfig: {}, permissions: {},
});
await db.insert(issues).values({
id: issueId, companyId, goalId, title: "Create crash-proof.txt", status: "in_progress",
priority: "medium", assigneeAgentId: agentId, workMode,
...(options.conversation ? { conversationAgentId: agentId, conversationUserId: "local-board", conversationState: "active" } : {}),
});
const newRun = async () => {
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", contextSnapshot: { issueId } });
return runId;
};
const binding = (runId: string) => ({ companyId, issueId, agentId, runId });
const writePlan = async (runId: string, body = PLAN) => documentService(db).upsertIssueDocument({
issueId, key: "plan", title: "Plan", format: "markdown", body,
baseRevisionId: (await documentService(db).getIssueDocumentByKey(issueId, "plan"))?.latestRevisionId ?? undefined,
createdByAgentId: agentId, createdByRunId: runId,
} as never);
const cards = () => db.select().from(issueThreadInteractions)
.where(and(eq(issueThreadInteractions.issueId, issueId), eq(issueThreadInteractions.kind, "request_confirmation")));
return { companyId, issueId, agentId, newRun, binding, writePlan, cards };
}
it("opens exactly one review card for a recovered run's new plan revision", async () => {
const t = await seed();
await t.newRun(); // the killed run
const recovered = await t.newRun();
await t.writePlan(recovered);
const outcome = await ensureNativePlanReviewCard(db, t.binding(recovered));
expect(outcome.kind).toBe("created");
const cards = await t.cards();
expect(cards).toHaveLength(1);
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
expect(cards[0]).toMatchObject({ status: "pending", sourceRunId: recovered, createdByAgentId: t.agentId });
expect(cards[0]!.payload).toMatchObject({
acceptLabel: "Approve plan", rejectLabel: "Request changes",
target: { type: "issue_document", key: "plan", revisionId: plan!.latestRevisionId, revisionNumber: 1 },
});
const activity = await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId));
expect(activity).toEqual([expect.objectContaining({ action: "issue.thread_interaction_created", actorType: "system" })]);
});
// The agent's plan card opened as instructed: bound to the saved plan revision.
async function agentPlanCard(t: Awaited<ReturnType<typeof seed>>, runId: string, key: string) {
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
return issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee",
payload: { version: 1, prompt: "Approve the plan?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
revisionId: plan!.latestRevisionId, revisionNumber: plan!.latestRevisionNumber } },
} as never, { agentId: t.agentId, runId });
}
const plainCard = (t: Awaited<ReturnType<typeof seed>>, runId: string, key: string, prompt: string) =>
issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee_on_accept",
payload: { version: 1, prompt, acceptLabel: "Confirm", rejectLabel: "Request changes" },
} as never, { agentId: t.agentId, runId });
it("does nothing when the agent already opened its plan card for the revision", async () => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
await agentPlanCard(t, runId, "confirm-plan-v1");
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending" });
expect(await t.cards()).toHaveLength(1);
});
it("keeps one card across repeated and concurrent settles of the same and later runs", async () => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
const reconcileRun = await t.newRun();
const outcomes = await Promise.all([
ensureNativePlanReviewCard(db, t.binding(runId)),
ensureNativePlanReviewCard(db, t.binding(runId)),
ensureNativePlanReviewCard(db, t.binding(reconcileRun)),
]);
await ensureNativePlanReviewCard(db, t.binding(runId));
await ensureNativePlanReviewCard(db, t.binding(reconcileRun));
expect(outcomes.filter(outcome => outcome.kind === "created")).toHaveLength(1);
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId))).toHaveLength(1);
const cards = await t.cards();
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
expect(cards).toHaveLength(1);
});
it("opens a new card for the revision written after Request changes and leaves the old one unanswerable", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
const created = await ensureNativePlanReviewCard(db, t.binding(first));
if (created.kind !== "created") throw new Error("expected a card");
const interactions = issueThreadInteractionService(db);
const [oldCard] = await t.cards();
await interactions.rejectInteraction(
{ id: t.issueId, companyId: t.companyId }, oldCard!.id,
{ reason: "Name the file crash-proof-2.txt" } as never, { userId: "local-board" } as never,
);
// Request changes answered this revision: nothing new until the agent revises.
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "reviewed" });
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Use crash-proof-2.txt.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
const cards = await t.cards();
expect(cards).toHaveLength(2);
const pending = cards.filter(card => card.status === "pending");
expect(pending).toHaveLength(1);
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("rejected");
});
it("replaces a still-pending card for an older revision", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
await ensureNativePlanReviewCard(db, t.binding(first));
const [oldCard] = await t.cards();
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Revised.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
const cards = await t.cards();
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("expired");
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
await expect(interactionsAccept(t, oldCard!.id)).rejects.toThrow();
});
it("never withdraws a newer revision's card from a delayed settle of an older one", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
const revisionOne = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Revised.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
// The first run's settle read revision 1 before revision 2 landed.
staleRead.next = revisionOne;
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "not_applicable" });
const cards = await t.cards();
expect(cards).toHaveLength(1);
expect(cards[0]).toMatchObject({ status: "pending" });
expect(cards[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
});
it("withdraws the agent's plan card for v1 when a recovered run writes v2, leaving one answerable card", async () => {
const t = await seed();
const crashed = await t.newRun();
await t.writePlan(crashed);
const v1 = await agentPlanCard(t, crashed, "own-v1");
const recovered = await t.newRun();
await t.writePlan(recovered, `${PLAN}\n3. Revised after recovery.`);
await expect(ensureNativePlanReviewCard(db, t.binding(recovered))).resolves.toMatchObject({ kind: "created" });
const pending = (await t.cards()).filter(card => card.status === "pending");
expect(pending).toHaveLength(1);
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
await expect(interactionsAccept(t, v1.id)).rejects.toThrow();
});
it("keeps an unrelated confirmation opened after the plan ordinary: answering it never approves the plan", async () => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
const unrelated = await plainCard(t, runId, "rename-repo", "May I rename the repository?");
expect((unrelated.payload as { target?: unknown }).target).toBeUndefined();
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "created" });
await interactionsAccept(t, unrelated.id);
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
expect(issue!.workMode).toBe("planning");
const planCards = (await t.cards()).filter(card => (card.payload as { target?: { key?: string } }).target?.key === "plan");
expect(planCards).toEqual([expect.objectContaining({ status: "pending" })]);
});
it("leaves a card opened before plan binding existed answerable, and still opens the current plan's card", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
// A row an older release saved: the agent's plan card with no target.
const [legacy] = await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "pending",
continuationPolicy: "wake_assignee_on_accept", sourceRunId: first, createdByAgentId: t.agentId,
payload: { version: 1, prompt: "Proceed with plan v1?", acceptLabel: "Confirm", rejectLabel: "Request changes" },
}).returning();
const second = await t.newRun();
await new Promise(resolve => setTimeout(resolve, 5));
await t.writePlan(second, `${PLAN}\n3. Revised.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
const cards = await t.cards();
// Not withdrawn by guess; its answer reaches the agent as an ordinary confirmation.
expect(cards.find(card => card.id === legacy!.id)?.status).toBe("pending");
expect(cards.filter(card => card.status === "pending" &&
(card.payload as { target?: { revisionNumber?: number } }).target?.revisionNumber === 2)).toHaveLength(1);
// Accepting the old card does not approve the newer revision.
await interactionsAccept(t, legacy!.id);
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
expect(issue!.workMode).toBe("planning");
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
});
it.each(["server", "agent"])("keeps run A's pending %s plan card as the gate when run B settles a Plan-mode conversation", async (opener) => {
const t = await seed("planning", { conversation: true });
const first = await t.newRun();
await t.writePlan(first);
if (opener === "server") await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "created" });
else await agentPlanCard(t, first, "conversation-plan");
const second = await t.newRun();
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "pending" });
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
});
async function interactionsAccept(t: Awaited<ReturnType<typeof seed>>, id: string) {
return issueThreadInteractionService(db).acceptInteraction(
{ id: t.issueId, companyId: t.companyId, projectId: null, goalId: null }, id, {} as never, { userId: "local-board" } as never,
);
}
it("returns the original card for an identical retry after a plan revision landed", async () => {
const t = await seed();
const runId = await t.newRun();
const first = await plainCard(t, runId, "retry-key", "May I proceed?");
// The response was lost; meanwhile the agent saved its plan.
await t.writePlan(runId);
const retried = await plainCard(t, runId, "retry-key", "May I proceed?");
expect(retried.id).toBe(first.id);
});
it("reports a Plan-mode run with no plan, and leaves Standard tasks untouched", async () => {
const planning = await seed();
const runId = await planning.newRun();
await expect(ensureNativePlanReviewCard(db, planning.binding(runId))).resolves.toEqual({ kind: "no_plan" });
expect(await planning.cards()).toHaveLength(0);
const standard = await seed("standard");
const standardRun = await standard.newRun();
await standard.writePlan(standardRun);
await expect(ensureNativePlanReviewCard(db, standard.binding(standardRun))).resolves.toEqual({ kind: "not_applicable" });
expect(await standard.cards()).toHaveLength(0);
});
it("leaves the card Codex and Claude open from their plan event as the only card", async () => {
const t = await seed();
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: t.companyId, agentId: t.agentId, status: "running", contextSnapshot: { issueId: t.issueId } });
const synced = await synchronizeCompletedProviderPlan({
db,
execution: {
binding: t.binding(runId), provider: { kind: "codex" }, task: { workMode: "planning" }, executionMode: "plan",
planningContext: { documentId: null, baseRevisionId: null, baseRevisionNumber: 0, markdown: "", sha256: "none", reviewContext: {} },
} as never,
event: { sourceEventId: "event-1", turnId: "turn-1", eventType: "plan.proposed",
payload: { schema: "paperclip.plan.proposed.v1", proposalId: "plan-1", status: "completed", markdown: PLAN, source: "codex" } },
});
expect(synced).toMatchObject({ status: "synchronized" });
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending", interactionId: synced!.confirmationId });
expect(await t.cards()).toHaveLength(1);
});
it("does not put a person's own plan edit up for review", async () => {
const t = await seed();
const runId = await t.newRun();
await documentService(db).upsertIssueDocument({
issueId: t.issueId, key: "plan", title: "Plan", format: "markdown", body: "# My plan", createdByUserId: "local-board",
});
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toEqual({ kind: "not_applicable" });
expect(await t.cards()).toHaveLength(0);
});
// Each way a Plan-mode run can leave the task, and the one current action
// the user gets: a review card for the revision, or (no plan / already
// answered) the arbiter's "save your plan" continuation.
type Scenario = { name: string; setup: (t: Awaited<ReturnType<typeof seed>>, runId: string) => Promise<void>;
kind: "created" | "pending" | "reviewed" | "no_plan" };
const question = async (t: Awaited<ReturnType<typeof seed>>, runId: string) => {
const [row] = await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "ask_user_questions", status: "pending",
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
payload: { version: 1, questions: [{ id: "q1", prompt: "Which name?", selectionMode: "single",
options: [{ id: "a", label: "A" }] }] },
}).returning();
return row!;
};
const scenarios: Scenario[] = [
{ name: "no plan saved", setup: async () => {}, kind: "no_plan" },
{ name: "plan saved, agent opened no card (first run or recovered run)", setup: async (t, runId) => { await t.writePlan(runId); }, kind: "created" },
{ name: "plan saved, agent opened its plan card bound to the revision", setup: async (t, runId) => {
await t.writePlan(runId); await agentPlanCard(t, runId, `own-${runId}`);
}, kind: "pending" },
{ name: "plan saved, agent opened an unbound confirmation (ordinary, not a plan review)", setup: async (t, runId) => {
await t.writePlan(runId); await plainCard(t, runId, `plain-${runId}`, "Proceed?");
}, kind: "created" },
{ name: "plan saved, agent asked a current question", setup: async (t, runId) => {
await t.writePlan(runId); await question(t, runId);
}, kind: "pending" },
{ name: "plan saved, an older question a later comment made historical", setup: async (t, runId) => {
await question(t, runId);
await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
authorUserId: "local-board", body: "Use A.", createdAt: new Date(Date.now() + 1_000) });
await t.writePlan(runId);
}, kind: "created" },
{ name: "plan saved, an older question the user dismissed", setup: async (t, runId) => {
const row = await question(t, runId);
await db.update(issueThreadInteractions).set({ dismissedAt: new Date(), dismissedByUserId: "local-board" })
.where(eq(issueThreadInteractions.id, row.id));
await t.writePlan(runId);
}, kind: "created" },
...(["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"] as const).flatMap(key =>
(["pending", "accepted", "rejected"] as const).map((status): Scenario => ({
name: `plan saved, an unrelated ${key} card (${status}) opened after it`,
setup: async (t, runId) => {
await t.writePlan(runId);
await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status,
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
payload: { version: 1, prompt: "Allow this?", [key]: { id: "governed" } },
});
},
kind: "created",
}))),
{ name: "plan saved, a confirmation someone else opened after it", setup: async (t, runId) => {
await t.writePlan(runId);
await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "rejected",
continuationPolicy: "none", createdByUserId: "local-board",
payload: { version: 1, prompt: "Unrelated?" },
});
}, kind: "created" },
{ name: "revision already answered with Request changes, no new revision", setup: async (t, runId) => {
await t.writePlan(runId);
await ensureNativePlanReviewCard(db, t.binding(runId));
const [card] = await t.cards();
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
}, kind: "reviewed" },
{ name: "new revision after Request changes", setup: async (t, runId) => {
await t.writePlan(runId);
await ensureNativePlanReviewCard(db, t.binding(runId));
const [card] = await t.cards();
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
await t.writePlan(runId, `${PLAN}\n3. Renamed.`);
}, kind: "created" },
];
it.each(scenarios)("$name", async ({ setup, kind }) => {
const t = await seed();
const runId = await t.newRun();
await setup(t, runId);
const outcome = await ensureNativePlanReviewCard(db, t.binding(runId));
expect(outcome.kind).toBe(kind);
// A repeat settle changes nothing, and at most one review card is pending.
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({
kind: kind === "created" ? "pending" : kind });
const planReviews = (await t.cards()).filter(card => card.status === "pending" &&
(card.payload as { target?: { key?: string } }).target?.key === "plan");
expect(planReviews.length).toBeLessThanOrEqual(1);
if (kind === "created") expect(planReviews).toHaveLength(1);
});
// Every state the current revision's own plan card can reach, and what the
// user is left with: a current card, or (they decided) the agent's bounded
// "revise your plan" continuation. Never a silent wait, never a second card
// for a plan the user already accepted.
type CardState = { status: string; by?: "user" | "agent" | "system"; dismissed?: boolean; laterComment?: boolean;
outcome: "pending" | "reviewed" | "created" };
const cardStates: CardState[] = [
{ status: "pending", outcome: "pending" },
{ status: "pending", dismissed: true, outcome: "pending" },
{ status: "pending", laterComment: true, outcome: "pending" },
{ status: "accepted", by: "user", outcome: "reviewed" },
{ status: "rejected", by: "user", outcome: "reviewed" },
{ status: "cancelled", by: "user", outcome: "reviewed" },
{ status: "cancelled", by: "agent", outcome: "created" },
{ status: "expired", by: "system", outcome: "created" },
{ status: "expired", by: "agent", outcome: "created" },
{ status: "failed", by: "system", outcome: "created" },
];
it.each(cardStates)("current revision's card $status (by $by, dismissed $dismissed, later comment $laterComment) -> $outcome",
async ({ status, by, dismissed, laterComment, outcome }) => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
const resolved = status !== "pending";
const [card] = await db.insert(issueThreadInteractions).values(<typeof issueThreadInteractions.$inferInsert>{
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: status as never,
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
idempotencyKey: planReviewCardIdempotencyKey(plan!.latestRevisionId!),
payload: { version: 1, prompt: "Approve plan revision 1?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
revisionId: plan!.latestRevisionId, revisionNumber: 1 } },
...(resolved ? { resolvedAt: new Date(),
resolvedByUserId: by === "user" ? "local-board" : null,
resolvedByAgentId: by === "agent" ? t.agentId : null } : {}),
...(dismissed ? { dismissedAt: new Date(), dismissedByUserId: "local-board" } : {}),
}).returning();
if (laterComment) await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
authorUserId: "local-board", body: "Looking now.", createdAt: new Date(Date.now() + 1_000) });
const first = await ensureNativePlanReviewCard(db, t.binding(runId));
expect(first.kind).toBe(outcome);
const again = await ensureNativePlanReviewCard(db, t.binding(await t.newRun()));
expect(again.kind).toBe(outcome === "created" ? "pending" : outcome);
const pending = (await t.cards()).filter(row => row.status === "pending");
if (outcome === "reviewed") expect(pending).toHaveLength(0);
else expect(pending).toHaveLength(1);
if (outcome === "created") expect(pending[0]!.id).not.toBe(card!.id);
});
it("opens exactly one card for the current revision when settles race across a revision change", async () => {
for (let round = 0; round < 15; round += 1) {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
await ensureNativePlanReviewCard(db, t.binding(first));
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Round ${round}.`);
const runs = await Promise.all([t.newRun(), t.newRun(), t.newRun()]);
await Promise.all([second, ...runs].map(runId => ensureNativePlanReviewCard(db, t.binding(runId))));
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
const pending = (await t.cards()).filter(card => card.status === "pending");
expect(pending).toHaveLength(1);
expect(pending[0]!.payload).toMatchObject({ target: { revisionId: plan!.latestRevisionId } });
}
});
});
@@ -153,6 +153,7 @@ const explicitOpenApiOperationCoverageExclusions = new Set([
// Ordinary board sessions and agent API keys cannot invoke these endpoints.
"GET /api/customer-success/v1/run-authority",
"POST /api/customer-success/v1/read",
"POST /api/customer-success/v1/read-v2",
"POST /api/customer-success/v1/run-liveness",
// OAuth discovery and protocol endpoints have their own metadata contract;
// browser connection-management operations remain documented in the board API.
+12 -3
View File
@@ -1,9 +1,11 @@
import { createPublicKey, verify } from "node:crypto";
import { Router } from "express";
import { Router, type Request as ExpressRequest, type Response as ExpressResponse } from "express";
import type { Db } from "@paperclipai/db";
import {
canonicalJson,
inspectionReadPath,
parseInspectionQuery,
INSPECTION_READ_PATH,
INSPECTION_AUDIENCE,
INSPECTION_PERMIT_TYPE,
INSPECTION_HEADER,
@@ -180,7 +182,10 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
if (!match) throw forbidden("Managed run bearer required");
res.json(await customerSuccessRunAuthority(db, match[1]));
});
router.post("/read", async (req, res) => {
// `/read` serves the original query features; `/read-v2` also serves
// count, order and view. Cloud picks the path from the query, so a tenant
// without `/read-v2` answers 404 and Cloud fails closed.
const read = async (req: ExpressRequest, res: ExpressResponse) => {
if (process.env.PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED !== "true")
throw forbidden("Inspection is disabled");
if (req.headers.authorization || req.headers.cookie)
@@ -209,6 +214,8 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
}
if (canonicalJson(query) !== canonicalJson(permit.query))
throw forbidden("Inspection parameters do not match permit");
if (req.path === INSPECTION_READ_PATH && inspectionReadPath(query) !== INSPECTION_READ_PATH)
throw forbidden("This inspection query needs the extended read path");
// Replay fencing and all inspection state live in Cloud. No tenant receipt.
const consumed = await fetch(`${origin}/v1/customer-success/permits/consume`, {
method: "POST",
@@ -223,7 +230,9 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
if (body === null)
throw unprocessable("Inspection response is too large; use pagination or a byte range");
res.type("application/json").send(body);
});
};
router.post("/read", read);
router.post("/read-v2", read);
// Cloud run liveness check for inspection authority. Cloud asks with its
// own signed, stack-addressed, 60-second question; no agent credential,
// identity key, actor, session or activity is involved.
@@ -1,7 +1,7 @@
import fs from "node:fs/promises";
import { constants } from "node:fs";
import { and, eq, getTableColumns, type SQL } from "drizzle-orm";
import type { AnyPgTable, AnyPgColumn } from "drizzle-orm/pg-core";
import { and, asc, count, desc, eq, getTableColumns, type SQL } from "drizzle-orm";
import { getTableConfig, type AnyPgTable, type AnyPgColumn } from "drizzle-orm/pg-core";
import * as schema from "@paperclipai/db";
import type { Db } from "@paperclipai/db";
import {
@@ -31,6 +31,42 @@ export interface CustomerSuccessInspectionOptions {
pluginWorkerManager?: PluginWorkerManager;
}
/**
* The `summary` view of a run: status, timestamps, ids and error codes, never
* the large JSON columns (result, usage, context snapshot, runner profile...),
* which make a full run row 170-540 KB. An allowlist, so a new column stays out
* until someone adds it here.
*/
export const RUN_SUMMARY_COLUMNS = [
"id",
"companyId",
"agentId",
"issueId",
"scopeKind",
"invocationSource",
"triggerDetail",
"status",
"errorCode",
"exitCode",
"runtimeMode",
"driverKind",
"retryOfRunId",
"processLossRetryCount",
"scheduledRetryAttempt",
"continuationAttempt",
"livenessState",
"startedAt",
"finishedAt",
"createdAt",
"updatedAt",
] as const;
function durationMs(row: Record<string, unknown>): number | null {
const started = row.startedAt instanceof Date ? row.startedAt.getTime() : null;
const finished = row.finishedAt instanceof Date ? row.finishedAt.getTime() : null;
return started !== null && finished !== null ? Math.max(0, finished - started) : null;
}
// This is a reviewed catalog of readers, not a proxy for existing GET routes.
// Select credentials out of queries; never load encrypted identity records.
interface Reader {
@@ -109,6 +145,13 @@ export const inspectionReaders: Record<InspectionResource, Reader> = {
threads: { table: schema.chatConversations, parent: "endpointId" },
};
/** The table's primary key columns: a stable tie-breaker for ordered pages. */
export function primaryKeyColumns(table: AnyPgTable): AnyPgColumn[] {
const config = getTableConfig(table);
const single = config.columns.filter((column) => column.primary);
return single.length ? single : (config.primaryKeys[0]?.columns ?? []);
}
async function ownRow(tx: Db, table: AnyPgTable, companyId: string, id: string) {
const columns = getTableColumns(table) as Record<string, AnyPgColumn>;
const [row] = await tx
@@ -157,7 +200,7 @@ export async function readCustomerSuccessResource(
.where(eq(schema.companies.id, q.companyId));
if (!company) throw notFound("Inspection company not found");
}
if (q.operation === "list" || q.operation === "get") {
if (q.operation === "list" || q.operation === "get" || q.operation === "count") {
const reader = inspectionReaders[q.resource!];
const all = getTableColumns(reader.table) as Record<string, AnyPgColumn>;
const columns = Object.fromEntries(
@@ -180,6 +223,7 @@ export async function readCustomerSuccessResource(
const { inArray } = await import("drizzle-orm");
if (!memberships.length) {
if (q.operation === "get") throw notFound("Inspection resource not found");
if (q.operation === "count") return { total: 0, byStatus: all.status ? {} : null };
return { items: [], nextOffset: null };
}
predicates.push(
@@ -200,13 +244,51 @@ export async function readCustomerSuccessResource(
throw unprocessable("This reader does not accept parentId");
predicates.push(eq(all[reader.parent], q.parentId));
}
if (q.operation === "count") {
// Totals only: no row content leaves the database.
if (!all.status) {
const [{ total }] = await tx
.select({ total: count() })
.from(reader.table)
.where(and(...predicates));
return { total: Number(total), byStatus: null };
}
const groups = await tx
.select({ status: all.status, total: count() })
.from(reader.table)
.where(and(...predicates))
.groupBy(all.status);
const byStatus: Record<string, number> = {};
let total = 0;
for (const group of groups) {
byStatus[String(group.status)] = Number(group.total);
total += Number(group.total);
}
return { total, byStatus };
}
const limit = q.operation === "get" ? 1 : Math.max(1, q.limit ?? 25);
const order = all[reader.id ?? "id"] ?? all.createdAt ?? all.companyId;
const idColumn = all[reader.id ?? "id"];
let orderBy: SQL[] | AnyPgColumn[];
if (q.order) {
if (!all.createdAt) throw unprocessable("This resource has no creation time to order by");
const direction = q.order === "newest" ? desc : asc;
// Rows written together share createdAt; the full primary key keeps
// offset pages from repeating or skipping them.
orderBy = [all.createdAt, ...primaryKeyColumns(reader.table)].map((column) => direction(column));
} else {
orderBy = [idColumn ?? all.createdAt ?? all.companyId];
}
const selected =
q.view === "summary"
? Object.fromEntries(
RUN_SUMMARY_COLUMNS.filter((key) => columns[key]).map((key) => [key, columns[key]]),
)
: columns;
let rows = await tx
.select(columns)
.select(selected)
.from(reader.table)
.where(and(...predicates))
.orderBy(order)
.orderBy(...orderBy)
.limit(limit + (q.operation === "get" ? 0 : 1))
.offset(q.offset ?? 0);
if (q.resource === "agents")
@@ -245,6 +327,7 @@ export async function readCustomerSuccessResource(
q.companyId!,
rows as Array<{ id: string }>,
);
if (q.view === "summary") rows = rows.map((r) => ({ ...r, durationMs: durationMs(r) }));
// Match the existing structured event/config redaction, without scanning
// prose, documents, instructions, skill contents, or workspace files.
if (
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
import { NATIVE_PLAN_REVIEW_DIRECTIVE, buildPaperclipTaskMarkdown } from "./task-markdown.js";
const issue = {
id: "task-1",
@@ -66,6 +66,15 @@ describe("heartbeat task markdown rendering", () => {
expect(markdown).toContain("Do not invent material user intent or success criteria");
});
it("tells a native Plan-mode run that Paperclip opens the one plan review card", () => {
const planning = { issue: { ...issue, workMode: "planning" } };
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true })).toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
// Adapters keep their own approval flow, and an accepted plan is executed.
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: false })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true, acceptedPlanContinuation: true,
taskPlan: { documentId: "plan", revisionId: "revision", revisionNumber: 1, body: "Do it." } })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
});
it("preserves execution of a clear accepted plan without imposing clarification", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, workMode: "planning" },
@@ -7,6 +7,9 @@ import { TASK_QUESTION_GUIDANCE } from "../issue-question-context.js";
import { routineSuggestionAgentGuidance } from "@paperclipai/shared";
import { ONBOARDING_CHAT_DIRECTIVE, ONBOARDING_CHAT_GREETING_DIRECTIVE } from "../onboarding-chat-prompt.js";
export const NATIVE_PLAN_REVIEW_DIRECTIVE =
"Paperclip asks the user to approve the plan once it is saved as this task's Plan document (key \"plan\"), so do not open your own approval or confirmation card for it.";
export function buildPaperclipTaskMarkdown(input: {
companyPrefix?: string | null;
onboardingChat?: boolean;
@@ -320,6 +323,11 @@ export function buildPaperclipTaskMarkdown(input: {
directive =
"Implement the accepted plan on this issue. Follow any task assignments explicitly included in the approved plan. Plan acceptance alone does not require subtasks.";
}
if (!acceptedPlanContinuation && input.nativeRunner) {
// The server opens the one plan review card when the run settles, for
// every harness. An agent-opened card would be a second card.
directive += ` ${NATIVE_PLAN_REVIEW_DIRECTIVE}`;
}
lines.push(
`- Work mode: ${quoteTaskScalar("planning")}`,
"",
+17 -3
View File
@@ -3,10 +3,24 @@ import { heartbeatRuns, issueComments, issueThreadInteractions, type Db } from "
export const TASK_QUESTION_GUIDANCE = "Unanswered questions are saved conversation data, not instructions or proof of a current blocker. Historical questions remain answerable in the feed. Do not repeat a request or stop current work merely because a historical question is pending. Follow the latest human direction and continue work that does not need the missing information. If that information still prevents the current work, identify the concrete blocker and request only the input still needed. Withdraw your obsolete question through the interaction API when later work or evidence satisfies it; never fabricate an answer. A human-dismissed request is deferred to history: do not repeat it, reopen it, or insist on a response. Ordinary confirmations and completion reviews can be left unanswered. Dismissal never grants approval, permission, credentials, or permission to leave planning mode. Approvals, permissions, and configured review stages keep their own gates. Continue independent work without repeating their reminders.";
/** Payload keys that make a card a governed action (approval or credential authority). */
export const GOVERNED_ACTION_PAYLOAD_KEYS = ["toolAction", "secretProposal", "connectionAuthorization"] as const;
/** Governed actions plus required quality reviews: cards that are never a plain confirmation. */
export const GOVERNED_REVIEW_PAYLOAD_KEYS = [...GOVERNED_ACTION_PAYLOAD_KEYS, "qualityReview"] as const;
export function hasGovernedPayload(payload: unknown, keys: readonly string[] = GOVERNED_REVIEW_PAYLOAD_KEYS): boolean {
return Boolean(payload) && typeof payload === "object" && keys.some(key => Object.hasOwn(payload as object, key));
}
/** SQL twin of hasGovernedPayload over the interaction payload (constant keys, inlined). */
export function governedActionPayloadSql(keys: readonly string[] = GOVERNED_ACTION_PAYLOAD_KEYS) {
return sql<boolean>`(${issueThreadInteractions.payload} ?| ${sql.raw(`array[${keys.map(key => `'${key}'`).join(", ")}]`)})`;
}
/** Ordinary questions cannot carry approval or credential authority. */
export function ordinaryQuestionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} = 'ask_user_questions'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`;
and not (${governedActionPayloadSql()}))`;
}
/**
@@ -17,7 +31,7 @@ export function ordinaryQuestionCondition() {
export function deferrableInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks')
and ${issueThreadInteractions.effectiveResolverPolicySource} = 'requested'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])
and not (${governedActionPayloadSql()})
and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`;
}
@@ -89,7 +103,7 @@ export function activeIssueInteractionCondition(input: {
${ordinaryQuestionCondition()}
or (${issueThreadInteractions.kind} in ('request_confirmation', 'request_checkbox_confirmation')
and ${issueThreadInteractions.effectiveResolverPolicy} = 'anyone'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))
and not (${governedActionPayloadSql()}))
)
)` : undefined,
)!;
@@ -14,7 +14,7 @@ import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
import { projectGitHubInteractionErrors } from "./tool-access/github-action-error-projection.js";
import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text";
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { historicalQuestionCondition } from "./issue-question-context.js";
import { hasGovernedPayload, historicalQuestionCondition } from "./issue-question-context.js";
import {
currentContinuationOrigins,
deliveredContinuationCommentIds,
@@ -228,6 +228,8 @@ type CreateInteractionOptions = {
supersedePendingSiblingInteractions?: boolean;
replayAcceptedInteractionIds?: readonly string[];
requireAcceptedReplay?: boolean;
/** Runs once, in the insert transaction, only when this call created the card (never on an idempotent replay). */
afterInsertInTransaction?: (tx: Db, row: IssueThreadInteractionRow) => Promise<void>;
};
type InteractionWakeup = (
@@ -693,7 +695,7 @@ async function isEquivalentAcceptedReplay(
if (
!replayAcceptedInteractionIds.includes(row.id)
|| !isRequestConfirmationLikeKind(row.kind)
|| ["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"].some(key => Object.hasOwn(row.payload, key))
|| hasGovernedPayload(row.payload)
|| row.status !== "accepted"
|| row.result?.outcome !== "accepted"
|| !row.resolvedAt
@@ -5324,6 +5326,7 @@ export function issueThreadInteractionService(
})
.returning();
await options.afterInsertInTransaction?.(tx as unknown as Db, row);
if (row.addresseeAgentId || row.addresseeUserId) {
const [privacyIssue] = await tx.select().from(issues).where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)));
await ensureAssignmentIssueAccessGrant(tx, { ...privacyIssue!,
@@ -0,0 +1,252 @@
import { and, eq, inArray } from "drizzle-orm";
import { documentRevisions, documents, issueThreadInteractions, issues, type Db } from "@paperclipai/db";
import { logActivity, publishActivity } from "../activity-log.js";
import { documentService } from "../documents.js";
import { HttpError } from "../../errors.js";
import { logger } from "../../middleware/logger.js";
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
import { activeIssueInteractionCondition, hasGovernedPayload } from "../issue-question-context.js";
import { isConversation } from "../../lib/conversation-wake-policy.js";
/**
* The Plan-mode review card for the current plan revision.
*
* Codex and Claude report their plan as a provider event, and the session
* opens the Approve / Request changes card for it. Harnesses without such an
* event (Antigravity and other ACPX agents) write the Plan document with a
* tool and must open the card themselves. A run that forgets, or a recovered
* run that resumes after the original process died, would otherwise leave a
* Plan-mode task waiting on a review nobody can give. When a Plan-mode run
* settles, the server opens the card for the current revision unless one
* already covers it.
*/
export type NativePlanReviewCardOutcome =
/** The server opened the card for this revision. */
| { kind: "created"; interactionId: string; revisionId: string }
/** A pending card (or question) already gives the user the next action. */
| { kind: "pending"; interactionId: string }
/** The current revision was already answered; the agent owes a new revision. */
| { kind: "reviewed"; revisionId: string }
/** Plan mode produced no plan to review. */
| { kind: "no_plan" }
/** Not a Plan-mode task this agent owns, or the revision is not the agent's. */
| { kind: "not_applicable" };
type Binding = { companyId: string; issueId: string; runId: string; agentId: string };
const record = (value: unknown): Record<string, unknown> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
export function planReviewCardIdempotencyKey(revisionId: string): string {
return `plan-review:v1:${revisionId}`;
}
/**
* The one Plan-review card shape, for the card Paperclip opens from a
* provider's plan event (Codex, Claude) and the one it opens on settle.
*/
export function planReviewConfirmationInput(input: {
issueId: string;
documentId: string;
revisionId: string;
revisionNumber: number;
sourceRunId: string;
idempotencyKey: string;
source: "provider_plan" | "plan_document";
}) {
return {
kind: "request_confirmation" as const,
idempotencyKey: input.idempotencyKey,
sourceRunId: input.sourceRunId,
title: `Review plan revision ${input.revisionNumber}`,
summary: input.source === "provider_plan"
? "Review the synchronized Paperclip plan."
: "Review the plan before the agent starts the work.",
continuationPolicy: "wake_assignee" as const,
payload: {
version: 1 as const,
prompt: `Approve plan revision ${input.revisionNumber}?`,
...(input.source === "provider_plan"
? { detailsMarkdown: "The completed provider plan has been synchronized to the canonical Plan document." }
: {}),
acceptLabel: "Approve plan",
rejectLabel: "Request changes",
rejectRequiresReason: true,
supersedeOnUserComment: false,
target: {
type: "issue_document" as const,
issueId: input.issueId,
documentId: input.documentId,
key: "plan",
revisionId: input.revisionId,
revisionNumber: input.revisionNumber,
label: `Plan v${input.revisionNumber}`,
},
},
};
}
async function coveringCard(db: Db, binding: Binding, revision: { id: string }, conversationMode: boolean) {
// A historical or deferred card cannot give the user the next action; the
// same rule decides the run's governance gate.
const active = new Set((await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, binding.companyId),
eq(issueThreadInteractions.issueId, binding.issueId),
eq(issueThreadInteractions.status, "pending"),
activeIssueInteractionCondition({ runId: binding.runId, conversationMode }),
))).map(row => row.id));
const cards = await db.select({
id: issueThreadInteractions.id,
kind: issueThreadInteractions.kind,
status: issueThreadInteractions.status,
payload: issueThreadInteractions.payload,
createdAt: issueThreadInteractions.createdAt,
resolvedByUserId: issueThreadInteractions.resolvedByUserId,
resolvedByAgentId: issueThreadInteractions.resolvedByAgentId,
result: issueThreadInteractions.result,
}).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, binding.companyId),
eq(issueThreadInteractions.issueId, binding.issueId),
inArray(issueThreadInteractions.kind, ["request_confirmation", "ask_user_questions"]),
));
const targetRevision = (payload: unknown) => {
const target = record(record(payload).target);
return target.type === "issue_document" && typeof target.revisionId === "string" ? target.revisionId : null;
};
// Only an explicit plan review covers a revision: a card bound to this
// revision (the server's, Codex/Claude's, or an agent's card opened with the
// plan target). An unbound confirmation is an ordinary request: it never
// covers a plan, never starts execution and is never withdrawn here. A
// pending question also gives the user the next action. A card bound to an
// older revision does not cover this one.
const covers = (card: (typeof cards)[number]) => {
if (card.kind === "ask_user_questions") return card.status === "pending";
if (hasGovernedPayload(card.payload)) return false;
return targetRevision(card.payload) === revision.id;
};
// A pending card bound to this revision always gates it, also when the
// conversation prior-turn rule would leave it out of the active set.
const pending = cards.find(card => card.status === "pending" && covers(card) &&
(active.has(card.id) || targetRevision(card.payload) === revision.id));
if (pending) return { kind: "pending" as const, interactionId: pending.id };
// How each terminal state of a card bound to this revision counts:
// - accepted or rejected: the user decided this revision;
// - cancelled by the user (withdrawn from the thread): the user declined to
// review this revision. Do not reopen it; the agent is asked to revise.
// - cancelled by an agent or the system, expired (superseded, stale, task
// closed) or failed: no one reviewed it. The revision gets a fresh card.
// A card withdrawn as a stale target was for an older revision, even though
// the withdrawal records the current revision on it.
const bound = cards.filter(card => card.kind === "request_confirmation" && covers(card) &&
record(card.result).outcome !== "stale_target");
const decided = bound.find(card => ["accepted", "rejected"].includes(card.status) ||
(card.status === "cancelled" && card.resolvedByUserId && !card.resolvedByAgentId));
if (decided) return { kind: "reviewed" as const, revisionId: revision.id };
const unreviewed = bound.filter(card => card.status !== "pending")
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];
return unreviewed ? { kind: "reopen" as const, afterInteractionId: unreviewed.id } : null;
}
export async function ensureNativePlanReviewCard(db: Db, binding: Binding): Promise<NativePlanReviewCardOutcome> {
const publications: Parameters<typeof publishActivity>[0][] = [];
// One decision per task at a time: reading the current revision and its
// cards, withdrawing older cards, choosing the key and inserting all happen
// under the task row lock, so two settles can never both open a card for
// one plan. Card creation takes the same lock first, so the order matches.
const outcome = await db.transaction(async (transaction) => {
const tx = transaction as unknown as Db;
const [issue] = await tx.select({
workMode: issues.workMode, status: issues.status, assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId, hiddenAt: issues.hiddenAt,
conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId,
}).from(issues).where(and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId))).limit(1).for("update");
if (!issue || issue.workMode !== "planning" || issue.hiddenAt || issue.assigneeUserId ||
issue.assigneeAgentId !== binding.agentId || ["done", "cancelled"].includes(issue.status)) {
return { kind: "not_applicable" } as const;
}
const plan = await documentService(tx).getIssueDocumentByKey(binding.issueId, "plan");
if (!plan?.latestRevisionId) return { kind: "no_plan" } as const;
const [revision] = await tx.select({
id: documentRevisions.id, revisionNumber: documentRevisions.revisionNumber,
createdByAgentId: documentRevisions.createdByAgentId,
}).from(documentRevisions).where(and(
eq(documentRevisions.id, plan.latestRevisionId), eq(documentRevisions.companyId, binding.companyId),
)).limit(1);
if (!revision) return { kind: "no_plan" } as const;
// A delayed settle that read an older revision must not act on it.
const [current] = await tx.select({ latestRevisionId: documents.latestRevisionId, latestRevisionNumber: documents.latestRevisionNumber })
.from(documents).where(and(eq(documents.id, plan.id), eq(documents.companyId, binding.companyId))).for("update");
if (current?.latestRevisionId !== revision.id) return { kind: "not_applicable" } as const;
const conversationMode = isConversation(issue);
const existing = await coveringCard(tx, binding, revision, conversationMode);
if (existing && existing.kind !== "reopen") return existing;
// Only the assigned agent's own proposal is put up for review. A revision
// a person wrote is theirs already.
if (revision.createdByAgentId !== binding.agentId) return { kind: "not_applicable" } as const;
// A card for this revision that no one reviewed keeps its key; the fresh
// card's key names the one it follows.
const idempotencyKey = existing?.kind === "reopen"
? `${planReviewCardIdempotencyKey(revision.id)}:after:${existing.afterInteractionId}`
: planReviewCardIdempotencyKey(revision.id);
// Withdraw cards bound to an older revision. Answering one is already
// refused as a stale target, so this only tidies the thread: a row it
// cannot read must not stop the current card from opening.
await tx.transaction(async (savepoint) => {
await issueThreadInteractionService(savepoint as unknown as Db).expireStaleRequestConfirmationsForIssueDocument(
{ id: binding.issueId, companyId: binding.companyId },
{ id: plan.id, key: "plan", latestRevisionId: current.latestRevisionId, latestRevisionNumber: current.latestRevisionNumber },
{ agentId: binding.agentId, runId: binding.runId });
}).catch((error: unknown) => logger.warn({ issueId: binding.issueId, error }, "Could not withdraw stale plan review cards"));
let inserted = false;
try {
const interaction = await issueThreadInteractionService(tx).create(
{ id: binding.issueId, companyId: binding.companyId },
planReviewConfirmationInput({
issueId: binding.issueId, documentId: plan.id, revisionId: revision.id, revisionNumber: revision.revisionNumber,
sourceRunId: binding.runId, source: "plan_document", idempotencyKey,
}) as never,
{ agentId: binding.agentId, runId: binding.runId },
{
// Leave the agent's other pending cards answerable. Only cards bound
// to an older plan revision were withdrawn above; an unbound card is
// never withdrawn by guess.
supersedePendingSiblingInteractions: false,
// Only the call that inserted the card records it.
afterInsertInTransaction: async (insertTx, row) => {
inserted = true;
await logActivity(insertTx, {
companyId: binding.companyId,
actorType: "system",
actorId: "native-plan-review",
agentId: binding.agentId,
runId: binding.runId,
issueId: binding.issueId,
action: "issue.thread_interaction_created",
entityType: "issue",
entityId: binding.issueId,
details: {
interactionId: row.id,
interactionKind: "request_confirmation",
source: "plan_mode_settle",
planRevisionId: revision.id,
planRevisionNumber: revision.revisionNumber,
},
}, publications);
},
},
);
return inserted
? { kind: "created", interactionId: interaction.id, revisionId: revision.id } as const
: { kind: "pending", interactionId: interaction.id } as const;
} catch (error) {
// The task closed or the agent may no longer write here. A refused card
// must not fail the run's settlement; database errors still surface so
// finalization (or the recovery pass) retries.
if (!(error instanceof HttpError) || error.status >= 500) throw error;
const covered = await coveringCard(tx, binding, revision, conversationMode);
return covered && covered.kind !== "reopen" ? covered : { kind: "not_applicable" } as const;
}
});
for (const publication of publications) publishActivity(publication);
return outcome;
}
@@ -114,6 +114,7 @@ import {
} from "../heartbeat-run-summary.js";
import { resolveChatRunPresentationAuthorizationReason } from "../chat-run-publications.js";
import { settledResponsePublicationSql } from "./native-response-publication-receipt.js";
import { ensureNativePlanReviewCard } from "./native-plan-review-card.js";
import { hasChatRunOwnedProviderInteraction } from "../chat-interaction-arbitration.js";
import {
authorizeCommittedChatResponse,
@@ -1677,6 +1678,23 @@ export async function finalizeNativeRun(input: {
? await findSupersededExternalReviewRequests(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
}) : [];
// A Plan-mode run that settles with a plan revision nobody was asked to
// review gets its review card here, whichever harness ran it and whether
// or not the agent remembered to open it. The card is the review gate below.
const planReview = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" &&
authoritativeIssue.workMode === "planning" && result.reportedWorkDisposition !== "done" &&
!isNativePlanWaitResult(result) &&
!readNativeReviewAssignmentContext(run.contextSnapshot)
? await ensureNativePlanReviewCard(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
}).catch((error: unknown) => {
// The run already succeeded; a card that could not be opened must
// not fail its settlement. The task settles in its response wait and
// the stranded-task pass opens the card (idempotently) later.
logger.warn({ runId: run.id, issueId: authoritativeIssue.id, error }, "Plan review card could not be opened at settle; recovery will retry");
return null;
})
: null;
const governanceGate = await pendingNativeGovernance({
db: input.db,
companyId: run.companyId,
@@ -1778,6 +1796,7 @@ export async function finalizeNativeRun(input: {
monitorWaitSuperseded: supersededMonitorWait !== null,
monitorWaitAuthorized: authoritativeIssue.workMode === "standard" && authoritativeIssue.executionRunId === run.id && monitorWaitAt !== null,
planWaitAuthorized: planWait !== null,
planNotProduced: planReview?.kind === "no_plan" || planReview?.kind === "reviewed",
hasPendingChildCompletion,
providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision,
providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision,
@@ -15147,10 +15147,12 @@ describe("native warm session supervision", () => {
async ({ name, firstEnvironment = {}, secondEnvironment = {}, refreshTools, unsupportedRefresh = false,
managedGitHub = false, reuse, adoptionReuse = reuse }) => {
const decisions: Record<string, boolean> = {};
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : [])] as const) {
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : []),
...(refreshTools && !unsupportedRefresh ? ["released-unavailable"] as const : [])] as const) {
const portable = path === "portable" || path === "portable-bootstrap";
const bootstrap = path === "portable-bootstrap";
const pluginRecovery = portable || path === "legacy-plugin";
const releasedUnavailable = path === "released-unavailable";
const pluginRecovery = portable || path === "legacy-plugin" || releasedUnavailable;
githubAccess.create.mockReset().mockImplementation(async () => ({ env: {}, ready: true, duplexRequested: false,
activate: githubAccess.activate.mockReset().mockImplementation(() => vi.fn()), stop: githubAccess.stop.mockReset().mockResolvedValue(undefined) }));
const stateBase = await mkdtemp(join(tmpdir(), "paperclip-runnerd-reuse-key-"));
@@ -15228,7 +15230,7 @@ describe("native warm session supervision", () => {
const projection = vi.spyOn(controllerRecovery, "resolveNativeControllerRecovery").mockResolvedValue({ kind: "no_prior_execution" });
const restore = path === "legacy-plugin" ? vi.spyOn(runnerCheckpoint, "restoreNativeRunnerCheckpoint")
.mockImplementation(async (_db, binding) => binding.runId === first.binding.runId && recoveredSession.close.mock.calls.length ? {} as never : null) : undefined;
const issueProjection = path === "legacy-plugin" ? vi.spyOn(issueServiceModule, "issueService")
const issueProjection = path === "legacy-plugin" || releasedUnavailable ? vi.spyOn(issueServiceModule, "issueService")
.mockReturnValue({ update: vi.fn(async () => null) } as never) : undefined;
try {
await executePaperclipNativeSession({ db: leaseDb(first), execution: first, runnerInstanceId: "runner-reuse-key",
@@ -15261,14 +15263,26 @@ describe("native warm session supervision", () => {
});
}
if (pluginRecovery) state.createBackend.mockReturnValueOnce({
kind: "test", recoverSession: async () => ({ recovered: true, session: recoveredSession }),
kind: "test", recoverSession: async () => {
if (releasedUnavailable) throw new Error("native_runner_reuse_unavailable");
return { recovered: true, session: recoveredSession };
},
} as never);
const createOwner = pluginTaskRuntime.createPluginRunnerTaskOwner;
const owners = releasedUnavailable ? vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner")
.mockImplementation(ownerInput => Object.assign(createOwner(ownerInput), { retiredBeforeClaim: () => true })) : undefined;
const resumeFrom = releasedUnavailable ? vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue("target-task") : undefined;
const pluginTaskDescription = { kind: "description", taskId: "target-task", warmTaskVersion: 1,
launchPreparationVersion: 1, projectAuthCheckVersion: 1, releaseResumeVersion: 1,
...(releasedUnavailable ? { executionContextVersion: 1 as const } : {}),
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } } as const;
const portableTarget = { ...target, runner: undefined, leaseId: "target-lease",
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" ? "resumed" : "created", providerLeaseId: "target-task" },
runnerTask: vi.fn(async (operation: { kind: string }) => {
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" || releasedUnavailable ? "resumed" : "created", providerLeaseId: "target-task" },
runnerTask: vi.fn(async (operation: { kind: string }, options?: { executionContext?: unknown }) => {
if (releasedUnavailable && operation.kind === "describe") {
if (options?.executionContext) throw new Error("fixture replacement bound to the old task context");
return { ...pluginTaskDescription, taskId: "fresh-task" };
}
if (path === "legacy-plugin") {
expect(recoveredSession.close).toHaveBeenCalledOnce();
expect(operation.kind).toBe("describe");
@@ -15313,6 +15327,16 @@ describe("native warm session supervision", () => {
expect(portableTarget.runnerTask).toHaveBeenCalledOnce();
continue;
}
if (releasedUnavailable) {
try {
await continuation;
delete decisions[path];
expect(portableTarget.runnerTask.mock.calls.map(([operation]) => operation.kind)).toContain("describe");
expect(state.execute).toHaveBeenCalledTimes(2);
expect(recoveredSession.close).not.toHaveBeenCalled();
} finally { owners?.mockRestore(); resumeFrom?.mockRestore(); }
continue;
}
if (path === "adoption") await expect(continuation).rejects.toThrow("fixture adoption decision recorded");
else await continuation;
expect(decisions[path]).toBe(portable ? true : path === "adoption" ? adoptionReuse : reuse);
@@ -19613,12 +19637,12 @@ describe("runnerd provider runtime wiring", () => {
});
it.each((["codex", "claude"] as const).flatMap(provider => [
...[[false, false, false, false], [true, false, false, false], [false, true, false, false], [false, false, true, false], ...(provider === "codex" ? [[false, false, false, true]] : [])]
.map(([unknown, shutdown, journalFailure, deadline]) => [provider, unknown, shutdown, journalFailure, deadline, "idle timeout"] as const),
...[[false, false, false], [true, false, false], [false, true, false], ...(provider === "codex" ? [[false, false, true]] : [])]
.map(([unknown, shutdown, deadline]) => [provider, unknown, shutdown, deadline, "idle timeout"] as const),
...(["controller restart", "detach failure", "environment deletion", "replacement hand-off"] as const)
.map(retirement => [provider, false, false, false, false, retirement] as const),
.map(retirement => [provider, false, false, false, retirement] as const),
]))(
"releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, journalFailure=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, journalFailure, deadline, retirement) => {
"releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, deadline, retirement) => {
await closeIdleWarmNativeSessionsForRestart();
expect(readNativeSessionIdleWork()).toBe("none");
const previousHome = process.env.PAPERCLIP_HOME;
@@ -19654,7 +19678,7 @@ describe("runnerd provider runtime wiring", () => {
});
let allowPhysicalStop!: () => void;
const physicalStop = new Promise<void>(resolve => { allowPhysicalStop = resolve; });
const close = vi.fn(async () => { if (shutdown || deadline || journalFailure) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {});
const close = vi.fn(async () => { if (shutdown || deadline) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {});
const session = { release, close, detachControllerForRestart };
const validated = validatePrpStructuredRunResult({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done",
summary: "Completed", completionClaim: { contractRevision: current.completionContract.contract.revision,
@@ -19683,7 +19707,7 @@ describe("runnerd provider runtime wiring", () => {
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
runnerExecutionTarget: { ...target, runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy");
expect(nextTask).not.toHaveBeenCalled();
if (provider === "codex" && !unknown && !shutdown && !journalFailure && !deadline) {
if (provider === "codex" && !unknown && !shutdown && !deadline) {
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
runnerExecutionTarget: { ...target, environmentId: "competing-environment", runnerTask: nextTask,
@@ -19714,33 +19738,6 @@ describe("runnerd provider runtime wiring", () => {
expect(JSON.parse(await readFile(join(directory, (await readdir(directory))[0]!), "utf8")).releasedRunner).toBeUndefined();
return;
}
if (journalFailure) {
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
const path = join(directory, (await readdir(directory))[0]!);
await rename(path, `${path}.saved`);
await mkdir(path);
let finished = false;
void execute.finally(() => { finished = true; }).catch(() => undefined);
allowRelease();
await new Promise(resolve => setImmediate(resolve));
expect(finished).toBe(false);
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, remoteCwd: "different-workspace", runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy");
expect(nextTask).not.toHaveBeenCalled();
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(readNativeSessionIdleWork()).toBe("present");
expect(finished).toBe(false);
await rm(path, { recursive: true });
await rename(`${path}.saved`, path);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
allowPhysicalStop();
await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(readNativeSessionIdleWork()).toBe("none");
expect(detachControllerForRestart).not.toHaveBeenCalled();
return;
}
allowRelease();
await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(readNativeSessionIdleWork()).toBe("none");
@@ -19748,21 +19745,20 @@ describe("runnerd provider runtime wiring", () => {
const files = await readdir(directory);
const path = join(directory, files[0]!);
const envelope = JSON.parse(await readFile(path, "utf8"));
expect(envelope.releasedRunner).toMatchObject({ source, taskId: "retained-task", scopeDigest: expect.any(String) });
expect(envelope.releasedRunner).toBeUndefined();
expect(JSON.stringify(envelope)).not.toContain("synthetic-fixture");
if (!unknown) {
const calls = owners.mock.calls.length;
for (const changed of [{ remoteCwd: "different-workspace" }, { runnerTaskProjectIds: ["different-project"] }]) {
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, ...changed, runnerTask: nextTask },
runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch");
}
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, runnerTask: nextTask,
sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } },
runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch");
expect(owners).toHaveBeenCalledTimes(calls);
expect(nextTask).not.toHaveBeenCalled();
expect(state.execute).toHaveBeenCalledTimes(1);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
}
if (retirement === "environment deletion") {
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: target.environmentId, reason: "environment deleted" }))
@@ -19777,7 +19773,7 @@ describe("runnerd provider runtime wiring", () => {
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, busy: 0, failed: 1 });
expect(close).not.toHaveBeenCalled();
expect(readNativeSessionIdleWork()).toBe("present");
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
}
detachControllerForRestart.mockResolvedValue(undefined);
}
@@ -19788,7 +19784,7 @@ describe("runnerd provider runtime wiring", () => {
expect(readNativeSessionIdleWork()).toBe("none");
expect(close).not.toHaveBeenCalled();
expect(task.mock.calls.map(([operation]) => (operation as { kind: string }).kind)).toEqual(["describe"]);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
if (provider === "codex" && !unknown) {
const inspected = vi.spyOn(remoteWarmRecoveryRuntime, "inspectRemoteWarmSessionRecovery").mockImplementation(async request => {
request.loadCheckpoint(current);
@@ -19805,18 +19801,15 @@ describe("runnerd provider runtime wiring", () => {
{ runnerExecutionTarget: { ...target, runnerTaskProjectIds: ["different-project"] } },
{ runnerExecutionTarget: { ...target, remoteCwd: "different-workspace" } },
{ runnerExecutionTarget: { ...target, sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } } },
]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("released_owner_scope_mismatch");
]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("fixture completed-source proof checked");
await writeFile(path, JSON.stringify({ ...envelope,
releasedRunner: { source, taskId: "retained-task", scopeDigest: `sha256:${"0".repeat(64)}` } }));
await expect(executePaperclipNativeSession(base)).rejects.toThrow("fixture completed-source proof checked");
expect(inspected.mock.calls.at(-1)![0].loadCheckpoint(current)).toMatchObject({ identity: envelope.snapshot.identity });
expect(owners).toHaveBeenCalledTimes(calls);
expect(state.execute).toHaveBeenCalledTimes(1);
} finally { inspected.mockRestore(); }
}
await owners.mock.calls.at(-1)![0].onResumed!(source);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
const replacement = { ...envelope, snapshot: { ...envelope.snapshot, identity: { ...envelope.snapshot.identity, runId: "new-owner" } },
releasedRunner: { ...envelope.releasedRunner, source: { ...source, runId: "new-owner" } } };
await writeFile(path, JSON.stringify(replacement));
await expect(owners.mock.calls.at(-1)![0].onResumed!(source)).rejects.toThrow("released_source_mismatch");
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(replacement.releasedRunner);
} finally {
detachControllerForRestart.mockResolvedValue(undefined);
registerRunStartHandover(null);
@@ -19827,7 +19820,7 @@ describe("runnerd provider runtime wiring", () => {
it.each((["codex", "claude"] as const).flatMap(provider => (["current", "stale", ...(provider === "codex" ? ["foreign runner", "foreign lease"] : [])] as const)
.map(receipt => [provider, receipt] as const)))(
"records the confirmed %s source after external checkpoint registration and attachment (receipt=%s)", async (provider, receipt) => {
"accepts only the attached %s source's release receipt after external checkpoint registration (receipt=%s)", async (provider, receipt) => {
const invalidReceipt = receipt !== "current";
await closeIdleWarmNativeSessionsForRestart();
const previousHome = process.env.PAPERCLIP_HOME;
@@ -19899,7 +19892,6 @@ describe("runnerd provider runtime wiring", () => {
.toBe("paperclip.runner.external-control-plane-state.v1");
} else {
expect(options.existingSession).toBe(session);
await owners.mock.calls[0]![0].onResumed!(source);
authority.rotateRunIdentity(successor);
await register!(authority, successor);
await writeFile(join(root, "runner/runner-state.json"), JSON.stringify(durableRunnerState(successor, "ready")));
@@ -19931,7 +19923,7 @@ describe("runnerd provider runtime wiring", () => {
expect(release).toHaveBeenCalledOnce();
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
const path = join(directory, (await readdir(directory))[0]!);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(source);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
following = run(next);
void following.catch(() => undefined);
if (invalidReceipt) {
@@ -19944,7 +19936,7 @@ describe("runnerd provider runtime wiring", () => {
} else {
await expect(following).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(release).toHaveBeenCalledTimes(2);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(successor);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
expect(close).not.toHaveBeenCalled();
}
} finally {
@@ -337,6 +337,7 @@ import {
type NativeStatusDecision,
} from "./status-arbiter.js";
import { conflict, HttpError } from "../../errors.js";
import { planReviewConfirmationInput } from "./native-plan-review-card.js";
import { redactSensitiveText } from "../../redaction.js";
import { classifyRemoteConnectionError } from "../remote-connection-failure.js";
import { resolvePaperclipRunnerBinary, resolvePaperclipRunnerBinaryAsync, resolveRemotePaperclipRunnerBinary, verifiedBundledRemoteRunnerBinary } from "./native-codex-runner.js";
@@ -2324,33 +2325,15 @@ export async function synchronizeCompletedProviderPlan(input: {
id: input.execution.binding.issueId,
companyId: input.execution.binding.companyId,
},
{
kind: "request_confirmation",
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
planReviewConfirmationInput({
issueId: input.execution.binding.issueId,
documentId: current.id,
revisionId: revision.id,
revisionNumber: revision.revisionNumber,
sourceRunId: input.execution.binding.runId,
title: `Review plan revision ${revision.revisionNumber}`,
summary: "Review the synchronized Paperclip plan.",
continuationPolicy: "wake_assignee",
payload: {
version: 1,
prompt: `Approve plan revision ${revision.revisionNumber}?`,
detailsMarkdown:
"The completed provider plan has been synchronized to the canonical Plan document.",
acceptLabel: "Approve plan",
rejectLabel: "Request changes",
rejectRequiresReason: true,
supersedeOnUserComment: false,
target: {
type: "issue_document",
issueId: input.execution.binding.issueId,
documentId: current.id,
key: "plan",
revisionId: revision.id,
revisionNumber: revision.revisionNumber,
label: `Plan v${revision.revisionNumber}`,
},
},
} as never,
source: "provider_plan",
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
}) as never,
{
agentId: input.execution.binding.agentId,
runId: input.execution.binding.runId,
@@ -8796,49 +8779,23 @@ function legacyNativeSessionCheckpointPath(
);
}
type ReleasedWarmRunner = { source: DurableRecoveryIdentity; taskId: string; scopeDigest: string };
const RELEASED_SOURCE_KEYS = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"] as const;
function releasedWarmScope(input: Parameters<typeof executePaperclipNativeSession>[0]): string {
const target = input.runnerExecutionTarget;
return nativeSha256({ companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId,
environmentId: target?.kind === "remote" ? target.environmentId ?? null : null, workspace: nativeSessionWorkspaceScope(input.execution),
cwd: input.execution.workspace.cwd, remoteCwd: target?.kind === "remote" ? target.remoteCwd : null,
projectIds: target?.kind === "remote" && target.transport === "sandbox" ? target.runnerTaskProjectIds ?? [] : [],
accountIdentity: input.managedAiAccountIdentity ?? null, credentialIdentity: input.managedAiCredentialIdentity ?? null });
function releasedDurableIdentity(identity: Record<string, unknown> | null): DurableRecoveryIdentity | undefined {
if (!identity || RELEASED_SOURCE_KEYS.some(key => typeof identity[key] !== "string" || !identity[key])) return undefined;
const field = (key: typeof RELEASED_SOURCE_KEYS[number]) => identity[key] as string;
return { runnerInstanceId: field("runnerInstanceId"), environmentLeaseId: field("environmentLeaseId"), runId: field("runId"),
normalizedSessionId: field("normalizedSessionId"), turnId: field("turnId"), itemId: field("itemId") };
}
function requireReleasedWarmScope(input: Parameters<typeof executePaperclipNativeSession>[0],
proof: ReleasedWarmRunner | undefined, identity: unknown): DurableRecoveryIdentity {
function releasedWarmSource(input: Parameters<typeof executePaperclipNativeSession>[0], taskId: string | null): DurableRecoveryIdentity {
const target = input.runnerExecutionTarget;
if (!proof || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|| proof.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId
|| proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)) {
const source = releasedDurableIdentity(readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution)));
if (!source || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|| taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
throw new Error("native_session_released_owner_scope_mismatch");
}
return proof.source;
}
function readWarmNativeEnvelope(execution: NativeExecutionInput): Record<string, unknown> | null {
const path = nativeSessionCheckpointPath(execution);
if (!existsSync(path)) return null;
const envelope = record(JSON.parse(readBoundedNativeFile(path, NATIVE_WARM_CHECKPOINT_MAX_BYTES,
"native_session_supervisor_checkpoint_too_large").toString("utf8")));
if (envelope.schema !== "paperclip.native-session-supervisor.v1") throw new Error("native_session_supervisor_checkpoint_mismatch");
return envelope;
}
function releasedWarmRunner(envelope: Record<string, unknown> | null): ReleasedWarmRunner | undefined {
if (!envelope || envelope.releasedRunner === undefined) return undefined;
const proof = record(envelope.releasedRunner), source = record(proof.source);
const snapshot = record(envelope.snapshot), identity = record(snapshot.identity);
for (const key of ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"]) {
if (typeof source[key] !== "string" || !source[key]) throw new Error("native_session_released_source_mismatch");
}
if (typeof proof.taskId !== "string" || !proof.taskId || typeof proof.scopeDigest !== "string"
|| identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId) {
throw new Error("native_session_released_source_mismatch");
}
return proof as ReleasedWarmRunner;
return source;
}
function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Record<string, unknown>): void {
@@ -8849,38 +8806,15 @@ function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Reco
chmodSync(path, 0o600);
}
function updateReleasedWarmRunner(execution: NativeExecutionInput, source: DurableRecoveryIdentity,
taskId: string, proof: ReleasedWarmRunner | null): void {
const envelope = readWarmNativeEnvelope(execution);
const previous = releasedWarmRunner(envelope);
if (!envelope) {
if (proof) throw new Error("native_session_supervisor_checkpoint_missing");
return;
}
if (!proof && !previous) return;
const identity = record(record(envelope.snapshot).identity);
if (identity.companyId !== execution.binding.companyId || identity.agentId !== execution.binding.agentId
|| identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId
|| (previous && (previous.taskId !== taskId || canonicalJson(previous.source) !== canonicalJson(source)))) {
throw new Error("native_session_released_source_mismatch");
}
if (proof) envelope.releasedRunner = proof;
else delete envelope.releasedRunner;
writeWarmNativeEnvelope(execution, envelope);
}
function persistWarmNativeCheckpoint(
execution: NativeExecutionInput,
configDigest: string,
snapshot: PersistedNativeSession,
processConfigDigest?: string,
): void {
const previous = releasedWarmRunner(readWarmNativeEnvelope(execution));
writeWarmNativeEnvelope(execution, {
schema: "paperclip.native-session-supervisor.v1", configDigest, processConfigDigest,
updatedAt: new Date().toISOString(), snapshot,
...(previous && previous.source.runId === snapshot.identity.runId
&& previous.source.normalizedSessionId === snapshot.identity.sessionId ? { releasedRunner: previous } : {}),
});
}
@@ -11252,10 +11186,11 @@ async function executePaperclipNativeSessionAttempt(
}
const cachedReleasedOwner = warmNativeSessions.get(nativeSessionScopeKey(input.execution));
if (cachedReleasedOwner?.released) {
const proof = portableSource ? undefined : releasedWarmRunner(readWarmNativeEnvelope(input.execution));
const identity = readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution));
const durable = portableSource ? undefined : releasedDurableIdentity(identity);
const target = input.runnerExecutionTarget;
const source = portableSource ?? (proof && { taskId: proof.taskId, identity: proof.source });
const source = portableSource ?? (durable && cachedReleasedOwner.pluginTaskId
? { taskId: cachedReleasedOwner.pluginTaskId, identity: durable } : undefined);
if (source && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId
&& (portableSource || target.sandboxLeaseAcquisition?.outcome === "created")
&& source.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
@@ -11265,8 +11200,7 @@ async function executePaperclipNativeSessionAttempt(
|| cachedReleasedOwner.preparingRunId && cachedReleasedOwner.preparingRunId !== input.execution.binding.runId
|| cachedReleasedOwner.instructionPreparationRunId && !ownInstructionPreparation
|| cachedReleasedOwner.closeOnReleaseReason) throw new Error("native_session_supervisor_busy");
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId ||
(proof && (proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)))) {
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId) {
throw new Error("native_session_released_owner_scope_mismatch");
}
const wasBusy = cachedReleasedOwner.busy;
@@ -11284,7 +11218,7 @@ async function executePaperclipNativeSessionAttempt(
}
forgetWarmNativeSession(nativeSessionScopeKey(input.execution), cachedReleasedOwner);
} finally { cachedReleasedOwner.busy = wasBusy; }
} else requireReleasedWarmScope(input, proof, identity);
} else releasedWarmSource(input, cachedReleasedOwner.pluginTaskId ?? null);
}
if (input.useRunnerd && canRecoverWarmOwner && !input.backend &&
input.runnerExecutionTarget?.kind === "remote" &&
@@ -11320,7 +11254,6 @@ async function executePaperclipNativeSessionAttempt(
}
if (durableIdentityMatchesSession(identity, input.execution) && identity.runId !== input.execution.binding.runId &&
runnerdAuthorityLifecycleWithVerifiedBackup({ root, identity, execution: input.execution, allowVerifiedBackup: true }) !== "suspended") {
let releasedSource = portableSource?.identity;
remoteWarmRecovery = await inspectRemoteWarmSessionRecovery({
db: input.db, execution: input.execution, target: input.runnerExecutionTarget, identity,
portableSourceTaskId: portableSource?.taskId,
@@ -11328,19 +11261,15 @@ async function executePaperclipNativeSessionAttempt(
resolve(root, "control-plane", "control-plane-state.json"), NATIVE_CONTROL_PLANE_STATE_MAX_BYTES,
"runner_durable_identity_too_large").toString("utf8"))),
matchesExecution: previous => matchesRemoteWarmExecution(previous, input.execution, input.toolRefreshOnResume),
loadCheckpoint: previous => {
if (!portableSource) {
const proof = releasedWarmRunner(readWarmNativeEnvelope(previous));
if (proof) releasedSource = requireReleasedWarmScope(input, proof, identity);
}
return loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote");
},
loadCheckpoint: previous => loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote"),
canReuseProcess: previous => !portableSource && !needsCoreGitHubAccess(input) &&
nativeSessionConfigDigest(previous, "remote") === nativeSessionConfigDigest(input.execution, "remote") && canReuseNativeProcess(input,
record(JSON.parse(readBoundedNativeFile(nativeSessionCheckpointPath(previous),
NATIVE_WARM_CHECKPOINT_MAX_BYTES, "native_session_supervisor_checkpoint_too_large").toString("utf8"))).processConfigDigest),
}) ?? undefined;
if (remoteWarmRecovery) {
const releasedSource = portableSource?.identity
?? (pluginTaskDescription?.releaseResumeVersion === 1 ? releasedDurableIdentity(identity) : undefined);
remoteWarmRecovery.releasedSource = releasedSource;
if (releasedSource) {
const header = await loadNativeRunnerCheckpointHeader(input.db, remoteWarmRecovery.previousExecution.binding).catch((error: unknown) => {
@@ -12318,6 +12247,7 @@ async function executePaperclipNativeSessionAttempt(
let reusingReleasedRunner = false;
let relaunchReleased: { owner?: ReturnType<typeof createPluginRunnerTaskOwner>; source: DurableRecoveryIdentity;
runner: { version: string; digest: string }; published?: true } | undefined;
let releasedRecoveryOwner: ReturnType<typeof createPluginRunnerTaskOwner> | undefined;
let managedCredentialSession: NativeSession | undefined;
let githubAccess: NativeGitHubAccess | undefined;
let releaseGitHubRun: (() => void) | undefined;
@@ -12340,8 +12270,7 @@ async function executePaperclipNativeSessionAttempt(
const registered = warmNativeSessions.get(warmSessionId);
const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget)
? undefined : registered;
const releasedSource = entry?.released ? requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)),
readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))) : undefined;
const releasedSource = entry?.released ? releasedWarmSource(input, entry.pluginTaskId ?? null) : undefined;
if (entry || remoteWarmRecovery?.releasedSource) {
if (input.execution.provider.kind === "codex" ||
(input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude")) {
@@ -12644,7 +12573,10 @@ async function executePaperclipNativeSessionAttempt(
pluginTaskDescription,
retainedPluginTaskOwner: existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner,
relaunchReleased: relaunchReleased ? { source: relaunchReleased.source, runner: relaunchReleased.runner } : undefined,
onPluginTaskOwner: owner => { if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner; },
onPluginTaskOwner: owner => {
if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner;
else if (remoteWarmRecovery?.releasedSource && !releasedRecoveryOwner) releasedRecoveryOwner = owner;
},
beginRetainedRunAttachment: existingWarmSession && reusingReleasedRunner ? beginRetainedRunAttachment(existingWarmSession) : undefined,
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId,
remoteWarmRecovery: remoteWarmRecovery ? (recovery => ({
@@ -12678,13 +12610,22 @@ async function executePaperclipNativeSessionAttempt(
input.useRunnerd && input.backend === undefined
? await timeController("backend_setup", () => executionContext ? executionContext.wait(createExecutionBackend) : createExecutionBackend())
: null;
let releasedRecoveryUnavailable: Error | undefined;
let recovered: Awaited<ReturnType<NonNullable<NonNullable<typeof runnerdBackend>["recoverSession"]>>> | undefined;
if (remoteWarmRecovery) {
const recovery = remoteWarmRecovery;
if (executionContext) await executionContext.wait(() => recovery.revalidate(leaseOwner));
else await recovery.revalidate(leaseOwner);
const recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, {
signal: executionContext?.signal ?? new AbortController().signal,
});
try {
recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, {
signal: executionContext?.signal ?? new AbortController().signal,
});
} catch (error) {
if (!recovery.releasedSource || !(error instanceof Error) || error.message !== "native_runner_reuse_unavailable") throw error;
releasedRecoveryUnavailable = error;
}
}
if (remoteWarmRecovery && !releasedRecoveryUnavailable) {
if (!recovered?.recovered || !recovered.session) throw new Error("runner_state_identity_mismatch: remote_warm_session_unproven");
const movedSession = remoteWarmRecovery.portableSourceTaskId !== undefined;
// A portable resume already starts a new Runner. Its run attachment
@@ -12733,12 +12674,14 @@ async function executePaperclipNativeSessionAttempt(
)).then(rows => rows[0])
: null;
let remoteCleanupLease = await readRemoteCleanupLease();
const continueAfterUnavailableReuse = async (error: unknown) => {
const continueAfterUnavailableReuse = async (error: unknown, recovering = false) => {
const target = input.runnerExecutionTarget;
const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner;
const releasedRecovery = recovering && remoteWarmRecovery?.releasedSource ? remoteWarmRecovery : undefined;
const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession)
: relaunchReleased?.owner ?? (releasedRecovery ? releasedRecoveryOwner : undefined);
if (!(error instanceof Error) || error.message !== "native_runner_reuse_unavailable" || !retainedOwner
|| retainedOwner.retiredBeforeClaim() !== true
|| remoteWarmRecovery || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox"
|| (remoteWarmRecovery && !releasedRecovery) || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox"
|| !target.runnerTask || runnerdBackend === null) return false;
const retainedTaskId = target.sandboxLeaseAcquisition?.providerLeaseId;
if (existingWarmSession) await existingWarmSession.close({ reason: "retained Runner was unavailable for reuse" });
@@ -12750,6 +12693,16 @@ async function executePaperclipNativeSessionAttempt(
}
}
relaunchReleased = undefined;
if (releasedRecovery) {
if (remoteWarmRecoveryPending) {
if (executionContext) await executionContext.wait(() => releasedRecovery.revalidate(leaseOwner));
else await releasedRecovery.revalidate(leaseOwner);
}
remoteWarmRecovery = undefined;
remoteWarmRecoveryPending = false;
releasedRecoveryOwner = undefined;
await finishStartupContextForFallback();
}
const inspect = () => target.runnerTask!({ kind: "describe" }, executionContext ? { executionContext } : undefined);
const description = environmentTaskResultSchema.parse(await (executionContext ? executionContext.wait(inspect) : inspect()));
if (description.kind !== "description" || description.taskId === retainedTaskId) return false;
@@ -12761,6 +12714,7 @@ async function executePaperclipNativeSessionAttempt(
remoteCleanupLease = await readRemoteCleanupLease();
return true;
};
if (releasedRecoveryUnavailable && !await continueAfterUnavailableReuse(releasedRecoveryUnavailable, true)) throw releasedRecoveryUnavailable;
const portTarget = input.runnerExecutionTarget;
if (input.useRunnerd && !input.backend && !existingWarmSession && portTarget?.kind === "remote" && portTarget.transport === "sandbox"
&& portTarget.runner && !portTarget.runnerTask && portTarget.sandboxLeaseAcquisition?.outcome === "resumed"
@@ -14183,11 +14137,8 @@ async function executePaperclipNativeSessionAttempt(
|| entry.pluginTaskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
throw new Error("native_session_released_source_mismatch");
}
const source = operation.identity;
updateReleasedWarmRunner(input.execution, source, entry.pluginTaskId,
{ source, taskId: entry.pluginTaskId, scopeDigest: releasedWarmScope(input) });
} catch {
entry.closeOnReleaseReason = "released Runner source proof could not be verified or saved";
entry.closeOnReleaseReason = "released Runner source could not be verified";
await closeWarmNativeSession(entry, entry.closeOnReleaseReason);
forgetWarmNativeSession(scope, entry);
return;
@@ -17060,8 +17011,6 @@ async function createRunnerdBackendWithinSessionClaim(
releasedSource: input.remoteWarmRecovery?.releasedSource,
releasedSourceRunner: input.remoteWarmRecovery?.releasedSourceRunner,
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
onResumed: async source => updateReleasedWarmRunner(input.execution, source, input.remoteWarmRecovery?.portableSourceTaskId ?? description.taskId, null),
onRetired: async source => updateReleasedWarmRunner(input.execution, source, description.taskId, null),
adoptIdentity: adoptionIdentity ?? (adopting && prior ? {
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
import { arbitrateNativeStatus } from "./status-arbiter.js";
import { PLAN_NOT_PRODUCED_REASON } from "./plan-mode-status.js";
const yieldedWait: NativeEvidenceAssessment = {
objectiveClaimSatisfied: false, objectiveSatisfied: false, allCriteriaSatisfied: false, verificationPassed: false,
hasFailedVerification: false, hasBlockingRemainingWork: false, reportedDisposition: "yielded",
summary: "Waiting for plan review", contractRevisionMatches: true, criterionAssessments: [],
verificationAssessments: [], verificationCaveats: [], acceptedEvidenceRefs: [], missingRequirements: [],
rejectedEvidence: [], unverifiableEvidence: [], blocker: null,
continuation: { kind: "response_wake", summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
attentionRequests: [], ignoredAttentionRequests: [],
} as NativeEvidenceAssessment;
const arbitrate = (overrides: Partial<Parameters<typeof arbitrateNativeStatus>[0]>) => arbitrateNativeStatus({
assessment: yieldedWait, terminalState: "succeeded", workspaceFinalizeStatus: "succeeded",
agentId: "agent", priorIssueStatus: "in_progress", ...overrides,
});
// Every way a Plan-mode response wait can settle leaves the user one current
// action (the review card is the gate) or schedules the agent to produce one.
describe("Plan-mode response wait settlement", () => {
it.each([
{ name: "assigned run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" } },
reasonCode: "governed_response_waiting", next: "card" },
{ name: "comment-started run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" }, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
reasonCode: "governed_response_waiting", next: "card" },
{ name: "assigned run, no plan", input: { planNotProduced: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "comment-started run, no plan", input: { planNotProduced: true, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "comment-started run whose comment was superseded, no plan", input: { planNotProduced: true, boardResponseWaitOrigin: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "second miss after the continuation", input: { planNotProduced: true, allowIncompleteContinuation: false },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "recovery" },
])("$name", ({ input, reasonCode, next }) => {
const decision = arbitrate(input);
expect(decision.reasonCode).toBe(reasonCode);
const kinds = decision.effects.map(effect => effect.kind);
if (next === "card") expect(kinds).toContain("create_interaction");
if (next === "continuation") expect(kinds).toContain("enqueue_continuation");
if (next === "recovery") expect(kinds).toContain("record_finalization_error");
});
it("leaves Standard-mode and conversation waits unchanged", () => {
expect(arbitrate({}).reasonCode).toBe("response_wake_waiting_for_input");
expect(arbitrate({ boardResponseWaitAuthorized: true }).reasonCode).toBe("board_response_waiting");
expect(arbitrate({ planNotProduced: true, isConversation: true }).reasonCode).not.toBe(PLAN_NOT_PRODUCED_REASON);
});
});
@@ -0,0 +1,36 @@
import type { NativeAuthoritativeIssueStatus, NativeStatusDecision } from "./status-arbiter.js";
export const PLAN_NOT_PRODUCED_REASON = "plan_mode_plan_not_produced";
/**
* Plan mode waits only on a plan review. A Plan-mode run that yields a
* response wait with no plan to review (none saved, or the current revision
* already answered) must not rest as a silent wait. The agent is asked once to
* save its plan (its review card then opens); after that, the task keeps its
* status and shows a recovery step.
*/
export function planNotProducedDecision(input: {
priorIssueStatus: NativeAuthoritativeIssueStatus;
agentId: string;
allowIncompleteContinuation?: boolean;
}): Omit<NativeStatusDecision, "policyVersion"> {
if (input.allowIncompleteContinuation === false) {
return {
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
effects: [{ kind: "record_finalization_error", cause: PLAN_NOT_PRODUCED_REASON,
nextAction: "The agent finished in Plan mode without a new plan to review. Ask it to write the plan, or switch the task out of Plan mode.",
agentId: input.agentId }],
};
}
return {
statusAction: "in_progress", toStatus: "in_progress",
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
effects: [{
kind: "enqueue_continuation", continuationKind: "same_agent",
summary: "This task is in Plan mode and there is no new plan to review. Save your plan (or the revised plan) to this task's Plan document; Paperclip then asks the user to approve it. If you need an answer first, ask a question instead of waiting.",
// The bounded incomplete-report key: a second miss gets the recovery step.
idempotencyKey: "native-completion-incomplete", agentId: input.agentId,
}],
};
}
@@ -311,7 +311,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr
const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false });
await waitForCondition("automatic release A", () => releases.length === 1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } });
expect(await proof()).toMatchObject({ source: releases[0], taskId: taskA });
expect(await proof()).toBeUndefined();
const providerSessionId = (await supervisor()).snapshot.providerSessionId;
expect(providerSessionId).toEqual(expect.any(String));
if (detached) await new Promise(done => setTimeout(done, detachedIdleTimeoutMs + 200));
@@ -401,7 +401,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr
const runB = await admitNext();
if (denied || mode === "bare unavailable") return;
await waitForCondition("automatic release B", () => releases.length === 2);
expect(await proof()).toMatchObject({ source: releases[1], taskId: taskB });
expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/);
expect(submissions).toBe(2);
@@ -248,7 +248,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
await waitForCondition("parked Runner stopped", () => handle!.isExitConfirmed?.() === true);
const identity = { ...operation.identity, ...operation.runner };
const archived = join(runnerRoot, `archived-${operation.identity.runId}.json`);
const archivedState = await state();
const parkedState = await state();
await rename(join(runnerRoot, "runner-state.json"), archived);
const launch = submittedLaunch!.launch!;
listenPath = `/api/runner/v1/connect/${identity.runId}`;
@@ -260,8 +260,8 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
...(harness === "claude" ? { acpxLaunchProfile: { authorityDigest: `sha256:${sha("fixture authority")}`, command: sidecar,
commandSha256: `sha256:${sha(await readFile(sidecar, "utf8"))}`, sidecarScript,
sidecarScriptSha256: `sha256:${sha(await readFile(sidecarScript, "utf8"))}` } } : {}) });
relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: archivedState.runId });
return { kind: "resume", taskId, outcome: "resumed", runner: artifact, archivedState };
relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: parkedState.runId });
return { kind: "resume", taskId, outcome: "resumed", runner: artifact };
}
if (operation.kind === "resume") {
expect(relaunch).toBe(false);
@@ -310,7 +310,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false });
await waitForCondition("automatic release A", () => releases.length === 1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } });
expect(await proof()).toMatchObject({ source: releases[0], taskId });
expect(await proof()).toBeUndefined();
const providerSessionId = (await supervisor()).snapshot.providerSessionId;
expect(providerSessionId).toEqual(expect.any(String));
const pid = handle!.child.pid;
@@ -324,7 +324,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] });
} else await new Promise(done => setTimeout(done, adoptedIdleTimeoutMs + 200));
expect(stops).toBe(0); expect(handle!.isExitConfirmed?.()).toBe(false);
expect(await proof()).toMatchObject({ source: releases[0], taskId });
expect(await proof()).toBeUndefined();
}
expect(readNativeSessionIdleWork()).toBe("none");
await reconcileNativeFinalizations(db, [runId]);
@@ -358,7 +358,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
expect(handle!.isExitConfirmed!()).toBe(true);
expect((await readFile(calls, "utf8")).split(/\r?\n/).filter(method => method === "turn/start")).toHaveLength(1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runB)))).toHaveLength(0);
expect(releases).toHaveLength(1); expect((await proof())?.source.runId).not.toBe(runB);
expect(releases).toHaveLength(1); expect(await proof()).toBeUndefined();
return runB;
}
expect(await pendingFollowup).toMatchObject({ exitCode: 0, timedOut: false });
@@ -369,7 +369,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
const runB = await admitNext();
if (cancellation) return;
await waitForCondition("automatic release B", () => releases.length === 2);
expect(await proof()).toMatchObject({ source: releases[1], taskId });
expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
expect(adoption).toHaveBeenCalledTimes(adopted ? 1 : 0);
if (adopted) expect(adoption.mock.calls[0]![0]).toMatchObject({ identity: releases[0], execution: { binding: { runId: runB } } });
@@ -377,7 +377,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
if (adopted) {
runC = await admitNext();
await waitForCondition("automatic release C", () => releases.length === 3);
expect(releases[2]!.runId).toBe(runC); expect(await proof()).toMatchObject({ source: releases[2], taskId });
expect(releases[2]!.runId).toBe(runC); expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
expect(adoption).toHaveBeenCalledTimes(1);
}
@@ -615,17 +615,11 @@ describe("plugin Runner release/resume facade", () => {
it.each([
["the parked build", undefined],
["a relaunched build", { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` }],
])("clears the released Runner proof after a resume on %s, once Core saved a relaunched build", async (_label, runner) => {
])("passes the provider's resume outcome through on %s", async (_label, runner) => {
const task = vi.fn(async (): Promise<unknown> => ({ kind: "resume", taskId: "task", outcome: "resumed", ...(runner ? { runner } : {}) }));
const onResumed = vi.fn(async () => {});
const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, onResumed, resumeRelaunchedRunnerVersion: 1 });
const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, resumeRelaunchedRunnerVersion: 1 });
const outcome = await owner.driver.releaseResume!.resume(requirements.identity, "transient-ticket");
if (runner) {
expect(outcome).toEqual({ outcome: "resumed", runner, settled: expect.any(Function) });
expect(onResumed).not.toHaveBeenCalled();
if (typeof outcome === "object") await outcome.settled?.();
} else expect(outcome).toBe("resumed");
expect(onResumed).toHaveBeenCalledExactlyOnceWith(requirements.identity);
expect(outcome).toEqual(runner ? { outcome: "resumed", runner } : "resumed");
});
it("resumes with the credential resolved for the rebound claimant run", async () => {
@@ -805,8 +799,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
const next = { ...source, runId: "next-run", turnId: "turn-next-run", itemId: "item-next-run" };
const parked = { version: "0.4.0", digest: `sha256:${"c".repeat(64)}` };
const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` };
const settledCut = { schema: "paperclip.runner.durable.state.v1", ...source, lifecycle: "ready", nextSourceSeq: 4, ackedSourceSeq: 3,
outbox: [], pendingTerminalDelivery: null, processedCommands: {} };
const base = { taskId: "task", projectIds: ["00000000-0000-4000-8000-000000000001"], projectAuthCheckVersion: 1 as const, harness: "codex", warmTaskVersion: 1 as const, releaseResumeVersion: 1 as const,
accountIdentity: "selected-account", credentialIdentity: "selected-credential" };
const relaunchSpec = (): RunnerProcessLaunchSpec => {
@@ -814,14 +806,14 @@ describe("plugin Runner relaunch as the claimant run", () => {
return { ...spec, nativeRunner: { ...spec.nativeRunner!, identity: next, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } };
};
async function relaunchOwner(resume: (operation: any) => unknown,
options: { resumeIdentityVersion?: 1; onResumed?: () => Promise<void>; fresh?: true } = { resumeIdentityVersion: 1 }) {
options: { resumeIdentityVersion?: 1; fresh?: true } = { resumeIdentityVersion: 1 }) {
const { task } = provider();
const perform = task.getMockImplementation()!;
task.mockImplementation(async operation => operation.kind === "resume" ? resume(operation) : perform(operation));
const close = vi.fn(async () => {});
ingress.connect.mockReset().mockReturnValue({ ready: Promise.resolve(), quiesce: vi.fn(), close });
const relaunchInput = { ...base, task, authorityRunId: next.runId, resumeRelaunchedRunnerVersion: 1 as const,
resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked }, onResumed: options.onResumed };
resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked } };
const owner = createPluginRunnerTaskOwner(options.fresh ? relaunchInput : { ...base, task, adoptIdentity: source, authorityRunId: source.runId });
if (!options.fresh) owner.rebind(relaunchInput);
await prepare(owner, { ...requirements, identity: next });
@@ -831,10 +823,8 @@ describe("plugin Runner relaunch as the claimant run", () => {
}
it("starts the stopped Runner again as the claimant run and accepts the reported build", async () => {
const onResumed = vi.fn(async () => {});
const { owner, task, authority, registration } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }),
{ resumeIdentityVersion: 1, onResumed });
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build }));
expect(owner.driver.relaunchReleasedRunner).toEqual(source);
expect(owner.driver.adoptExistingRunner).toBeUndefined();
expect(owner.relaunchMayHaveStarted()).toBe(false);
@@ -848,7 +838,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
}]);
expect(task.mock.calls.some(([operation]) => operation.kind === "submit")).toBe(false);
expect(authority.acceptRelaunchedRunner).toHaveBeenCalledExactlyOnceWith("synthetic-ticket", build, parked);
expect(onResumed).toHaveBeenCalledExactlyOnceWith(source);
expect(ingress.connect).toHaveBeenCalledOnce();
expect(owner.relaunchMayHaveStarted()).toBe(true);
owner.rebind({ ...base, task, authorityRunId: "later-run", resumeRelaunchedRunnerVersion: 1, resumeIdentityVersion: 1,
@@ -859,7 +848,7 @@ describe("plugin Runner relaunch as the claimant run", () => {
it("relaunches through a new owner, as after a Core restart, without submitting or adopting", async () => {
const { owner, task, authority, registration } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }),
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build }),
{ resumeIdentityVersion: 1, fresh: true });
expect(task.mock.calls.find(([operation]) => operation.kind === "prepare")?.[0]).toMatchObject({ priorIdentity: source });
expect(owner.driver.relaunchReleasedRunner).toEqual(source);
@@ -885,7 +874,7 @@ describe("plugin Runner relaunch as the claimant run", () => {
let attempts = 0;
const { task, registration, owner } = await relaunchOwner(() => {
if (attempts++ === 0) throw new Error("fixture resume reply lost");
return { kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut };
return { kind: "resume", taskId: "task", outcome: "resumed", runner: build };
});
owner.launcher(relaunchSpec());
registration.activate();
@@ -897,21 +886,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
} finally { await registration.release("detach"); }
});
it.each([
["an unsettled cut", { ...settledCut, outbox: [{ sourceSeq: 4 }] }],
["another source's cut", { ...settledCut, runId: "other-run" }],
])("refuses %s before the Runner can connect", async (_label, archivedState) => {
const { authority, registration, owner } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState }));
owner.launcher(relaunchSpec());
registration.activate();
try {
await expect(registration.ready()).rejects.toThrow("native_runner_released_state_unsettled");
expect(authority.acceptRelaunchedRunner).not.toHaveBeenCalled();
expect(owner.relaunchMayHaveStarted()).toBe(true);
expect(ingress.connect).not.toHaveBeenCalled();
} finally { await registration.release("detach"); }
});
it("reports an unavailable relaunch for ordinary recovery", async () => {
const { registration, owner } = await relaunchOwner(() => ({ kind: "resume", taskId: "task", outcome: "unavailable" }));
@@ -5,7 +5,7 @@ import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvir
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent,
isSettledReleasedRunnerCut } from "../../vendor/paperclip-runner/index.js";
} from "../../vendor/paperclip-runner/index.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
import type { NativeExecutionContext } from "./native-execution-context.js";
@@ -60,8 +60,6 @@ export function createPluginRunnerTaskOwner(input: {
launchDigestVersion?: 1;
releasedSource?: DurableRecoveryIdentity;
sessionHandoff?: boolean;
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
onRetired?: (identity: DurableRecoveryIdentity) => Promise<void>;
githubBroker?: { url: string; token: string };
githubCredentialBrokerVersion?: 1;
configuredEnvironmentVersion?: 1;
@@ -262,11 +260,8 @@ export function createPluginRunnerTaskOwner(input: {
retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true;
throw new Error("native_runner_reuse_unavailable");
}
if (!result.archivedState || !result.runner || !isSettledReleasedRunnerCut(result.archivedState, source)) {
throw new Error("native_runner_released_state_unsettled");
}
if (!result.runner) throw new Error("native_runner_released_state_unsettled");
authority.acceptRelaunchedRunner(native.ticket, result.runner, relaunch.runner);
await input.onResumed?.(source);
markReady();
return;
}
@@ -429,8 +424,6 @@ export function createPluginRunnerTaskOwner(input: {
if (submitted) {
await call({ kind: "complete" });
completed = true;
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
if (identity) await input.onRetired?.(identity);
}
},
// The Runner is about to exit (its close suspend completed), as on release.
@@ -469,10 +462,7 @@ export function createPluginRunnerTaskOwner(input: {
if (activeOutbound === outbound) activeOutbound = null;
},
resume: async (identity: DurableRecoveryIdentity, ticket: string) => {
const outcome = await resume(identity, ticket);
if (typeof outcome === "object") return { ...outcome, settled: async () => { await input.onResumed?.(identity); } };
if (outcome === "resumed") await input.onResumed?.(identity);
return outcome;
return await resume(identity, ticket);
},
};
},
@@ -555,8 +545,6 @@ export function createPluginRunnerTaskOwner(input: {
}
await call({ kind: "complete" });
completed = true;
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
if (identity) await input.onRetired?.(identity);
}
return stoppedState?.executionStopped === true && completed && !detached;
};
@@ -5,6 +5,7 @@ import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, N
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
import { planNotProducedDecision } from "./plan-mode-status.js";
import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CODE,
NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS } from "./native-agent-blocker.js";
@@ -236,6 +237,8 @@ export function arbitrateNativeStatus(input: {
publishedExternalReview?: boolean;
/** Server-verified accepted plan request and normal provider terminal. */
planWaitAuthorized?: boolean;
/** A Plan-mode run settled with no unanswered plan revision to review. */
planNotProduced?: boolean;
monitorWaitAuthorized?: boolean;
caseHandoffAuthorized?: boolean;
/** The saved timer already admitted another run and this run no longer owns checkout. */
@@ -854,6 +857,12 @@ export function arbitrateNativeStatus(input: {
effects: [],
};
}
// Before the passive board/response waits: a Plan-mode run, assigned or
// comment-started, with no plan to review must not rest as a silent wait.
if (input.planNotProduced === true && !input.isConversation && input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake") {
return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, ...planNotProducedDecision(input) };
}
if (
input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake" &&
+23
View File
@@ -28,6 +28,7 @@ import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
import { RESTRICTED_WORKSPACE_SOURCE_REASON } from "../workspace-source-restriction.js";
import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js";
import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.js";
import { ensureNativePlanReviewCard } from "../native-runtime/native-plan-review-card.js";
import { hasCommittedNativeConversationTurnWait, hasCommittedNativeResponseWakeWait } from "../native-runtime/native-response-wake-wait.js";
import { listExternalReviewWaits } from "../native-runtime/external-review-wait.js";
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
@@ -5099,6 +5100,28 @@ export function recoveryService(
continue;
}
// A Plan-mode task whose run settled before the server opened plan
// review cards on settle (or whose card opening was interrupted) gets
// its card here; the card is then its next action.
if (
issue.workMode === "planning" &&
issue.status === "in_progress" &&
latestRun?.status === "succeeded" &&
latestRun.agentId === agentId &&
// An accepted native plan waits for the user's next message; its
// answered plan question is the review. Never ask for it again.
parseObject(latestRun.resultJson).finalizationReasonCode !== "native_plan_accepted_waiting_for_continuation" &&
!(await hasCommittedNativePlanWait(db, {
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
})) &&
(await ensureNativePlanReviewCard(db, {
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
})).kind === "created"
) {
result.skipped += 1;
result.issueIds.push(issue.id);
continue;
}
if (
await hasActiveExecutionPath(
issue.companyId,
+2 -1
View File
@@ -641,7 +641,7 @@ type RemoteHttpExecutionAudit = {
protocol: "MCP JSON-RPC 2.0" | "Railway GraphQL" | "Railway GraphQL + SSH" | "Google Workspace REST";
httpMethod: "POST";
endpoint: string;
mcpMethod: "tools/call";
mcpMethod?: "tools/call";
requestId: string;
upstreamToolName: string;
dispatched: true;
@@ -8419,6 +8419,7 @@ export function createToolGatewayService(
};
if (workspaceTarget?.transport === "paperclip_rest") {
execution.request.protocol = "Google Workspace REST";
delete execution.request.mcpMethod;
execution.request.endpoint = googleWorkspaceRestAuditEndpoint(workspaceTarget.service);
await assertWorkspaceGrantCurrent();
const signal = taskSignals.run ? AbortSignal.any([controller.signal, taskSignals.run]) : controller.signal;
-1
View File
@@ -101,7 +101,6 @@ export const decodeDurablePrpCheckpoint = runner.decodeDurablePrpCheckpoint;
export const captureLegacyDurablePrpCheckpoint = runner.captureLegacyDurablePrpCheckpoint;
export const inspectDurablePrpCheckpointHeader = runner.inspectDurablePrpCheckpointHeader;
export const inspectDurablePrpCheckpointRunner = runner.inspectDurablePrpCheckpointRunner;
export const isSettledReleasedRunnerCut = runner.isSettledReleasedRunnerCut;
export const revertUnattachedRelaunchRotation = runner.revertUnattachedRelaunchRotation;
export const inspectUnclaimedBootstrapCheckpoint = runner.inspectUnclaimedBootstrapCheckpoint;
export const inspectUnauthenticatedBootstrapCheckpoint = runner.inspectUnauthenticatedBootstrapCheckpoint;