From cbc5132e6c3925683c5fd720edf47c56b2998faf Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 28 Sep 2026 08:45:53 -0500 Subject: [PATCH] fix(adapters): expose a verified provider stop before workspace restoration (#14311) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent adapters own local or remote provider processes. > - Run cleanup must know when the final provider process has stopped. > - A remote timeout or a lost transport does not prove that the provider stopped. > - Retried provider invocations also make an earlier stop signal stale. > - This pull request adds a verified final-invocation stop callback before workspace restoration. > - The dependent instruction revision change uses that boundary to preserve private instruction edits safely. ## Linked Issues or Issue Description **What happened?** Adapter completion did not expose a reliable point between provider shutdown and workspace restoration. Cleanup could lose provider-written files, or treat a remote timeout as proof that a process stopped. **Expected behavior** Cleanup runs once after the final provider invocation has a verified stop receipt and before workspace restoration. An incomplete remote command keeps collection pending. **Steps to reproduce** 1. Run a remote provider that returns a timeout without a numeric exit code. 2. Let the adapter return or retry the provider. 3. Attempt to collect provider-written files during cleanup. The adapter has no verified final-process boundary to use. This is the prerequisite for the stacked canonical instruction revision pull request. It has no database or UI dependency. Related #13291 verifies remote termination for later recovery; this change exposes the earlier adapter-owned stop boundary before workspace restoration. The scopes do not duplicate each other. ## What Changed - Add a stop callback to adapter execution context and a final-invocation fence. - Confirm local child closure and complete remote exit receipts. Reject remote timeouts, missing exits, transport failures, and SSH exit 255 as stop proof. - Invoke collection once before workspace restoration in eight CLI adapters and at the confirmed ACP stop boundary. - Preserve the stop observation when a later log flush fails. - Run bridge and workspace cleanup in `finally` even when collection rejects. ACP records a safe error without exposing a raw filesystem path. Grok keeps collection errors separate from workspace restore failures and preserves completed provider results when both cleanup steps fail. - Correct the existing Cursor test shell fixture so bounded remote file reads run against real fixture files. ## Verification - Three stop-boundary regressions failed before the callback implementation and passed after it. - Independent prerequisite branch: 377 tests passed across 24 adapter, process-target, and ACP suites. Two added collector-rejection tests failed before the cleanup fix and passed after it. - A third regression reproduced Grok misclassifying a collection failure as failed workspace restoration. Two additional cases covered completed and failed provider turns when collection and restore both fail. The Grok and restore-classifier suites passed 48 tests. - All nine affected package typechecks and affected package builds passed; Grok checks passed again after its classification fix. - Integrated instruction branch: native local, legacy local, and native Daytona each passed three browser tasks with exact persisted bytes, fresh-task readback, history/restore, and explicit conflict resolution. Unchanged warm Daytona passed three turns. Legacy Codex passed all five checks again after the exception-safe cleanup fix. - Alternate staging passed the same three-task native Daytona flow: exact stopped-run save, independent downloaded readback, browser history/restore, and explicit resolution of a real concurrent edit. The deployed source was `14c3d810c9e05625121b3d27767aea9317b03125`, which covers the initial adapter callback. Later Grok cleanup failures are qualified by the adapter tests above. - The final combined native Daytona flow passed again on deployed `2bedd0f23bf4698b1f8b818f6796900647030427`: three fresh tasks proved ordinary instruction edits, independent readback, History/Restore, concurrent board conflict, and explicit candidate resolution. This native staging flow does not claim to exercise the Grok adapter. ## Risks - An unverified remote stop intentionally does not trigger collection. A later controller with verified stop evidence must recover it or report the copy unavailable. - The callback is optional. Callers that do not register it retain their existing behavior. - The callback runs before workspace restoration and can delay cleanup if its caller does not bound its own work. The dependent instruction collector uses bounded reads and retries. A rejected callback still permits bridge and workspace cleanup; it cannot claim an instruction save. ## Model Used OpenAI Codex, GPT-6, with tool use and code execution. The runtime does not expose the exact deployment variant or context-window size. Multiple Codex agents implemented and verified the change. ## 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/acpx-engine/execute.test.ts | 52 +++++++++++++ .../adapter-utils/src/acpx-engine/execute.ts | 30 +++++--- .../adapter-utils/src/execution-target.ts | 13 +++- .../src/provider-stopped-boundary.test.ts | 75 +++++++++++++++++++ .../src/provider-stopped-boundary.ts | 19 +++++ packages/adapter-utils/src/types.ts | 3 + .../claude-local/src/server/execute.ts | 25 ++++--- .../codex-local/src/server/execute.test.ts | 38 +++++++++- .../codex-local/src/server/execute.ts | 53 +++++++------ .../cursor-local/src/server/execute.test.ts | 16 +--- .../cursor-local/src/server/execute.ts | 31 +++++--- .../gemini-local/src/server/execute.ts | 17 +++-- .../grok-local/src/server/execute.test.ts | 63 ++++++++++++++++ .../adapters/grok-local/src/server/execute.ts | 31 +++++++- .../adapters/kimi-local/src/server/execute.ts | 17 +++-- .../opencode-local/src/server/execute.ts | 17 +++-- .../adapters/pi-local/src/server/execute.ts | 17 +++-- 17 files changed, 428 insertions(+), 89 deletions(-) create mode 100644 packages/adapter-utils/src/provider-stopped-boundary.test.ts create mode 100644 packages/adapter-utils/src/provider-stopped-boundary.ts diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts index 98a2007fd3e..2a9c57ef23e 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.test.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts @@ -6355,10 +6355,30 @@ describe("ACPX engine run lifecycle corrections (F3: one teardown error policy)" }; } + it("collects instructions after confirmed close on a thrown provider turn, before workspace restore", async () => { + const { stateDir, localCwd, executionTarget } = await setupRemoteSandbox(); + const { paperclipStops, anyStopped } = stubBridges(); + const order: string[] = []; + const execute = createAcpxEngineExecutor({ + stagingLocks: new Map(), warmHandles: new Map(), stagedRuntimes: new Map(), + createRuntime: () => ({ ensureSession: async () => okHandle, startTurn: () => throwingTurn(), + close: async () => { order.push("close"); } }) as never, + }); + const result = await execute({ runId: "instruction-stop-failure", + ...remoteArgs(stateDir, localCwd, executionTarget, { onProviderStopped: async () => { + expect(anyStopped(paperclipStops)).toBe(true); + order.push("collect"); + } }), + } as never); + expect(result.exitCode).toBe(1); + expect(order).toEqual(["close", "collect"]); + }); + it("test_teardown_continues_after_one_teardown_step_fails", async () => { const { stateDir, localCwd, executionTarget } = await setupRemoteSandbox(); const { paperclipStops, processStops, anyStopped } = stubBridges(); const stagingLocks = new Map>(); + const collectInstructions = vi.fn(async () => {}); const logs: Array<{ stream: string; text: string }> = []; const execute = createAcpxEngineExecutor({ stagingLocks, @@ -6378,6 +6398,7 @@ describe("ACPX engine run lifecycle corrections (F3: one teardown error policy)" const result = await execute({ runId: "td-continue", ...remoteArgs(stateDir, localCwd, executionTarget, { + onProviderStopped: collectInstructions, onLog: async (stream: "stdout" | "stderr", text: string) => { logs.push({ stream, text }); }, @@ -6385,6 +6406,7 @@ describe("ACPX engine run lifecycle corrections (F3: one teardown error policy)" } as never); expect(result.exitCode).toBe(1); + expect(collectInstructions).not.toHaveBeenCalled(); // The close failure did not stop the bridge stops or the lease release. expect(anyStopped(paperclipStops)).toBe(true); expect(anyStopped(processStops)).toBe(true); @@ -6395,6 +6417,36 @@ describe("ACPX engine run lifecycle corrections (F3: one teardown error policy)" ).toBe(true); }); + it("restores managed home and releases the lease when instruction collection rejects", async () => { + const { stateDir, localCwd, executionTarget } = await setupRemoteSandbox(); + const { paperclipStops, processStops, anyStopped } = stubBridges(); + const stagingLocks = new Map>(); + const order: string[] = []; + const logs: string[] = []; + const execute = createAcpxEngineExecutor({ + stagingLocks, warmHandles: new Map(), stagedRuntimes: new Map(), + prepareRemoteManagedHome: async (input) => ({ + stagedRuntime: await input.stage([]), + teardown: async () => { order.push("restore"); return { ok: true }; }, + }), + createRuntime: () => ({ ensureSession: async () => okHandle, startTurn: () => throwingTurn(), + close: async () => { order.push("close"); } }) as never, + }); + const result = await execute({ runId: "instruction-collection-reject", + ...remoteArgs(stateDir, localCwd, executionTarget, { + onProviderStopped: async () => { order.push("collect"); throw new Error("collector failed reading /private/test-instructions/AGENTS.md"); }, + onLog: async (_stream: string, text: string) => { logs.push(text); }, + }), + } as never); + expect(result.exitCode).toBe(1); + expect(order).toEqual(["close", "collect", "restore"]); + expect(anyStopped(paperclipStops)).toBe(true); + expect(anyStopped(processStops)).toBe(true); + expect(stagingLocks.size).toBe(0); + expect(logs.some(text => text.includes('teardown step "instruction-collection" failed: Instruction collection failed'))).toBe(true); + expect(logs.some(text => text.includes("/private/test-instructions"))).toBe(false); + }); + it("test_staging_lease_releases_in_finally_on_every_exit_path", async () => { const scenarios: Array<{ name: string; diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts index cacae0af7e4..a3f1f7b3841 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.ts @@ -3600,12 +3600,13 @@ async function closeWarmHandle(input: { input.handles.delete(input.key); } clearWarmHandleTimer(input.entry); - await input.entry.runtime.close({ + const stopped = await input.entry.runtime.close({ handle: input.entry.handle, reason: input.reason, discardPersistentState: input.discardPersistentState ?? false, - }).catch(() => {}); + }).then(() => true, () => false); flushChildStderr(input.entry.childStderrState); + return stopped; } function warmHandleMatches( @@ -5289,7 +5290,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { ) { // A matching warm entry closes through the warm store, which also // clears its idle timer and flushes its child stderr. - await closeWarmHandle({ + runtimeStopConfirmed = await closeWarmHandle({ handles: warmHandles, key: prepared.sessionKey, entry: existing, @@ -5335,12 +5336,23 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { // runs, so the host mints a `traceparent` for the provider spans, and the // per-task restore spans parent to `sandbox.syncBack`. syncBack: () => timedPhase("sync_back", async () => { - await runRuntimeSpan("sandbox.syncBack", async () => { - const restoreOutcome = await syncBackManagedHome(prepared); - if (!restoreOutcome.ok) { - workspaceRestoreFailureField = { workspaceRestoreFailure: restoreOutcome.code }; - } - }); + // A transport error or terminal narrative cannot authorize collecting + // mutable provider files. Require the owned close or local OS handle. + const stopped = runtimeStopConfirmed || (!prepared.processSessionBridge && capturedProcessExited(processIdentitySink?.localProcess)); + try { + if (stopped) await ctx.onProviderStopped?.(); + } catch { + // Match ACP's fail-soft teardown policy without describing this as + // a workspace restore failure or exposing paths from a raw error. + await recordTeardownError("instruction-collection", new Error("Instruction collection failed after provider stop. No instruction save is claimed.")); + } finally { + await runRuntimeSpan("sandbox.syncBack", async () => { + const restoreOutcome = await syncBackManagedHome(prepared); + if (!restoreOutcome.ok) { + workspaceRestoreFailureField = { workspaceRestoreFailure: restoreOutcome.code }; + } + }); + } }), // The staging lease releases as the run's final act, AFTER the coordinator // reproduces the result, in the run root `finally` below. This step stays a diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index 0735cb51056..54b055bac6d 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -280,6 +280,9 @@ export interface AdapterExecutionTargetProcessOptions { onLog: (stream: "stdout" | "stderr", chunk: string) => Promise; onRuntimeProgress?: RuntimeStatusSink; onSpawn?: (meta: { pid: number; processGroupId: number | null; startedAt: string }) => Promise; + /** Trusted invocation observation, not a turn completion callback. Called only + * after local child close or a remotely observed exit, including nonzero exits. */ + onProcessStopped?: () => void; terminalResultCleanup?: TerminalResultCleanupOptions; /** * Sandbox-only: factory from the Paperclip bridge handle that streams the @@ -894,6 +897,7 @@ export async function runAdapterExecutionTargetProcess( // after the clean process completion cannot latch a false mid-run loss. A // control channel that died before this clean completion still fails the // run closed. + if (!result.timedOut && typeof result.exitCode === "number" && Number.isInteger(result.exitCode) && result.exitCode >= 0) options.onProcessStopped?.(); const settled = applyRunDispositionSeam(result, options.settleRunDisposition); if (runLogTail) { await runLogTail.finish({ stdout: result.stdout, stderr: result.stderr }); @@ -912,7 +916,7 @@ export async function runAdapterExecutionTargetProcess( ? sanitizeRemoteExecutionEnv(options.env) : options.env; - return await runChildProcess(runId, command, args, { + const result = await runChildProcess(runId, command, args, { cwd: options.cwd, env, stdin: options.stdin, @@ -924,6 +928,13 @@ export async function runAdapterExecutionTargetProcess( localProcessSandbox: target?.kind === "local" || !target ? options.localProcessSandbox : null, remoteExecution: adapterExecutionTargetToRemoteSpec(target), }); + // Closing an SSH client on timeout/disconnect does not prove the remote + // provider exited. SSH status 255 is transport failure, never a stop receipt. + if (!target || target.kind === "local" || + (!result.timedOut && !result.signal && result.exitCode !== null && result.exitCode >= 0 && result.exitCode < 255)) { + options.onProcessStopped?.(); + } + return result; } export async function runAdapterExecutionTargetShellCommand( diff --git a/packages/adapter-utils/src/provider-stopped-boundary.test.ts b/packages/adapter-utils/src/provider-stopped-boundary.test.ts new file mode 100644 index 00000000000..6fabb28aa8d --- /dev/null +++ b/packages/adapter-utils/src/provider-stopped-boundary.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it, vi, afterEach } from "vitest"; +import * as serverUtils from "./server-utils.js"; +import { runAdapterExecutionTargetProcess } from "./execution-target.js"; +import { createProviderStoppedBoundary } from "./provider-stopped-boundary.js"; + +const result = { exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "", pid: 12, startedAt: "now" }; +const options = (onProcessStopped: () => void) => ({ cwd: "/tmp", env: {}, timeoutSec: 1, graceSec: 1, onLog: async () => {}, onProcessStopped }); +const target = (execute: () => Promise) => ({ kind: "remote", transport: "sandbox", remoteCwd: "/workspace", runner: { execute } }) as any; +afterEach(() => vi.restoreAllMocks()); +describe("owned provider process stop boundary", () => { + it.each([0, 1])("notifies after a remote invocation returns an observed exit code %s", async exitCode => { + const stopped = vi.fn(); + await runAdapterExecutionTargetProcess("run", target(async () => ({ ...result, exitCode })), "provider", [], options(stopped)); + expect(stopped).toHaveBeenCalledOnce(); + }); + it("notifies after the local child closed on timeout", async () => { + vi.spyOn(serverUtils, "runChildProcess").mockResolvedValue({ ...result, exitCode: null, signal: "SIGTERM", timedOut: true }); + const stopped = vi.fn(); + await runAdapterExecutionTargetProcess("run", null, "provider", [], options(stopped)); + expect(stopped).toHaveBeenCalledOnce(); + }); + it.each([ + { ...result, exitCode: null, timedOut: true }, + { ...result, exitCode: null, timedOut: false }, + ])("does not treat an incomplete remote execution as a stop receipt", async incomplete => { + const stopped = vi.fn(); + await runAdapterExecutionTargetProcess("run", target(async () => incomplete), "provider", [], options(stopped)); + expect(stopped).not.toHaveBeenCalled(); + }); + it("does not infer remote termination from a transport rejection", async () => { + const stopped = vi.fn(); + await expect(runAdapterExecutionTargetProcess("run", target(async () => { throw new Error("transport lost"); }), "provider", [], options(stopped))).rejects.toThrow("transport lost"); + expect(stopped).not.toHaveBeenCalled(); + }); +}); + +describe("final invocation instruction collection fence", () => { + it("collects once, after the last completed attempt, before restore", async () => { + const order: string[] = []; + const fence = createProviderStoppedBoundary(async () => { order.push("collect"); }); + fence.beginInvocation()(); + expect(order).toEqual([]); + fence.beginInvocation()(); + await fence.collectBeforeRestore(); + order.push("restore"); + await fence.collectBeforeRestore(); + expect(order).toEqual(["collect", "restore"]); + }); + it("an uncertain later attempt invalidates an earlier stop, including late callbacks", async () => { + const collect = vi.fn(async () => {}); + const fence = createProviderStoppedBoundary(collect); + const old = fence.beginInvocation(); old(); + fence.beginInvocation(); old(); + await fence.collectBeforeRestore(); + expect(collect).not.toHaveBeenCalled(); + }); + it("does not collect before any provider invocation", async () => { + const collect = vi.fn(async () => {}); + await createProviderStoppedBoundary(collect).collectBeforeRestore(); + expect(collect).not.toHaveBeenCalled(); + }); + it("does not infer SSH provider termination from transport exit 255", async () => { + vi.spyOn(serverUtils, "runChildProcess").mockResolvedValue({ ...result, exitCode: 255 }); + const stopped = vi.fn(); + await runAdapterExecutionTargetProcess("run", { kind: "remote", transport: "ssh", spec: { host: "fixture" }, remoteCwd: "/workspace" } as any, "provider", [], options(stopped)); + expect(stopped).not.toHaveBeenCalled(); + }); + it("retains the stop observation when a subsequent log-tail flush throws", async () => { + const stopped = vi.fn(); + await expect(runAdapterExecutionTargetProcess("run", target(async () => result), "provider", [], { + ...options(stopped), runLogTail: { create: () => ({ wrapCommand: (command: string, args: string[]) => ({ command, args }), start: () => {}, finish: async () => { throw new Error("log flush failed"); }, abort: async () => {} }) } as any, + })).rejects.toThrow("log flush failed"); + expect(stopped).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/adapter-utils/src/provider-stopped-boundary.ts b/packages/adapter-utils/src/provider-stopped-boundary.ts new file mode 100644 index 00000000000..be2e9101214 --- /dev/null +++ b/packages/adapter-utils/src/provider-stopped-boundary.ts @@ -0,0 +1,19 @@ +/** Per-adapter invocation fence. A failed later attempt invalidates an earlier + * stop receipt; a late callback from that earlier attempt cannot restore it. */ +export function createProviderStoppedBoundary(onProviderStopped?: () => Promise) { + let invocation = 0; + let stopped = false; + let collected = false; + return { + beginInvocation(): () => void { + const current = ++invocation; + stopped = false; + return () => { if (invocation === current) stopped = true; }; + }, + async collectBeforeRestore() { + if (!stopped || collected || !onProviderStopped) return; + collected = true; + await onProviderStopped(); + }, + }; +} diff --git a/packages/adapter-utils/src/types.ts b/packages/adapter-utils/src/types.ts index 541f7a6b683..50b3653c24b 100644 --- a/packages/adapter-utils/src/types.ts +++ b/packages/adapter-utils/src/types.ts @@ -202,6 +202,9 @@ export interface AdapterExecutionContext { /** Host-owned stop of this run's sandbox during setup or direct CLI execution. Resolves only after * provider termination is verified; never accepts an agent-selected lease. */ stopRemoteStartup?: () => Promise; + /** Host-owned collection after the final provider invocation is confirmed stopped, + * before remote workspace restore or disposal. Never call on an unverified timeout. */ + onProviderStopped?: () => Promise; /** Server-owned, actor-attributed snapshot also rendered by legacy wake prompts. */ executionContinuation?: ExecutionContinuationEnvelope | null; runId: string; diff --git a/packages/adapters/claude-local/src/server/execute.ts b/packages/adapters/claude-local/src/server/execute.ts index 8d8291fad6d..b573f3f7a9f 100644 --- a/packages/adapters/claude-local/src/server/execute.ts +++ b/packages/adapters/claude-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -397,6 +398,7 @@ export async function runClaudeLogin(input: { } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const engineSelection = await resolveClaudeExecutionEngineForRun(ctx); if (engineSelection.unavailableReason) { return { @@ -961,6 +963,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise ); } - async function runTeardown(input: { sandboxAuth: string; hostAuth: string }) { + async function runTeardown(input: { sandboxAuth: string; hostAuth: string; onProviderStopped?: () => Promise }) { const rootDir = await mkdtemp( path.join(os.tmpdir(), "paperclip-codex-copyback-e2e-"), ); @@ -138,6 +138,7 @@ describe("codex execute — outbound auth copy-back restore contribution", () => const executionResult = await execute({ runId: "run-copyback-e2e", + onProviderStopped: input.onProviderStopped, agent: { id: "agent-1", companyId: "company-1", @@ -181,6 +182,41 @@ describe("codex execute — outbound auth copy-back restore contribution", () => }; } + it("collects stopped-provider instruction edits before a throwing remote restore", async () => { + const order: string[] = []; + prepareAdapterExecutionTargetRuntime.mockImplementationOnce(async () => ({ + target: { kind: "remote", transport: "ssh" }, workspaceRemoteDir: "/remote/workspace", + runtimeRootDir: REMOTE_RUNTIME_ROOT, assetDirs: { home: `${REMOTE_RUNTIME_ROOT}/home` }, + restoreWorkspace: async () => { order.push("restore"); throw new Error("restore failed"); }, + })); + await expect(runTeardown({ sandboxAuth: "{}", hostAuth: "{}", onProviderStopped: async () => { order.push("collect"); } })).rejects.toThrow("restore failed"); + expect(order).toEqual(["collect", "restore"]); + }); + + it("collects after a failed provider exit before restoring its workspace", async () => { + runChildProcess.mockResolvedValueOnce({ exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "provider failed", pid: 321, startedAt: new Date().toISOString() }); + const collected = vi.fn(async () => {}); + await runTeardown({ sandboxAuth: "{}", hostAuth: "{}", onProviderStopped: collected }); + expect(collected).toHaveBeenCalledOnce(); + }); + + it("stops the bridge and restores the workspace when instruction collection rejects", async () => { + const order: string[] = []; + startAdapterExecutionTargetPaperclipBridge.mockResolvedValueOnce({ + env: {}, stop: async () => { order.push("bridge-stop"); }, + } as never); + prepareAdapterExecutionTargetRuntime.mockImplementationOnce(async () => ({ + target: { kind: "remote", transport: "ssh" }, workspaceRemoteDir: "/remote/workspace", + runtimeRootDir: REMOTE_RUNTIME_ROOT, assetDirs: { home: `${REMOTE_RUNTIME_ROOT}/home` }, + restoreWorkspace: async () => { order.push("restore"); }, + })); + await expect(runTeardown({ sandboxAuth: "{}", hostAuth: "{}", onProviderStopped: async () => { + order.push("collect"); + throw new Error("instruction collection failed"); + } })).rejects.toThrow("instruction collection failed"); + expect(order).toEqual(["collect", "bridge-stop", "restore"]); + }); + it("declares a Codex `home` asset carrying both inbound provision and outbound restore contributions", async () => { await runTeardown({ sandboxAuth: subscriptionAuth({ accountId: "acct", lastRefresh: "2026-07-09T01:00:00Z", marker: "s" }), diff --git a/packages/adapters/codex-local/src/server/execute.ts b/packages/adapters/codex-local/src/server/execute.ts index 8e8e4954e82..b32c3e11a93 100644 --- a/packages/adapters/codex-local/src/server/execute.ts +++ b/packages/adapters/codex-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -567,6 +568,7 @@ export async function ensureCodexSkillsInjected( } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const engineSelection = await resolveCodexExecutionEngineForRun(ctx); if (engineSelection.unavailableReason) { return { @@ -1321,6 +1323,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise undefined); - // A provider failure remains the primary outcome. When provider work - // succeeded, however, silently accepting a failed copy-back can lose - // the only workspace edits before a replacement sandbox starts. - if (executionError === null) throw error; + try { + await providerStop.collectBeforeRestore(); + } finally { + if (paperclipBridge) { + await paperclipBridge.stop(); + } + if (restoreRemoteWorkspace) { + try { + await onLog( + "stdout", + `[paperclip] Restoring workspace changes from ${describeAdapterExecutionTarget(executionTarget)}.\n`, + ); + await restoreRemoteWorkspace(); + } catch (error) { + await Promise.resolve( + onLog( + "stderr", + `[paperclip] Failed to restore workspace changes from ${describeAdapterExecutionTarget( + executionTarget, + )}: ${error instanceof Error ? error.message : String(error)}\n`, + ), + ).catch(() => undefined); + // A provider failure remains the primary outcome. When provider work + // succeeded, however, silently accepting a failed copy-back can lose + // the only workspace edits before a replacement sandbox starts. + if (executionError === null) throw error; + } } } } diff --git a/packages/adapters/cursor-local/src/server/execute.test.ts b/packages/adapters/cursor-local/src/server/execute.test.ts index d0d8ce4b327..a87d777bcad 100644 --- a/packages/adapters/cursor-local/src/server/execute.test.ts +++ b/packages/adapters/cursor-local/src/server/execute.test.ts @@ -271,21 +271,11 @@ printf '%s\\n' '{"type":"result","subtype":"success","session_id":"cursor-sessio const runner = { execute: async (input: { command: string; args?: string[]; env?: Record }) => { runnerState.commands.push(input.command); - if (input.command === "sh") { - return { - exitCode: 0, - signal: null, - timedOut: false, - stdout: "", - stderr: "", - pid: 555, - startedAt: new Date().toISOString(), - }; - } - + // Exercise actual bounded file reads during managed-home restoration; + // reporting empty success for every shell command hides missing bytes. return runChildProcess(`cursor-fresh-lease-${runnerState.commands.length}`, input.command, input.args ?? [], { cwd: remoteWorkspace, - env: input.env ?? {}, + env: { ...input.env, PATH: `${input.env?.PATH ?? ""}:/usr/bin:/bin` }, timeoutSec: 30, graceSec: 5, onLog: async () => {}, diff --git a/packages/adapters/cursor-local/src/server/execute.ts b/packages/adapters/cursor-local/src/server/execute.ts index 872d3779c75..99094605315 100644 --- a/packages/adapters/cursor-local/src/server/execute.ts +++ b/packages/adapters/cursor-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -199,6 +200,7 @@ export async function ensureCursorSkillsInjected( } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx; const executionTarget = readAdapterExecutionTarget({ executionTarget: ctx.executionTarget, @@ -655,6 +657,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise undefined); + try { + await providerStop.collectBeforeRestore(); + } finally { + if (paperclipBridge) { + await paperclipBridge.stop(); + } + if (restoreRemoteWorkspace) { + await onLog( + "stdout", + `[paperclip] Restoring workspace changes from ${describeAdapterExecutionTarget(executionTarget)}.\n`, + ); + await restoreRemoteWorkspace(); + } + if (localSkillsDir) { + await fs.rm(localSkillsDir, { recursive: true, force: true }).catch(() => undefined); + } } } } diff --git a/packages/adapters/gemini-local/src/server/execute.ts b/packages/adapters/gemini-local/src/server/execute.ts index 901fa10c1a4..1f133c822ee 100644 --- a/packages/adapters/gemini-local/src/server/execute.ts +++ b/packages/adapters/gemini-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import type { Dirent } from "node:fs"; import os from "node:os"; @@ -206,6 +207,7 @@ async function buildGeminiSkillsDir( } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const engineSelection = await resolveGeminiExecutionEngineForRun(ctx); if (engineSelection.unavailableReason) { return { @@ -638,6 +640,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise undefined) : Promise.resolve(), - ]); + try { + await providerStop.collectBeforeRestore(); + } finally { + await Promise.all([ + paperclipBridge?.stop(), + restoreRemoteWorkspace?.(), + localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(), + ]); + } } } diff --git a/packages/adapters/grok-local/src/server/execute.test.ts b/packages/adapters/grok-local/src/server/execute.test.ts index f3552bc06f6..1553e7aa8a4 100644 --- a/packages/adapters/grok-local/src/server/execute.test.ts +++ b/packages/adapters/grok-local/src/server/execute.test.ts @@ -847,6 +847,69 @@ describe("grok_local execute", () => { expect(await pathExists(stagedDir)).toBe(false); }); + it("keeps collection failure separate from a successful workspace restore", async () => { + delete process.env.XAI_API_KEY; + mocks.state.isRemote = true; + await seedHostGrokAuth("{}"); + const collectionError = new Error("instruction collection failed"); + const order: string[] = []; + let stagedDir = ""; + runProcessMock.mockImplementation(async (_run, _target, _command, _args, options) => { + options.onProcessStopped(); + return makeSuccessfulRunResult(); + }); + prepareRuntimeMock.mockImplementationOnce(async (input: { assets?: Array<{ localDir: string }> }) => { + stagedDir = input.assets?.[0]?.localDir ?? ""; + return { + workspaceRemoteDir: "/remote/workspace", + assetDirs: { home: "/remote/workspace/.paperclip-runtime/grok/home" }, + restoreWorkspace: async () => { order.push("restore"); }, + }; + }); + const ctx = await makeCtx("run-collection-reject", await makeTempRoot()); + ctx.onProviderStopped = async () => { order.push("collect"); throw collectionError; }; + const result = await execute(ctx); + expect(result.errorCode).toBe("instruction_collection_failed"); + expect(result.resultJson?.instructionCollectionFailure).toBe("collection_failed"); + expect(result.resultJson?.workspaceRestoreFailure).toBeUndefined(); + expect(order).toEqual(["collect", "restore"]); + expect(stagedDir).not.toBe(""); + expect(await pathExists(stagedDir)).toBe(false); + }); + + it.each([0, 2])("preserves provider output when collection and restore both fail after exit %s", async (exitCode) => { + delete process.env.XAI_API_KEY; + mocks.state.isRemote = true; + await seedHostGrokAuth("{}"); + runProcessMock.mockImplementation(async (_run, _target, _command, _args, options) => { + options.onProcessStopped(); + return { + ...makeSuccessfulRunResult(), exitCode, + stderr: exitCode ? "Model request failed." : "", + stdout: [JSON.stringify({ type: "text", data: "Saved output." }), JSON.stringify({ + type: "end", sessionId: "sess-1", requestId: "req-1", stopReason: "EndTurn", + usage: { input_tokens: 4, output_tokens: 9 }, + })].join("\n"), + }; + }); + prepareRuntimeMock.mockImplementationOnce(async () => ({ + workspaceRemoteDir: "/remote/workspace", + assetDirs: { home: "/remote/workspace/.paperclip-runtime/grok/home" }, + restoreWorkspace: async () => { throw new Error("restore failed"); }, + })); + const ctx = await makeCtx("run-collection-and-restore-reject", await makeTempRoot()); + ctx.onProviderStopped = async () => { throw new Error("instruction collection failed"); }; + const result = await execute(ctx); + expect(result).toMatchObject({ + errorCode: "workspace_restore_failed", exitCode, sessionId: "sess-1", summary: "Saved output.", + usage: { inputTokens: 4, outputTokens: 9 }, + resultJson: { instructionCollectionFailure: "collection_failed", workspaceRestoreFailure: "restore_failed", + requestId: "req-1", finalResponseRecorded: true, executionBeforeRestore: { exitCode } }, + }); + expect(result.errorMessage).toContain("Instruction collection failed"); + if (exitCode) expect(result.errorMessage).toContain("Model request failed."); + }); + it.each(["completed", "failed", "timed_out"])("preserves %s output and removes the staged home when restore fails", async (state) => { delete process.env.XAI_API_KEY; mocks.state.isRemote = true; diff --git a/packages/adapters/grok-local/src/server/execute.ts b/packages/adapters/grok-local/src/server/execute.ts index 7fe54948066..fab47a1fb6e 100644 --- a/packages/adapters/grok-local/src/server/execute.ts +++ b/packages/adapters/grok-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import { withWorkspaceRestore } from "@paperclipai/adapter-utils/workspace-restore-result"; import { cancellableSandboxStartup } from "@paperclipai/adapter-utils/acpx-engine/startup-cancellation"; import fs from "node:fs/promises"; @@ -246,6 +247,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx; const executionTarget = readAdapterExecutionTarget({ executionTarget: ctx.executionTarget, @@ -616,6 +618,7 @@ async function executeTurn(ctx: AdapterExecutionContext): Promise { await restoreRemoteWorkspace?.(); }); + return await withWorkspaceRestore( + async () => { + let result: AdapterExecutionResult; + let collectionFailed = false; + const collectionFailureMessage = "Instruction collection failed after provider stop. No instruction save is claimed."; + try { + result = await executeTurn(); + } finally { + try { + await providerStop.collectBeforeRestore(); + } catch { + collectionFailed = true; + await onLog("stderr", `[paperclip] ${collectionFailureMessage}\n`).catch(() => undefined); + } + } + if (!collectionFailed) return result; + const providerFailed = result.timedOut || result.signal || result.errorCode + || (result.exitCode !== null && result.exitCode !== 0); + return { + ...result, + ...(!providerFailed ? { errorCode: "instruction_collection_failed" } : {}), + errorMessage: [result.errorMessage, collectionFailureMessage].filter(Boolean).join(" "), + resultJson: { ...result.resultJson, instructionCollectionFailure: "collection_failed" }, + }; + }, + async () => { await restoreRemoteWorkspace?.(); }, + ); } finally { // Cleanup runs after settlement on both success and failure. if (stagedGrokHomeDir) { diff --git a/packages/adapters/kimi-local/src/server/execute.ts b/packages/adapters/kimi-local/src/server/execute.ts index 732f4ca0a2c..3dafa56c897 100644 --- a/packages/adapters/kimi-local/src/server/execute.ts +++ b/packages/adapters/kimi-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -186,6 +187,7 @@ async function buildKimiSkillsDir( } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const engineSelection = await resolveKimiExecutionEngineForRun(ctx); if (engineSelection.unavailableReason) { return { @@ -605,6 +607,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise undefined) : Promise.resolve(), - ]); + try { + await providerStop.collectBeforeRestore(); + } finally { + await Promise.all([ + paperclipBridge?.stop(), + restoreRemoteWorkspace?.(), + localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(), + ]); + } } } diff --git a/packages/adapters/opencode-local/src/server/execute.ts b/packages/adapters/opencode-local/src/server/execute.ts index 7ce3ab0b364..6d5683612f6 100644 --- a/packages/adapters/opencode-local/src/server/execute.ts +++ b/packages/adapters/opencode-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -222,6 +223,7 @@ async function buildOpenCodeSkillsDir(config: Record): Promise< } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx; const executionTarget = readAdapterExecutionTarget({ executionTarget: ctx.executionTarget, @@ -641,6 +643,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise undefined) : Promise.resolve(), - ]); + try { + await providerStop.collectBeforeRestore(); + } finally { + await Promise.all([ + paperclipBridge?.stop(), + restoreRemoteWorkspace?.(), + localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(), + ]); + } } } finally { await preparedRuntimeConfig.cleanup(); diff --git a/packages/adapters/pi-local/src/server/execute.ts b/packages/adapters/pi-local/src/server/execute.ts index 54f3fede440..b38a737aa00 100644 --- a/packages/adapters/pi-local/src/server/execute.ts +++ b/packages/adapters/pi-local/src/server/execute.ts @@ -1,3 +1,4 @@ +import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -221,6 +222,7 @@ async function readSavedSessionCwd(input: { } export async function execute(ctx: AdapterExecutionContext): Promise { + const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped); const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx; const executionTarget = readAdapterExecutionTarget({ executionTarget: ctx.executionTarget, @@ -733,6 +735,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise undefined) : Promise.resolve(), - ]); + try { + await providerStop.collectBeforeRestore(); + } finally { + await Promise.all([ + paperclipBridge?.stop(), + restoreRemoteWorkspace?.(), + localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(), + ]); + } } } finally { await preparedRuntimeConfig.cleanup();