From 9911b7052f602ae4bc2296ca27b05651fe4b873b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:23:19 -0600 Subject: [PATCH] Expose continuation retry keys and preserve account-repair resumes (#22046) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Runner gives agents a tool to report work and wait for a later check. > - That tool requires a stable retry key for each explicit wait. > - Codex can hide the wait fields when it renders our nested schema. > - Hidden fields make a correct report harder to construct. > - This pull request changes the provider schema structure and preserves its rules. > - Agents can see the required fields before they submit a report. ## Linked Issues or Issue Description **What happened?** The completion tool appears in Codex code mode with `continuation?: unknown`. An agent can omit the required retry key and receive a rejected report. The top-level schema was fixed in #21398. The nested continuation still uses the same problematic structure. **Expected behavior** Codex must show the required `kind`, `summary`, and `idempotencyKey` fields. Invalid reports must still fail validation. **Steps to reproduce** Render `PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA` with the public Codex code-mode renderer at `b271854568d6c9282e999d6f36e5e85f447d027d`. Its `render_map` function processes `allOf` before sibling properties. The conditional-only branch renders as `unknown` and hides those properties. Source: https://github.com/openai/codex/blob/b271854568d6c9282e999d6f36e5e85f447d027d/codex-rs/code-mode-protocol/src/json_schema_types.rs#L127 **Paperclip version or commit** Baseline: `01451fae5b25f784956e9932f12031dc194ac247`. The first complete CI browser attempt also exposed an intermittent account-repair race. Repair restores the task and resolves its recovery action, then a sweep can reclassify the same old failure and block it again before the queued reply starts. The repair in this PR honors that exact persisted resolution while holding the existing task lock. A later failed run still escalates. ## What Changed - Express the single provider continuation condition as direct `if` and `then` fields. This is equivalent to its previous `allOf` wrapper. - Keep the canonical output schema unchanged. Keep required retry keys and case handoff IDs. - Add a discovery guard, a 60-case provider/canonical validation comparison, and authenticated HTTP bridge checks. ### Hypothesis and thesis for a fix The nested `allOf` hides fields in the tested Codex renderer. The equivalent direct condition lets that renderer reach the object fields. This belongs in the existing provider compatibility schema. It changes no controller policy, company access, saved state, or retry identity. The experiment proves field visibility. It does not prove which renderer served a historical request or measure model omission rates. - Honor a resolved/restored configuration recovery for the same company, task and failed run before re-escalating. Dispatch checks and recovery for new failures remain intact. - Add a PostgreSQL regression covering repeat sweeps, a new failure identity, an unresolved recovery, and another task's repair. This belongs in the existing locked escalation function; no new state or subsystem is introduced. `service.ts` was already over 1,000 lines. - Define the handoff condition once and explicitly compose both canonical and provider schemas from it, removing the implicit one-element `allOf` assumption raised in review. ## Verification - Built and ran the exact pinned public Codex renderer in a disposable Rust crate. The complete baseline schema renders `continuation?: unknown`. The changed schema renders a nullable object with required `kind`, `summary`, and `idempotencyKey` fields. - The new discovery regression fails on the baseline. The same test passes with the fix. - Runner: `pnpm exec vitest run src/contracts/completion-result.test.ts src/contracts/tool-input-variants.test.ts src/contracts/provider-tool-schema-shape.test.ts src/drivers/runner-tool-bridge.schemas.test.ts src/drivers/runner-tool-bridge.continuation.test.ts` — 48 tests pass. - Runner: `pnpm exec tsc -p tsconfig.json` and `node scripts/generate-semantic-contracts.mjs --check` pass. - Server: the selected `task-monitor.integration.test.ts` test for unfinished monitor waits passes with embedded PostgreSQL. It rejects an unscheduled wait and accepts the saved monitor. - Server: the selected `issue-monitor-scheduler.test.ts` recovery test passes with embedded PostgreSQL. It checks persistence, same-key replay, and one scheduled wake. The fixture's successor run fails its separate responsible-user setup. This is not proof of successful successor execution. - HTTP bridge handler is simulated. It verifies rejection before dispatch, valid monitor/response-wake/handoff reports, retry identity, and authentication. - Recovery regression: baseline 1 failed / 3 passed (the restored task was blocked again); unchanged test after the fix 4 passed. Together with recovery state-read tests: 7 passed. Existing configuration-recovery selection: 4 passed, 108 deselected. - Final completion schema and authenticated HTTP bridge selection: 33 passed. - Local real browser journey with disposable embedded PostgreSQL and ACP/provider fixtures: baseline repeat5 produced 2 failures / 3 passes, matching CI. Fixed repeat5: 5 passed in 1.8 minutes. The test independently checks exactly one successful successor, stored connection binding and persisted reply after reload. - No full local suite, deployed recovery, or probabilistic model result is claimed. Fresh CI and review are required for the updated head. - Review follow-up: 48 focused schema/discovery/HTTP tests pass; `node scripts/generate-semantic-contracts.mjs --check` passes. Fresh CI/review required after the refactor. ## Risks Low runtime risk. The accepted input rules are unchanged. A provider that handles direct conditionals differently could expose a compatibility issue. The canonical validator still enforces the output contract. No migration or saved-session reset is needed. Previously saved state keeps the same format. Recovery now honors existing resolved/restored actions only for the exact failed source run, so a new configuration failure remains eligible for escalation. Company, task, ownership and dispatch checks remain in force. ## Model Used OpenAI GPT-6 Codex agent, with reasoning, tool use, and code execution. The runtime did not expose a more specific model ID. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../src/contracts/completion-result.test.ts | 21 +++++++ .../src/contracts/completion-result.ts | 20 +++++- .../runner-tool-bridge.continuation.test.ts | 63 +++++++++++++++++++ .../recovery/restored-configuration.test.ts | 48 ++++++++++++++ server/src/services/recovery/service.ts | 12 ++++ 5 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/runner-tool-bridge.continuation.test.ts create mode 100644 server/src/services/recovery/restored-configuration.test.ts diff --git a/packages/paperclip-runner/src/contracts/completion-result.test.ts b/packages/paperclip-runner/src/contracts/completion-result.test.ts index 807ba5f0ec2..e01308fa806 100644 --- a/packages/paperclip-runner/src/contracts/completion-result.test.ts +++ b/packages/paperclip-runner/src/contracts/completion-result.test.ts @@ -204,6 +204,27 @@ describe("provider-neutral completion result schema", () => { expect(validate(response)).toBe(false); }); + it("keeps nested continuation fields visible to code-mode discovery without changing validation", () => { + const continuation = PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA.properties.continuation; + expect(continuation).not.toHaveProperty("allOf"); + expect(continuation.type).toEqual(["object", "null"]); + expect(continuation.required).toEqual(["kind", "summary", "idempotencyKey"]); + const provider = new Ajv2020({ strict: false }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA); + const canonical = new Ajv2020({ strict: false }).compile(PRP_COMPLETION_RESULT_OUTPUT_SCHEMA); + for (const kind of ["monitor", "response_wake", "case_handoff", "same_agent", "invented"]) { + for (const key of [undefined, "", 42, "stable-wait-key"]) { + for (const handoffId of [undefined, "", "accepted-handoff-id"]) { + const report = { ...baseResult, reportedWorkDisposition: "yielded", continuation: { + kind, summary: "Wait for the next action.", + ...(key === undefined ? {} : { idempotencyKey: key }), + ...(handoffId === undefined ? {} : { handoffId }), + } }; + expect(provider(report), JSON.stringify(report.continuation)).toBe(canonical(report)); + } + } + } + }); + it("exposes concrete completion fields while retaining response-wake validation", () => { // The live Codex code-mode renderer reduced a conditional-only root allOf // to `args: unknown`. Keep this tool object-shaped for provider discovery. diff --git a/packages/paperclip-runner/src/contracts/completion-result.ts b/packages/paperclip-runner/src/contracts/completion-result.ts index 026becebbe6..6ec8aef35aa 100644 --- a/packages/paperclip-runner/src/contracts/completion-result.ts +++ b/packages/paperclip-runner/src/contracts/completion-result.ts @@ -166,7 +166,7 @@ const artifactsSchema = { }, } as const; -const waitContinuationSchema = { +const waitContinuationProperties = { type: "object", description: "Required when reportedWorkDisposition is yielded. Use response_wake for a response wait, or monitor only after a real monitor is persisted on the current task. Include kind, summary, and a stable idempotencyKey.", @@ -183,7 +183,21 @@ const waitContinuationSchema = { idempotencyKey: { type: "string", minLength: 1 }, handoffId: { type: "string", minLength: 1, description: "Exact server-issued handoff ID; required for case_handoff." }, }, - allOf: [{ if: { properties: { kind: { const: "case_handoff" } }, required: ["kind"] }, then: { required: ["handoffId"] } }], +} as const; + +const waitContinuationCondition = { + if: { properties: { kind: { const: "case_handoff" } }, required: ["kind"] }, + then: { required: ["handoffId"] }, +} as const; + +const waitContinuationSchema = { + ...waitContinuationProperties, + allOf: [waitContinuationCondition], +} as const; + +const providerWaitContinuationSchema = { + ...waitContinuationProperties, + ...waitContinuationCondition, } as const; const commonResultProperties = { @@ -391,7 +405,7 @@ export const PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA = { // tool calls. Give non-yielding results an explicit absence value instead // of forcing callers to invent a response-wake continuation. continuation: { - ...waitContinuationSchema, + ...providerWaitContinuationSchema, type: ["object", "null"], description: "For yielded, omit or use null to reuse this run's authorized published-review wait, eligible saved monitor, or repository-preparation continuation; the controller reads current task state. Otherwise provide a real response_wake or monitor with summary and idempotencyKey. Use null or omit for done, completed, or needs_review.", diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.continuation.test.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.continuation.test.ts new file mode 100644 index 00000000000..a270aa20538 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.continuation.test.ts @@ -0,0 +1,63 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { startRunnerToolBridge, type RunnerToolBridge } from "./runner-tool-bridge.js"; + +const bridges: RunnerToolBridge[] = []; +afterEach(async () => { await Promise.all(bridges.splice(0).map(bridge => bridge.close())); }); + +it("advertises readable continuation fields and rejects malformed waits before dispatch", async () => { + const handler = vi.fn(async () => ({ accepted: true })); + const bridge = await startRunnerToolBridge({ tools: [], handler }); + bridges.push(bridge); + const rpc = async (body: Record, secret = bridge.secret) => fetch(bridge.url, { + method: "POST", + headers: { Authorization: `Bearer ${secret}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", ...body }), + }); + const listed = await (await rpc({ id: "list", method: "tools/list" })).json() as { + result: { tools: Array<{ name: string; inputSchema: { properties: { continuation: Record } } }> }; + }; + const continuation = listed.result.tools.find(tool => tool.name === "paperclip_finish")!.inputSchema.properties.continuation; + expect(continuation).not.toHaveProperty("allOf"); + expect(continuation.required).toEqual(["kind", "summary", "idempotencyKey"]); + + const report = { + reportedWorkDisposition: "yielded", + summary: "The requested result is ready.", + completionClaim: { contractRevision: "1", objectiveSatisfied: false, criteria: [], remainingWork: [] }, + evidence: [], verification: [], + continuation: { kind: "monitor", summary: "Check the saved monitor.", idempotencyKey: "stable-wait" }, + }; + const call = async (id: string, value: unknown) => (await (await rpc({ + id, method: "tools/call", params: { name: "paperclip_finish", arguments: value }, + })).json() as { result: { isError?: boolean; content?: unknown } }).result; + + const { idempotencyKey: _key, ...missingKey } = report.continuation; + for (const [index, invalid] of [ + missingKey, + { ...report.continuation, idempotencyKey: "" }, + { ...report.continuation, idempotencyKey: 42 }, + { ...report.continuation, kind: "case_handoff" }, + ].entries()) { + expect((await call(`invalid-${index}`, { ...report, continuation: invalid })).isError).toBe(true); + } + expect((await call("wrong-disposition", { ...report, reportedWorkDisposition: "done" })).isError).toBe(true); + expect((await rpc({ id: "unauthorized", method: "tools/call", params: { name: "paperclip_finish", arguments: report } }, "wrong-secret")).status).toBe(401); + expect(handler).not.toHaveBeenCalled(); + + const accepted = await call("monitor", report); + expect(accepted.isError).not.toBe(true); + expect(await call("monitor", report)).toEqual(accepted); + expect(handler).toHaveBeenCalledOnce(); + expect((await call("monitor", { ...report, continuation: { ...report.continuation, idempotencyKey: "different" } })).isError).toBe(true); + expect(handler).toHaveBeenCalledOnce(); + for (const [index, valid] of [ + { ...report.continuation, kind: "response_wake" }, + { ...report.continuation, kind: "case_handoff", handoffId: "server-issued-handoff" }, + null, + ].entries()) { + expect((await call(`valid-${index}`, { ...report, continuation: valid })).isError).not.toBe(true); + } + const { continuation: _continuation, ...omitted } = report; + expect((await call("omitted", omitted)).isError).not.toBe(true); + expect(handler).toHaveBeenCalledTimes(5); +}); diff --git a/server/src/services/recovery/restored-configuration.test.ts b/server/src/services/recovery/restored-configuration.test.ts new file mode 100644 index 00000000000..49f5aa4ff34 --- /dev/null +++ b/server/src/services/recovery/restored-configuration.test.ts @@ -0,0 +1,48 @@ +import { randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { recoveryService } from "./service.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("restored configuration recovery", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("restored-configuration-"); + db = createDb(database.connectionString); + }); + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + it.each(["same_source", "new_source", "unresolved", "other_task"])("reconciles %s after configuration repair", async mode => { + const [company] = await db.insert(companies).values({ name: "Restored configuration", issuePrefix: `R${randomUUID().slice(0, 7)}` }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Worker", status: "idle", lifecycleState: "ready" }).returning(); + const [task] = await db.insert(issues).values({ companyId: company.id, title: "Resume repaired work", status: "in_progress", assigneeAgentId: agent.id }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, status: "failed", + errorCode: "configuration_incomplete", error: "Missing personal account", + resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, configurationIncomplete: { reason: "secret_binding_missing" } }, + startedAt: new Date("2026-07-15T20:00:00Z"), finishedAt: new Date("2026-07-15T20:01:00Z"), + contextSnapshot: { issueId: task.id } }).returning(); + const otherTask = mode === "other_task" ? (await db.insert(issues).values({ companyId: company.id, title: "Other task" }).returning())[0] : task; + const [resolved] = await db.insert(issueRecoveryActions).values({ companyId: company.id, sourceIssueId: otherTask.id, + kind: "stranded_assigned_issue", cause: "configuration_incomplete", fingerprint: randomUUID(), + status: mode === "unresolved" ? "active" : "resolved", outcome: mode === "unresolved" ? null : "restored", + evidence: { latestRunId: mode === "new_source" ? randomUUID() : run.id }, nextAction: "Repair the account" }).returning(); + const enqueueWakeup = vi.fn(async () => null); + const recovery = recoveryService(db, { enqueueWakeup }); + await recovery.reconcileStrandedAssignedIssues({ companyId: company.id, issueId: task.id }); + const [current] = await db.select().from(issues).where(eq(issues.id, task.id)); + expect(current).toMatchObject({ status: mode === "same_source" ? "in_progress" : "blocked", assigneeAgentId: agent.id }); + if (mode === "same_source") { + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, task.id))).toEqual([resolved]); + await recovery.reconcileStrandedAssignedIssues({ companyId: company.id, issueId: task.id }); + expect((await db.select().from(issues).where(eq(issues.id, task.id)))[0]).toEqual(current); + } + expect(enqueueWakeup).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 75efec067d3..67c3829b097 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -4257,6 +4257,18 @@ export function recoveryService( return null; } + if (input.recoveryCause === "configuration_incomplete" && input.latestRun) { + const [restored] = await tx.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, current.companyId), + eq(issueRecoveryActions.sourceIssueId, current.id), + eq(issueRecoveryActions.cause, "configuration_incomplete"), + eq(issueRecoveryActions.status, "resolved"), + eq(issueRecoveryActions.outcome, "restored"), + sql`${issueRecoveryActions.evidence}->>'latestRunId' = ${input.latestRun.id}`, + )).limit(1); + if (restored) return null; + } + // Acceptance holds the same issue lock before writing its successor. // An awaiting-release handoff need not change the issue's version or // owner, and generic recovery must not cancel that durable successor.