From 40bb466d787821e41d72f9d5159591c1346ed2cc Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:38:26 -0500 Subject: [PATCH 1/9] fix(ui): align chat connection and recovery cards (#15771) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task pages show external chat connections and recovery notices. > - These cards use different widths, colors, and spacing. > - The difference makes related task information harder to scan. > - This pull request gives these cards one shared surface. > - The benefit is a consistent task page for chat and email users. ## Linked Issues or Issue Description **What happened?** The external chat banner and recovery notice have different backgrounds, padding, and widths. The first banner needs more space above it. **Expected behavior** Connection, recovery, workspace repair, and task email cards use the same surface. The chat cards have the same width. **Steps to reproduce** Open a task with an external Slack conversation and a recovery notice. Compare the two cards. Open the Tasks / Context notices story to compare the updated cards with an AgentMail email card. ## What Changed - Add a shared token-based surface for task context cards. - Put chat recovery notices in the same width container as the connection banner. - Add space above the connection banner. - Apply the surface to task email cards and workspace export repair. - Add a Storybook view with per-card width, color, padding, and corner checks. - Give the workspace recovery card its own React key to prevent duplicate connection banners. ## Verification - Passed `pnpm check:token-gates`. - Passed 57 tests for ExecutionBlockerNotice, WorkspaceExportRecovery, and the external chat banner. - Passed UI typecheck and UI production build. - Captured desktop and mobile browser screenshots from the real components with fixture data. The three cards have equal widths, backgrounds, padding, and corners. - Full local typecheck needs Cargo, which is absent in the task environment. Full tests and build could not complete within the environment memory limit. Remote typecheck, build, all test shards, and security checks pass on commit e225a8e47. The Canary Dry Run also passes. Storybook visual/deploy jobs are skipped by workflow policy. ## Risks - Low risk. Recovery notices move outside the chat panel. Their actions and API calls stay the same. - Verify narrow screens and both task layout modes. ## Model Used - OpenAI GPT-6 through Codex. Tool use and code execution. The runtime does not expose an exact model variant or context window size. ## 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 --- ui/src/components/EmailMessageCard.tsx | 4 +- ui/src/components/EmailTaskActivity.tsx | 3 +- .../ExecutionBlockerNotice.test.tsx | 3 +- ui/src/components/ExecutionBlockerNotice.tsx | 6 +- ui/src/components/WorkspaceExportRecovery.tsx | 6 +- .../chat/ExternallyConnectedTaskBanner.tsx | 5 +- ui/src/index.css | 12 ++-- ui/src/pages/IssueDetail.tsx | 15 ++-- .../stories/task-context-notices.stories.tsx | 68 +++++++++++++++++++ 9 files changed, 103 insertions(+), 19 deletions(-) create mode 100644 ui/storybook/stories/task-context-notices.stories.tsx diff --git a/ui/src/components/EmailMessageCard.tsx b/ui/src/components/EmailMessageCard.tsx index be4a083e15f..b1c374e1ac4 100644 --- a/ui/src/components/EmailMessageCard.tsx +++ b/ui/src/components/EmailMessageCard.tsx @@ -42,7 +42,9 @@ export function EmailMessageCard({ message, publication, issueId, + contextNotice = false, }: { + contextNotice?: boolean; message: EmailMessage; publication?: EmailPublicationSummary; issueId: string; @@ -57,7 +59,7 @@ export function EmailMessageCard({ aria-label={ message.direction === "inbound" ? "Email received" : "Email sent" } - className="space-y-4 rounded-xl border border-border bg-card p-5" + className={contextNotice ? "task-context-notice space-y-3" : "space-y-4 rounded-xl border border-border bg-card p-5"} >
diff --git a/ui/src/components/EmailTaskActivity.tsx b/ui/src/components/EmailTaskActivity.tsx index 6f442b1372c..6a384fb1d0e 100644 --- a/ui/src/components/EmailTaskActivity.tsx +++ b/ui/src/components/EmailTaskActivity.tsx @@ -36,6 +36,7 @@ export function EmailTaskActivity({ )} {messages.map((m) => (

{p.request.subject ?? "Email reply"}

{p.request.to &&

To: {p.request.to.join(", ")}

} diff --git a/ui/src/components/ExecutionBlockerNotice.test.tsx b/ui/src/components/ExecutionBlockerNotice.test.tsx index 3960f71070b..980f0a6fdf1 100644 --- a/ui/src/components/ExecutionBlockerNotice.test.tsx +++ b/ui/src/components/ExecutionBlockerNotice.test.tsx @@ -36,8 +36,7 @@ describe("stopped task recovery notice", () => { const notice = container.querySelector('[role="status"][aria-label="Task recovery"]')!; expect(notice.textContent).toContain("Recorded work is preserved"); expect(notice.textContent).toContain("Retry"); - expect(notice.classList.contains("border")).toBe(true); - expect(notice.classList.contains("bg-muted")).toBe(true); + expect(notice.classList.contains("task-context-notice")).toBe(true); expect(notice.querySelector("a")?.getAttribute("href")).toBe("/agents/agent/runs/failed-run"); }); it.each([false, true])("explains cancelled runs and saved input; continue eligibility %s", async canContinue => { diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsx index c157a359b5d..0cb1eb0b775 100644 --- a/ui/src/components/ExecutionBlockerNotice.tsx +++ b/ui/src/components/ExecutionBlockerNotice.tsx @@ -4,9 +4,11 @@ import { agentsApi } from "../api/agents"; import { activityApi } from "../api/activity"; import { queryKeys } from "../lib/queryKeys"; import { Button } from "./ui/button"; +import { cn } from "../lib/utils"; import { Link } from "../lib/router"; -export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried }: { +export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried, className }: { + className?: string; companyId: string; issueId: string; blocker: ExecutionBlocker; @@ -33,7 +35,7 @@ export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried }, }); return ( -
+

{modelRejected ? "Model unavailable." : "Recovery needed."}{blocker.runError ? ` ${blocker.runError}` : ""}

{modelRejected &&

Choose a supported model or clear the task's model override, then retry.

} diff --git a/ui/src/components/WorkspaceExportRecovery.tsx b/ui/src/components/WorkspaceExportRecovery.tsx index 23ae74319b1..98376816817 100644 --- a/ui/src/components/WorkspaceExportRecovery.tsx +++ b/ui/src/components/WorkspaceExportRecovery.tsx @@ -3,12 +3,14 @@ import { useMutation } from "@tanstack/react-query"; import type { IssueRecoveryAction } from "@paperclipai/shared"; import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared"; import { issuesApi } from "../api/issues"; +import { cn } from "../lib/utils"; import { Button } from "./ui/button"; import { Label } from "./ui/label"; import { Textarea } from "./ui/textarea"; /** Copyback repair preserves the accepted result and never wakes the provider. */ -export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued }: { +export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued, className }: { + className?: string; issueId: string; action: IssueRecoveryAction | null; canManage: boolean; onQueued: () => void; }) { const noteId = useId(); @@ -23,7 +25,7 @@ export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued } if (!action || !isNativeWorkspaceExportRepairCause(action.cause) || action.ownerType !== "board" || !["active", "escalated"].includes(action.status) || typeof action.evidence.runId !== "string") return null; const queued = queuedActionVersion === String(action.updatedAt) || action.wakePolicy?.kind === "resume_native_run"; - return
+ return

Workspace export needs repair

{queued ?

Export is queued for the saved result. The agent will not repeat its work.

: <>

{"Automatic workspace export retries stopped. Inspect the export failure, restore provider or destination availability, and preserve the saved files in the retained sandbox. Retry export here when the cause is resolved."}

diff --git a/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx b/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx index 221f28c14aa..bb92647d243 100644 --- a/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx +++ b/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx @@ -17,6 +17,7 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Textarea } from "@/components/ui/textarea"; import { useToast } from "@/context/ToastContext"; import { Link } from "@/lib/router"; +import { cn } from "@/lib/utils"; import { queryKeys } from "@/lib/queryKeys"; import { useChatConnectorsEnabled, chatProviderVisible } from "@/hooks/useChatConnectorsEnabled"; import { issuesApi } from "@/api/issues"; @@ -124,6 +125,7 @@ export function useIssueChatBinding(companyId: string, issueId: string) { } type ConnectedTaskProps = { + className?: string; attachments?: IssueAttachment[]; companyId: string; issueId: string; @@ -148,6 +150,7 @@ export function ExternallyConnectedTaskBanner(props: ConnectedTaskProps) { } function ConnectedTaskComposer({ + className, attachments = [], companyId, issueId, @@ -486,7 +489,7 @@ function ConnectedTaskComposer({ return (
diff --git a/ui/src/index.css b/ui/src/index.css index c45d030ffc3..ce91a3a3dba 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -3120,11 +3120,13 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] { inset-inline: 0; } -/* Task recovery panel uses the shared spacing, radius, and type scales. */ -.execution-blocker-notice { - gap: calc(var(--spacing) * 2); - padding: calc(var(--spacing) * 2) calc(var(--spacing) * 3); - border-radius: var(--radius-md); +/* Connection and recovery cards share one surface and spacing scale. */ +.task-context-notice { + padding: calc(var(--spacing) * 3); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background-color: var(--muted); + color: var(--foreground); font-size: var(--text-sm); line-height: var(--text-sm--line-height); } diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index a7b7ff66094..b7ebb693a9a 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -7642,6 +7642,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS {taskChatShellEnabled ? null : createdFromNote} + {resolvedDetailTab === "chat" && ( + + )} + {resolvedDetailTab === "chat" && issue.executionBlocker && ( + + )} + {issue.status === "in_review" && issue.externalConversationState === "waiting" && (

Reply sent. Send a message to continue.

)} @@ -7952,11 +7962,6 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS : undefined } > - - {issue.executionBlocker && ( - - )} {resolvedDetailTab === "chat" ? ( { invalidateIssueDetail(); invalidateIssueCollections(); }} unavailableReason={!canManageBoardRuntime || !canResolveBoardRecoveryAction ? "You don’t have permission to repair this task’s workspace." diff --git a/ui/storybook/stories/task-context-notices.stories.tsx b/ui/storybook/stories/task-context-notices.stories.tsx new file mode 100644 index 00000000000..f92b8ffaaac --- /dev/null +++ b/ui/storybook/stories/task-context-notices.stories.tsx @@ -0,0 +1,68 @@ +import { useState } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { expect, within } from "storybook/test"; +import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner"; +import { ExecutionBlockerNotice } from "@/components/ExecutionBlockerNotice"; +import { EmailMessageCard } from "@/components/EmailMessageCard"; +import { queryKeys } from "@/lib/queryKeys"; + +const shellSectionClass = "mx-auto w-full max-w-(--tc-shell-max-w)"; + +function TaskContextNotices() { + const [client] = useState(() => { + const cache = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } }); + cache.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: true }); + cache.setQueryData(["issue-chat-binding", "demo", "context-notices"], { + endpointId: "slack-demo", provider: "slack", externalLabel: "#design · Card styling", + externalUrl: "https://slack.com", conversationId: "demo-thread", assignedAgentLocked: true, + }); + cache.setQueryData(queryKeys.issues.runs("context-notices"), []); + return cache; + }); + return ( + +
+
+

Chat connection and recovery

+ + {}} + blocker={{ recoveryActionId: "demo-recovery", runId: null, agentId: null, cause: "action_outcome_unknown", + nextAction: "Inspect the run before continuing. Recorded work is preserved." }} /> +
+ +
+
+
+
+ ); +} + +const meta = { + title: "Tasks/Context notices", + component: TaskContextNotices, + parameters: { layout: "fullscreen" }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const ConnectionAndRecovery: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const connection = await canvas.findByRole("region", { name: "External conversation" }); + const recovery = canvas.getByRole("status", { name: "Task recovery" }); + const email = canvas.getByRole("article", { name: "Email received" }); + for (const card of [recovery, email]) { + await expect(card.getBoundingClientRect().width).toBe(connection.getBoundingClientRect().width); + await expect(getComputedStyle(card).backgroundColor).toBe(getComputedStyle(connection).backgroundColor); + await expect(getComputedStyle(card).padding).toBe(getComputedStyle(connection).padding); + await expect(getComputedStyle(card).borderRadius).toBe(getComputedStyle(connection).borderRadius); + } + }, +}; From 28e134873ef72d06c4bbff7ac0e214baab0dcfb9 Mon Sep 17 00:00:00 2001 From: Kilian Date: Sat, 10 Oct 2026 17:46:21 +0200 Subject: [PATCH 2/9] fix(opencode-local): run in the realized workspace (#11438) 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 > - Paperclip adapters start each agent in its selected workspace > - Paperclip can realize a different workspace path for local and remote runs > - The OpenCode CLI prefers its inherited `PWD` when no `--dir` option is present > - The process `cwd` option does not update the inherited `PWD` value > - This pull request passes the realized workspace to OpenCode with `--dir` > - The benefit is that OpenCode sessions and tools use the workspace that Paperclip selected ## Linked Issues or Issue Description No matching issue exists. Refs #8287. That earlier pull request describes the realized remote workspace path. It does not make the OpenCode CLI use that path. I searched open and closed issues and pull requests for `opencode --dir`, `opencode cwd PWD`, and `opencode workspace directory`. I found no duplicate. **What happened?** Paperclip gives the OpenCode process the correct operating system `cwd`. However, the adapter does not pass OpenCode's `--dir` option. OpenCode uses `process.env.PWD` before `process.cwd()` when `--dir` is absent. A server `PWD` that differs from the realized workspace can therefore place the OpenCode session and its tools in the wrong directory. **Expected behavior** OpenCode must use the workspace that Paperclip realized for the run. An explicit `--dir` in `extraArgs` must remain valid and must not be duplicated. **Steps to reproduce** 1. Start the Paperclip server from directory A. 2. Configure an OpenCode agent with directory B, or realize directory B on a remote execution target. 3. Start a run without a manual `--dir` value in `extraArgs`. 4. Inspect the OpenCode session directory or run a directory-sensitive tool. 5. Before this change, OpenCode can use directory A from the inherited `PWD`. 6. After this change, OpenCode receives `--dir B`. **Paperclip version or commit** `b38d6ddb811b3ff3145ff5df60174eb9e7313fe6` **Deployment mode** Self-hosted server. The same adapter path is used in local development and remote execution. **Installation method** Built from source. **Agent adapter(s) involved** OpenCode. **Database mode** Not database-related. **Additional context** OpenCode v1.17.13 defines `--dir` and uses the inherited `PWD` as its fallback root. See the [OpenCode run command source](https://github.com/anomalyco/opencode/blob/10c894bdeef3618f5666fb506ef7f9491bb964d8/packages/opencode/src/cli/cmd/run.ts#L333-L339). ## What Changed - Add the realized execution workspace as `--dir` for OpenCode runs. - Preserve an explicit `--dir` or `--dir=...` value from `extraArgs`. - Stop option detection at the first `--` terminator. - Extend the remote execution tests for realized, explicit, and post-terminator directory arguments. ## Verification - `pnpm exec vitest run packages/adapters/opencode-local/src` passed: 7 files and 40 tests. - `pnpm --filter @paperclipai/adapter-opencode-local typecheck` passed. - `pnpm --filter @paperclipai/adapter-opencode-local build` passed. - `pnpm -r typecheck` passed for all 31 selected workspace projects. - `pnpm build` passed for all selected workspace projects. - `git diff --check` passed. I also ran `pnpm test:run`. It completed with 334 test files passing and 2 test files failing. It reported 3,790 passing tests and 4 skipped tests. The two failures are in `issue-monitor-scheduler.test.ts` and `workspace-runtime.test.ts`. Each failure reproduces on the unchanged base commit after this pull request is removed. Neither test imports or covers the OpenCode adapter. ## Risks - The behavior change is limited to OpenCode run arguments. - A custom old OpenCode binary that does not support `--dir` will reject the option. The current official OpenCode v1.17.13 CLI supports it. - An explicit operator `--dir` remains authoritative. The adapter does not add a duplicate option because OpenCode's parser converts repeated string options to an array. - This change does not modify schemas, migrations, APIs, telemetry, or user data. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex based on GPT-5. The runtime did not expose a more specific model ID or context-window size. The agent used high-depth reasoning, repository access, shell execution, and GitHub tools. ## 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 - [ ] 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: commitperclip-bot <305974387+commitperclip-bot@users.noreply.github.com> --- .../opencode-local/src/server/execute.remote.test.ts | 7 ++++++- packages/adapters/opencode-local/src/server/execute.ts | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/adapters/opencode-local/src/server/execute.remote.test.ts b/packages/adapters/opencode-local/src/server/execute.remote.test.ts index 7472e11ffe5..2271749e335 100644 --- a/packages/adapters/opencode-local/src/server/execute.remote.test.ts +++ b/packages/adapters/opencode-local/src/server/execute.remote.test.ts @@ -153,6 +153,7 @@ describe("opencode remote execution", () => { config: { command: "opencode", model: "opencode/gpt-5-nano", + extraArgs: ["--", "--dir"], ...(managed ? { managedAiConnection: { provider: "openrouter", method: "api_key" }, } : {}), @@ -236,6 +237,7 @@ describe("opencode remote execution", () => { `${managedRemoteWorkspace}/.paperclip-runtime/opencode/xdgConfig`, ); expect(modelProbeCall?.[3].remoteExecution?.remoteCwd).toBe("/remote/workspace"); + expect(runCall?.[2].slice(-4)).toEqual(["--dir", managedRemoteWorkspace, "--", "--dir"]); const call = runCall as | [string, string, string[], { env: Record; remoteExecution?: { remoteCwd: string } | null }] | undefined; @@ -335,7 +337,7 @@ describe("opencode remote execution", () => { expect(startAdapterExecutionTargetPaperclipBridge).not.toHaveBeenCalled(); }); - it("resumes saved OpenCode sessions for remote SSH execution only when the identity matches", async () => { + it("resumes matching remote sessions and preserves an explicit run directory", async () => { const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-remote-resume-")); cleanupDirs.push(rootDir); const workspaceDir = path.join(rootDir, "workspace"); @@ -370,6 +372,7 @@ describe("opencode remote execution", () => { config: { command: "opencode", model: "opencode/gpt-5-nano", + extraArgs: ["--dir", "/operator-supplied"], }, context: { paperclipWorkspace: { @@ -397,5 +400,7 @@ describe("opencode remote execution", () => { | undefined; expect(call?.[2]).toContain("--session"); expect(call?.[2]).toContain("session-123"); + expect(call?.[2].slice(-2)).toEqual(["--dir", "/operator-supplied"]); + expect(call?.[2].filter((arg) => arg === "--dir" || arg.startsWith("--dir="))).toHaveLength(1); }); }); diff --git a/packages/adapters/opencode-local/src/server/execute.ts b/packages/adapters/opencode-local/src/server/execute.ts index a7458fd3d97..7171067d005 100644 --- a/packages/adapters/opencode-local/src/server/execute.ts +++ b/packages/adapters/opencode-local/src/server/execute.ts @@ -621,6 +621,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise arg === "--dir" || arg.startsWith("--dir="))) { + args.push("--dir", effectiveExecutionCwd); + } if (extraArgs.length > 0) args.push(...extraArgs); return args; }; From 0e37a385e678d1a568f483c31ae1c19024d2df98 Mon Sep 17 00:00:00 2001 From: lorenzozane Date: Sat, 10 Oct 2026 23:48:00 +0800 Subject: [PATCH 3/9] fix(pi-local): avoid embedding model catalogue in errors (#13628) 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 > - The pi-local adapter discovers and validates models before it starts a local Pi process > - An unavailable-model error included model IDs from the discovered catalogue > - Repeating those IDs made persisted and rendered failures noisy and exposed substitute choices > - This pull request keeps the requested model, reports the available count, and points to the existing lookup command > - The benefit is a concise error without changing model discovery or matching ## Linked Issues or Issue Description Fixes #13612 ## What Changed - Replace model catalogue interpolation in unavailable-model errors with the requested model, normalized model count, and `pi --list-models`. - Add a regression test with 13 discovered models and exact error-message matching. ## Verification - `pnpm exec vitest run packages/adapters/pi-local/src/server/models.test.ts` - `pnpm exec vitest run packages/adapters/pi-local/src/server/*.test.ts` - `pnpm --filter @paperclipai/adapter-pi-local typecheck` - `git diff --check` All listed checks pass locally. The test suite uses a temporary Pi executable and verifies that model IDs are not appended to the error. ## Risks Low risk. Only unavailable-model error wording changes. Model discovery, matching, valid model execution, and failure handling remain unchanged. Full repository CI was not run locally because the host uses Node 22.22.1 and the repository declares Node >=24.11.0. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-5.6 Luna (`gpt-5.6-luna`); tool-assisted code execution. The context window size is not exposed in this session. ## 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) - [ ] 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 #13612) - [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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../pi-local/src/server/models.test.ts | 33 +++++++++++++++++++ .../adapters/pi-local/src/server/models.ts | 3 +- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/adapters/pi-local/src/server/models.test.ts b/packages/adapters/pi-local/src/server/models.test.ts index df777544a17..881c86defc1 100644 --- a/packages/adapters/pi-local/src/server/models.test.ts +++ b/packages/adapters/pi-local/src/server/models.test.ts @@ -1,3 +1,6 @@ +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { ensurePiModelConfiguredAndAvailable, @@ -30,4 +33,34 @@ describe("pi models", () => { }), ).rejects.toThrow(); }); + + it("does not embed the model catalogue when the configured model is unavailable", async () => { + const directory = await mkdtemp(join(tmpdir(), "paperclip-pi-models-")); + const command = join(directory, "pi"); + const modelIds = Array.from({ length: 13 }, (_, index) => `provider/model-${index}`); + await writeFile( + command, + `#!/bin/sh\nprintf 'provider model\\n';\n${modelIds + .map((id) => { + const [provider, model] = id.split("/"); + return `printf '${provider} ${model}\\n'`; + }) + .join(";\n")}\n`, + ); + await chmod(command, 0o755); + + try { + await expect( + ensurePiModelConfiguredAndAvailable({ + command, + model: "provider/missing", + }), + ).rejects.toMatchObject({ + message: + "Configured Pi model is unavailable: provider/missing. 13 models are available; list them with `pi --list-models`.", + }); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); diff --git a/packages/adapters/pi-local/src/server/models.ts b/packages/adapters/pi-local/src/server/models.ts index a6081cad738..06b1a803474 100644 --- a/packages/adapters/pi-local/src/server/models.ts +++ b/packages/adapters/pi-local/src/server/models.ts @@ -188,9 +188,8 @@ export async function ensurePiModelConfiguredAndAvailable(input: { } if (!models.some((entry) => entry.id === model)) { - const sample = models.slice(0, 12).map((entry) => entry.id).join(", "); throw new Error( - `Configured Pi model is unavailable: ${model}. Available models: ${sample}${models.length > 12 ? ", ..." : ""}`, + `Configured Pi model is unavailable: ${model}. ${models.length} models are available; list them with \`pi --list-models\`.`, ); } From b6f8c44f9f7c0fc243abe978b1168183c98852de Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 11:31:37 -0500 Subject: [PATCH 4/9] Reclaim abandoned computer home uploads from durable receipts Persist exact upload ownership before staging, renew a five-minute inactivity lease per chunk, and reclaim verified expired uploads on seed or home admission. Preserve active uploads and unrelated directories, and fence delayed writes and aborts after replacement. Co-Authored-By: Paperclip --- .../modules/computers/adapters/boat.test.ts | 50 ++++- .../computers/adapters/remote-program.ts | 171 ++++++++++++------ 2 files changed, 160 insertions(+), 61 deletions(-) diff --git a/server/src/modules/computers/adapters/boat.test.ts b/server/src/modules/computers/adapters/boat.test.ts index 00e65b5afff..9c5a82f37d8 100644 --- a/server/src/modules/computers/adapters/boat.test.ts +++ b/server/src/modules/computers/adapters/boat.test.ts @@ -180,13 +180,13 @@ describe("confined computer files", () => { const chunk = Buffer.alloc(1024 * 1024, 19); for (const offset of [0, chunk.length]) expect(f.call({ action: "seed-chunk", seedId, path: "memory/data", offset, base64: chunk.toString("base64") })).toEqual({}); expect(existsSync(f.root)).toBe(false); - const staging = readdirSync(f.temp).find(name => name.startsWith(".paperclip-seed-"))!; + const staging = readdirSync(f.temp).find(name => name.startsWith(".paperclip-seed-") && statSync(join(f.temp, name)).isDirectory())!; expect(statSync(join(f.temp, staging)).mode & 0o777).toBe(0o700); expect(statSync(join(f.temp, staging, "tree", "memory", "data")).mode & 0o777).toBe(0o600); expect(f.call({ action: "seed-chunk", seedId, path: "memory/data", offset: 0, base64: "" })).toEqual({ error: "conflict" }); expect(f.call({ action: "seed-commit", seedId })).toEqual({ seeded: true }); expect(readFileSync(join(f.root, "memory", "data"))).toEqual(Buffer.concat([chunk, chunk])); - expect(readdirSync(f.temp)).toEqual(["home"]); + expect(readdirSync(f.temp)).toEqual([".paperclip-seed-home.lock", "home"]); expect(f.call({ action: "seed-begin", seedId: randomUUID() })).toEqual({ started: false }); const g = fixture(); const partial = randomUUID(); g.call({ action: "seed-begin", seedId: partial }); @@ -194,7 +194,7 @@ describe("confined computer files", () => { expect(g.call({ action: "seed-chunk", seedId: partial, path: "large", offset: 0, base64: Buffer.alloc(1024 * 1024 + 1).toString("base64") })).toEqual({ error: "invalid" }); expect(g.call({ action: "seed-abort", seedId: partial })).toEqual({}); expect(existsSync(g.root)).toBe(false); - expect(readdirSync(g.temp)).toEqual([]); + expect(readdirSync(g.temp)).toEqual([".paperclip-seed-home.lock"]); }); it("does not replace a home created while its initial upload was in progress", () => { const f = fixture(); const seedId = randomUUID(); @@ -203,7 +203,49 @@ describe("confined computer files", () => { mkdirSync(f.root); expect(f.call({ action: "seed-commit", seedId })).toEqual({ seeded: false }); expect(readdirSync(f.root)).toEqual([]); - expect(readdirSync(f.temp)).toEqual(["home"]); + expect(readdirSync(f.temp)).toEqual([".paperclip-seed-home.lock", "home"]); + }); + it("reclaims only the expired receipted upload after an interrupted seed", () => { + const f = fixture(); const first = randomUUID(); const next = randomUUID(); + const receiptPath = join(f.temp, ".paperclip-seed-home.json"); + const oldStage = join(f.temp, `.paperclip-seed-home-${first}`); + const unrelated = join(f.temp, `.paperclip-seed-home-${randomUUID()}`); + mkdirSync(unrelated); writeFileSync(join(unrelated, "user-file"), "keep"); + expect(f.call({ action: "seed-begin", seedId: first })).toEqual({ started: true }); + expect(f.call({ action: "seed-chunk", seedId: first, path: "partial", offset: 0, base64: Buffer.alloc(1024 * 1024).toString("base64") })).toEqual({}); + expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ error: "conflict" }); + const receipt = JSON.parse(readFileSync(receiptPath, "utf8")); + expect(receipt.seedId).toBe(first); expect(receipt.updatedAt).toBeGreaterThan(0); + writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: Date.now() / 1000 - 180 })); + expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ error: "conflict" }); + writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: 0 })); + expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ started: true }); + expect(existsSync(oldStage)).toBe(false); + expect(f.call({ action: "seed-chunk", seedId: first, path: "late", offset: 0, base64: "" })).toEqual({ error: "conflict" }); + expect(readFileSync(join(unrelated, "user-file"), "utf8")).toBe("keep"); + expect(f.call({ action: "seed-abort", seedId: first })).toEqual({}); + expect(JSON.parse(readFileSync(receiptPath, "utf8")).seedId).toBe(next); + expect(f.call({ action: "seed-chunk", seedId: next, path: "complete", offset: 0, base64: Buffer.from("done").toString("base64") })).toEqual({}); + expect(f.call({ action: "seed-commit", seedId: next })).toEqual({ seeded: true }); + expect(readFileSync(join(f.root, "complete"), "utf8")).toBe("done"); + expect(existsSync(receiptPath)).toBe(false); + }); + it("cleans abandoned upload receipts on home admission but preserves unverified content", () => { + const f = fixture(); const seedId = randomUUID(); + const receiptPath = join(f.temp, ".paperclip-seed-home.json"); + const stage = join(f.temp, `.paperclip-seed-home-${seedId}`); + f.call({ action: "seed-begin", seedId }); + f.call({ action: "seed-chunk", seedId, path: "partial", offset: 0, base64: Buffer.from("partial").toString("base64") }); + mkdirSync(f.root); writeFileSync(join(f.root, "user-file"), "keep"); + const receipt = JSON.parse(readFileSync(receiptPath, "utf8")); + writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: 0 })); + writeFileSync(join(stage, "owner.json"), JSON.stringify({ purpose: "user-owned" })); + expect(f.call({ action: "list", limit: 1 })).toEqual({ error: "invalid" }); + expect(readFileSync(join(stage, "tree", "partial"), "utf8")).toBe("partial"); + writeFileSync(join(stage, "owner.json"), JSON.stringify({ purpose: receipt.purpose, root: receipt.root, seedId })); + expect(f.call({ action: "list", limit: 1 }).entries[0].name).toBe("user-file"); + expect(existsSync(stage)).toBe(false); expect(existsSync(receiptPath)).toBe(false); + expect(readFileSync(join(f.root, "user-file"), "utf8")).toBe("keep"); }); it("hashes and deletes files over the read limit while fencing changed bytes", () => { const f = fixture(); diff --git a/server/src/modules/computers/adapters/remote-program.ts b/server/src/modules/computers/adapters/remote-program.ts index f5b37d03913..e6697a06ed4 100644 --- a/server/src/modules/computers/adapters/remote-program.ts +++ b/server/src/modules/computers/adapters/remote-program.ts @@ -109,68 +109,125 @@ def directory(parts,create=False,start=None): except BaseException:os.close(fd);raise # Initial uploads stay in a private sibling until a no-replace rename publishes them. # Each request carries at most one bounded chunk, never the whole home. -if act in ('seed-begin','seed-chunk','seed-commit','seed-abort'): - import uuid,ctypes,errno - token=p.get('seedId','') +seed_actions=('seed-begin','seed-chunk','seed-commit','seed-abort') +# The durable receipt names one exact upload. Root listings (including home +# admission) reclaim expired uploads even after a controller crash or publish. +if act in seed_actions or (act=='list' and not p.get('path') and os.path.lexists(os.path.join(os.path.dirname(root),'.paperclip-seed-'+os.path.basename(root)+'.json'))): + import uuid,ctypes,errno,time,math + parentfd=None;leasefd=None;stagefd=None try: - if str(uuid.UUID(token))!=token:fail('invalid') - except (ValueError,TypeError,AttributeError):fail('invalid') - parentfd=directory(os.path.dirname(root).split('/'),create=True) - name=os.path.basename(root);staging='.paperclip-seed-'+name+'-'+token - stagefd=None;lockfd=None - try: - if act=='seed-abort': - try:shutil.rmtree(staging,dir_fd=parentfd) - except FileNotFoundError:pass - print('{}');sys.exit(0) - if act=='seed-begin': - try: - existing=os.stat(name,dir_fd=parentfd,follow_symlinks=False) - if not stat.S_ISDIR(existing.st_mode):fail('invalid') - print(json.dumps({'started':False}));sys.exit(0) - except FileNotFoundError:pass - os.mkdir(staging,0o700,dir_fd=parentfd) - stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) - lockfd=os.open('lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=stagefd) - fcntl.flock(lockfd,fcntl.LOCK_EX) - if act=='seed-begin': - os.mkdir('tree',0o700,dir_fd=stagefd) - print(json.dumps({'started':True})) - elif act=='seed-chunk': - relative=p.get('path','');safe(relative) - parts=[part for part in relative.split('/') if part not in ('','.')] - if not parts:fail('invalid') - data=base64.b64decode(p['base64'],validate=True);offset=p.get('offset') - if len(data)>1024*1024 or type(offset)!=int or offset<0 or offset+len(data)>256*1024*1024:fail('invalid') - destfd=directory(['tree']+parts[:-1],create=True,start=stagefd) - try:fd=os.open(parts[-1],os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW,0o600,dir_fd=destfd) - finally:os.close(destfd) - with os.fdopen(fd,'r+b') as f: + parentfd=directory(os.path.dirname(root).split('/'),create=act in seed_actions) + name=os.path.basename(root);receipt_name='.paperclip-seed-'+name+'.json' + leasefd=os.open('.paperclip-seed-'+name+'.lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=parentfd) + info=os.fstat(leasefd) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') + fcntl.flock(leasefd,fcntl.LOCK_EX) + def read_metadata(directory_fd,name): + fd=os.open(name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=directory_fd) + with os.fdopen(fd,'rb') as f: info=os.fstat(f.fileno()) - if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') - if info.st_size!=offset:fail('conflict') - f.seek(offset);f.write(data) - print('{}') - else: - libc=ctypes.CDLL(None,use_errno=True) - if hasattr(libc,'renameat2'):status=libc.renameat2(stagefd,b'tree',parentfd,os.fsencode(name),1) - elif hasattr(libc,'renameatx_np'):status=libc.renameatx_np(stagefd,b'tree',parentfd,os.fsencode(name),4) - else:fail('invalid') - if status!=0: - code=ctypes.get_errno() - if code not in (errno.EEXIST,errno.ENOTEMPTY):raise OSError(code,os.strerror(code)) - if not stat.S_ISDIR(os.stat(name,dir_fd=parentfd,follow_symlinks=False).st_mode):fail('invalid') - print(json.dumps({'seeded':status==0})) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1 or info.st_size>4096:fail('invalid') + return json.loads(f.read(4097)) + def save_receipt(value): + if value is None: + try:os.unlink(receipt_name,dir_fd=parentfd) + except FileNotFoundError:pass + else: + temporary=receipt_name+'.tmp' + fd=os.open(temporary,os.O_CREAT|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=parentfd) + with os.fdopen(fd,'wb') as f: + info=os.fstat(f.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') + f.truncate(0);f.write(json.dumps(value).encode());f.flush();os.fsync(f.fileno()) + os.rename(temporary,receipt_name,src_dir_fd=parentfd,dst_dir_fd=parentfd) + os.fsync(parentfd) + def identity(token):return {'purpose':'paperclip-initial-home-v1','root':root,'seedId':token} + def remove_receipted_upload(receipt): + staging='.paperclip-seed-'+name+'-'+receipt['seedId'] + try:fd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) + except FileNotFoundError:return + try: + try:marker=read_metadata(fd,'owner.json') + except FileNotFoundError: + # Receipt is durable before mkdir. An interrupted begin can only leave + # an empty directory here; never recursively remove unmarked content. + os.rmdir(staging,dir_fd=parentfd);return + if marker!=identity(receipt['seedId']):fail('invalid') + finally:os.close(fd) + shutil.rmtree(staging,dir_fd=parentfd) + try:receipt=read_metadata(parentfd,receipt_name) + except FileNotFoundError:receipt=None + if receipt is not None: + if not isinstance(receipt,dict) or receipt.get('purpose')!='paperclip-initial-home-v1' or receipt.get('root')!=root:fail('invalid') + if str(uuid.UUID(receipt.get('seedId','')))!=receipt['seedId']:fail('invalid') + updated=receipt.get('updatedAt') + if not isinstance(updated,(int,float)) or not math.isfinite(updated):fail('invalid') + # Exceeds the 120s queued+executing backend deadline, with restart margin. + if time.time()-updated>300: + remove_receipted_upload(receipt);save_receipt(None);receipt=None + if act in seed_actions: + token=p.get('seedId','') + if str(uuid.UUID(token))!=token:fail('invalid') + staging='.paperclip-seed-'+name+'-'+token + if act=='seed-begin': + try: + existing=os.stat(name,dir_fd=parentfd,follow_symlinks=False) + if not stat.S_ISDIR(existing.st_mode):fail('invalid') + print(json.dumps({'started':False}));sys.exit(0) + except FileNotFoundError:pass + if receipt is not None:fail('conflict') + # Reserve only an absent random path before persisting its exact identity. + try:os.stat(staging,dir_fd=parentfd,follow_symlinks=False);fail('conflict') + except FileNotFoundError:pass + receipt={**identity(token),'updatedAt':time.time()};save_receipt(receipt) + os.mkdir(staging,0o700,dir_fd=parentfd) + stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) + markerfd=os.open('owner.json',os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=stagefd) + with os.fdopen(markerfd,'wb') as f:f.write(json.dumps(identity(token)).encode());f.flush();os.fsync(f.fileno()) + os.mkdir('tree',0o700,dir_fd=stagefd) + print(json.dumps({'started':True})) + elif act=='seed-abort': + if receipt is not None and receipt['seedId']==token: + remove_receipted_upload(receipt);save_receipt(None) + print('{}') + else: + if receipt is None or receipt['seedId']!=token:fail('conflict') + stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) + if read_metadata(stagefd,'owner.json')!=identity(token):fail('invalid') + if act=='seed-chunk': + relative=p.get('path','');safe(relative) + parts=[part for part in relative.split('/') if part not in ('','.')] + if not parts:fail('invalid') + data=base64.b64decode(p['base64'],validate=True);offset=p.get('offset') + if len(data)>1024*1024 or type(offset)!=int or offset<0 or offset+len(data)>256*1024*1024:fail('invalid') + destfd=directory(['tree']+parts[:-1],create=True,start=stagefd) + try:fd=os.open(parts[-1],os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW,0o600,dir_fd=destfd) + finally:os.close(destfd) + with os.fdopen(fd,'r+b') as f: + info=os.fstat(f.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') + if info.st_size!=offset:fail('conflict') + f.seek(offset);f.write(data) + receipt['updatedAt']=time.time();save_receipt(receipt) + print('{}') + else: + libc=ctypes.CDLL(None,use_errno=True) + if hasattr(libc,'renameat2'):status=libc.renameat2(stagefd,b'tree',parentfd,os.fsencode(name),1) + elif hasattr(libc,'renameatx_np'):status=libc.renameatx_np(stagefd,b'tree',parentfd,os.fsencode(name),4) + else:fail('invalid') + if status!=0: + code=ctypes.get_errno() + if code not in (errno.EEXIST,errno.ENOTEMPTY):raise OSError(code,os.strerror(code)) + if not stat.S_ISDIR(os.stat(name,dir_fd=parentfd,follow_symlinks=False).st_mode):fail('invalid') + remove_receipted_upload(receipt);save_receipt(None) + print(json.dumps({'seeded':status==0})) except FileNotFoundError:fail('not_found') - except (OSError,ValueError):fail('invalid') + except (OSError,ValueError,TypeError,AttributeError):fail('invalid') finally: - if lockfd is not None:os.close(lockfd) if stagefd is not None:os.close(stagefd) - if act=='seed-commit': - try:shutil.rmtree(staging,dir_fd=parentfd) - except FileNotFoundError:pass - os.close(parentfd) - sys.exit(0) + if leasefd is not None:os.close(leasefd) + if parentfd is not None:os.close(parentfd) + if act in seed_actions:sys.exit(0) try:rootfd=directory(root.split('/')) except FileNotFoundError:fail('not_found') except OSError:fail('invalid') From 00f92a6d050245b721e3b5a41eac100dcc08aee2 Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 11:44:06 -0500 Subject: [PATCH 5/9] fix(computers): reserve bounded graceful runner retirement Fence admission and ordinary commands at warm expiry, reserve exact-generation process control for at most thirty seconds of shutdown, and always retire the owned slice after graceful close or timeout. Co-Authored-By: Paperclip --- .../adapter-utils/src/execution-target.ts | 2 +- .../modules/computers/adapters/boat.test.ts | 26 ++++ server/src/modules/computers/adapters/boat.ts | 9 +- .../computers/application/service.test.ts | 114 +++++++++++++++++- .../modules/computers/application/service.ts | 83 ++++++++++--- server/src/modules/computers/domain/ledger.ts | 2 + .../services/computer-environment-driver.ts | 4 +- 7 files changed, 219 insertions(+), 21 deletions(-) diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index 73595d5cfa6..19a62ca4262 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -247,7 +247,7 @@ export interface AdapterComputerExecutionTarget extends Omit; retainWarm(idleTimeoutMs: number): Promise; /** False means admission superseded this owner; callers must not close its process. */ - retire(): Promise; + retire(options?: { beforeStop?: () => Promise }): Promise; computerTool: { command: string; args: string[] }; } diff --git a/server/src/modules/computers/adapters/boat.test.ts b/server/src/modules/computers/adapters/boat.test.ts index 9c5a82f37d8..2c2535116b0 100644 --- a/server/src/modules/computers/adapters/boat.test.ts +++ b/server/src/modules/computers/adapters/boat.test.ts @@ -574,3 +574,29 @@ describe("Boat SSH admission", () => { expect(runner.execute).toHaveBeenCalledTimes(12); }); }); + + +describe("remote graceful retirement fence", () => { + it("records the exact generation deadline and blocks late launch or generation reuse", () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "computer-grace-"))); + roots.push(root); + const owners = join(root, "owners"); + const boot = join(root, "boot"); + writeFileSync(boot, "boot-id"); + const code = processProgram.replaceAll("/home/user/.paperclip-owners", owners) + .replaceAll("/proc/sys/kernel/random/boot_id", boot); + const invoke = (action: string, owner: Record) => { + const result = spawnSync("python3", ["-c", code], { input: JSON.stringify({ action, owner }), encoding: "utf8" }); + expect(result.status, result.stderr).toBe(0); + return JSON.parse(result.stdout); + }; + const owner = { id: "owned", generation: 7, phase: "retiring", retirementDeadline: "2099-01-01T00:00:00Z" }; + expect(invoke("advance", owner)).toEqual({}); + const marker = readFileSync(join(owners, "owned", "retiring.json"), "utf8"); + expect(JSON.parse(marker).deadline).toBe(Date.parse(owner.retirementDeadline)); + expect(invoke("launch", owner)).toEqual({ error: "conflict" }); + expect(invoke("advance", { ...owner, phase: "active", generation: 8 })).toEqual({ error: "conflict" }); + expect(invoke("advance", { ...owner, generation: 6 })).toEqual({ error: "conflict" }); + expect(readFileSync(join(owners, "owned", "retiring.json"), "utf8")).toBe(marker); + }); +}); diff --git a/server/src/modules/computers/adapters/boat.ts b/server/src/modules/computers/adapters/boat.ts index bf35376117d..9944f1d222b 100644 --- a/server/src/modules/computers/adapters/boat.ts +++ b/server/src/modules/computers/adapters/boat.ts @@ -112,7 +112,7 @@ with os.fdopen(fd,'a') as lock: `; export const processProgram = String.raw` -import os,sys,json,fcntl,subprocess,shutil,re +import os,sys,json,fcntl,subprocess,shutil,re,datetime p=json.load(sys.stdin);base='/home/user/.paperclip-owners';os.makedirs(base,exist_ok=True) def retire_owner(root,oid): open(os.path.join(root,'retired'),'a').close() @@ -151,6 +151,11 @@ with open(os.path.join(root,'lock'),'a') as lock: if owner['generation'] { expect(f.backend.stop).toHaveBeenCalledOnce(); }, ); - it("preserves recoverable running owners and gives completed warm owners their idle interval", async () => { + it("fences warm work at its deadline and bounds crashed-controller shutdown grace", async () => { const f = fixture(); await f.attach(); const binding = await f.admit(); + await binding.launch({ command: "runner" }); f.advance(180_000); await f.service.reconcile(); expect(f.backend.retire).not.toHaveBeenCalled(); @@ -343,6 +344,13 @@ describe("computer ownership", () => { await f.service.reconcile(); expect(f.backend.retire).not.toHaveBeenCalled(); f.advance(60_001); + await expect(f.admit()).rejects.toMatchObject({ code: "conflict" }); + await expect(binding.runner.execute({ command: "new work" })).rejects.toMatchObject({ code: "conflict" }); + await binding.process.runner.execute({ command: "close provider" }); + await f.service.reconcile(); + expect(f.backend.retire).not.toHaveBeenCalled(); + f.advance(30_000); + await expect(binding.process.ingress()).rejects.toMatchObject({ code: "conflict" }); await f.service.reconcile(); expect(f.backend.retire).toHaveBeenCalledOnce(); }); @@ -698,3 +706,107 @@ describe("computer retirement proof", () => { expect(f.backend.inspect).not.toHaveBeenCalled(); }); }); + + +describe("computer graceful retirement", () => { + it("fences admission and ordinary execution while allowing the exact pinned process to close", async () => { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + let finish!: () => void; + let entered!: () => void; + const closing = new Promise((resolve) => { finish = resolve; }); + const started = new Promise((resolve) => { entered = resolve; }); + const beforeStop = vi.fn(async () => { entered(); await closing; }); + const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop }); + await started; + expect((await f.repository.get(f.scope)).ledger.owners[0]).toMatchObject({ phase: "retiring" }); + await expect(f.admit()).rejects.toMatchObject({ code: "conflict" }); + await expect(binding.runner.execute({ command: "forbidden" })).rejects.toMatchObject({ code: "conflict" }); + await expect(binding.launch({ command: "forbidden" })).rejects.toMatchObject({ code: "conflict" }); + await binding.process.runner.execute({ command: "close" }); + await binding.process.ingress(); + expect(f.backend.retire).not.toHaveBeenCalled(); + const repeated = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop }); + finish(); + expect(await retiring).toEqual({ retired: true }); + expect(await repeated).toEqual({ retired: true }); + expect(beforeStop).toHaveBeenCalledOnce(); + expect(f.backend.retire).toHaveBeenCalledOnce(); + await expect(binding.process.ingress()).rejects.toMatchObject({ code: "conflict" }); + expect((await f.admit()).owner.ownerId).not.toBe(binding.owner.ownerId); + }); + it("never invokes a stale generation callback and always stops after callback failure", async () => { + const f = fixture(); + await f.attach(); + const old = await f.admit(); + await old.launch({ command: "runner" }); + await f.service.retainWarm({ ...f.scope, owner: old.owner, idleTimeoutMs: 60_000 }); + const current = await f.admit(); + const stale = vi.fn(async () => {}); + expect(await f.service.retire({ ...f.scope, owner: old.owner, beforeStop: stale })).toEqual({ retired: false }); + expect(stale).not.toHaveBeenCalled(); + expect(await f.service.retire({ ...f.scope, owner: current.owner, beforeStop: async () => { throw new Error("provider close failed"); } })).toEqual({ retired: true }); + expect(f.backend.retire).toHaveBeenCalledOnce(); + }); + it("bounds a stalled graceful close and denies late process control", async () => { + vi.useFakeTimers(); + try { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + let entered!: () => void; + const started = new Promise((resolve) => { entered = resolve; }); + const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop: async () => { + entered(); await new Promise(() => {}); + } }); + await started; + f.advance(30_001); + await expect(binding.process.runner.execute({ command: "late" })).rejects.toMatchObject({ code: "conflict" }); + await vi.advanceTimersByTimeAsync(30_000); + expect(await retiring).toEqual({ retired: true }); + expect(f.backend.retire).toHaveBeenCalledOnce(); + } finally { vi.useRealTimers(); } + }); + it("does not extend the original warm shutdown deadline when retirement starts late", async () => { + vi.useFakeTimers(); + try { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + await f.service.retainWarm({ ...f.scope, owner: binding.owner, idleTimeoutMs: 60_000 }); + f.advance(80_000); + let entered!: () => void; + const started = new Promise((resolve) => { entered = resolve; }); + const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop: async () => { + entered(); await new Promise(() => {}); + } }); + await started; + expect((await f.repository.get(f.scope)).ledger.owners[0]!.retirementDeadline).toBe("2026-10-10T12:01:30.000Z"); + f.advance(10_000); + await vi.advanceTimersByTimeAsync(10_000); + expect(await retiring).toEqual({ retired: true }); + expect(f.backend.retire).toHaveBeenCalledOnce(); + } finally { vi.useRealTimers(); } + }); + it("reconciles a crashed controller reservation only after its durable deadline", async () => { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + await f.repository.update(f.scope, (record) => { + record.ledger.owners[0]!.phase = "retiring"; + record.ledger.owners[0]!.retirementDeadline = "2026-10-10T12:00:30.000Z"; + }); + await f.service.reconcile(); + expect(f.backend.retire).not.toHaveBeenCalled(); + await expect(f.service.retire({ ...f.scope, owner: binding.owner })).rejects.toMatchObject({ code: "conflict" }); + f.advance(30_001); + await f.service.reconcile(); + expect(f.backend.retire).toHaveBeenCalledOnce(); + expect((await f.repository.get(f.scope)).ledger.owners[0]!.phase).toBe("retired"); + }); +}); diff --git a/server/src/modules/computers/application/service.ts b/server/src/modules/computers/application/service.ts index 3fb06c0a1c1..5ad160d8370 100644 --- a/server/src/modules/computers/application/service.ts +++ b/server/src/modules/computers/application/service.ts @@ -23,6 +23,8 @@ class ComputerSessionBusyError extends ComputerError { } } +// This is shutdown time only; admission and ordinary work stop at the warm deadline. +const RETIREMENT_GRACE_MS = 30_000; type Scope = { companyId: string; environmentId: string }; export function createComputerService( repository: ComputerRepository, @@ -38,6 +40,15 @@ export function createComputerService( ownerId: owner.id, generation: owner.generation, }); + const retirements = new Map>(); + const retirementGraceOpen = (owner: Owner) => owner.phase === "retiring" && + !!owner.retirementDeadline && Date.parse(owner.retirementDeadline) > now().getTime(); + const warmShutdownGraceOpen = (owner: Owner) => owner.kind === "runner" && owner.phase === "warm" && + !!owner.deadline && Date.parse(owner.deadline) + RETIREMENT_GRACE_MS > now().getTime(); + const processControlAllowed = (owner: Owner) => + ((owner.phase === "active" || owner.phase === "starting") && !expired(owner, now())) || + (owner.phase === "warm" && (!expired(owner, now()) || warmShutdownGraceOpen(owner))) || + retirementGraceOpen(owner); const base = (record: ComputerRecord) => `/home/user/paperclip/${segment(record.companyId)}`; async function admitRecord( @@ -173,14 +184,19 @@ export function createComputerService( const control = await backend.runner(record, { control: true }); let pinnedProcess = owner.process ? structuredClone(owner.process) : null; async function processScope() { - if (!pinnedProcess) return scoped({ ...record, owner: ownerRef }); + if (!pinnedProcess) { + const current = await scoped({ ...record, owner: ownerRef }); + if (!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) + throw new ComputerError("conflict", "Computer process capability has expired"); + return current; + } const latest = await repository.get(record); const candidate = latest.ledger.owners.find( (value) => value.id === owner.id, ); if ( !candidate?.process || - !["active", "starting", "warm"].includes(candidate.phase) || + !processControlAllowed(candidate) || candidate.process.nonce !== pinnedProcess.nonce || candidate.process.unitName !== pinnedProcess.unitName || candidate.process.bootId !== pinnedProcess.bootId || @@ -200,7 +216,8 @@ export function createComputerService( const current = await (processScoped ? processScope() : scoped({ ...record, owner: ownerRef })); - if (!["active", "starting", "warm"].includes(current.owner.phase)) + if ((!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) && + !(processScoped && pinnedProcess && processControlAllowed(current.owner))) throw new ComputerError("conflict", "Computer owner is retired"); // Start a command unit under the same owner slice while holding the remote tombstone lock. // The lock is released only after systemd knows the unit, so retirement cannot miss a delayed launch. @@ -235,6 +252,9 @@ try: with open(root+'/lock','a') as lock: fcntl.flock(lock,fcntl.LOCK_EX) if os.path.exists(root+'/retired'):raise RuntimeError('computer owner retired') + if os.path.exists(root+'/retiring.json'): + with open(root+'/retiring.json') as retirement:deadline=json.load(retirement)['deadline'] + if not p.get('processClaim') or time.time()*1000>=deadline:raise RuntimeError('computer owner is retiring') if p.get('processClaim'): claim=json.load(open(root+'/claim.json')) if any(claim[k]!=p['processClaim'][k] for k in ['nonce','unitName','bootId','launchGeneration']) or claim['bootId']!=open('/proc/sys/kernel/random/boot_id').read().strip():raise RuntimeError('computer process superseded') @@ -347,7 +367,7 @@ finally: }, async ingress(input?: { port?: number; path?: string }) { const current = await scoped({ ...record, owner: ownerRef }); - if (current.owner.phase === "retired") + if (!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) throw new ComputerError("conflict", "Computer owner retired"); return backend.ingress( current.record, @@ -389,10 +409,7 @@ finally: if (owner && owner.phase !== "warm") throw new ComputerSessionBusyError(owner.runId, owner.agentId); if (owner && expired(owner, now())) - throw new ComputerError( - "conflict", - "Computer warm session is retiring", - ); + throw new ComputerSessionBusyError(owner.runId, owner.agentId); if (owner) { owner.generation++; owner.phase = "starting"; @@ -504,19 +521,53 @@ finally: owner.runId === input.runId, ); } - async function retire(input: Scope & { owner: OwnerRef }) { + async function retire(input: Scope & { owner: OwnerRef; beforeStop?: () => Promise }) { + const key = `${input.companyId}:${input.environmentId}:${input.owner.computerId}:${input.owner.ownerId}:${input.owner.generation}`; + const existing = retirements.get(key); + if (existing) return existing; + const pending = performRetirement(input); + retirements.set(key, pending); + try { return await pending; } + finally { if (retirements.get(key) === pending) retirements.delete(key); } + } + async function performRetirement(input: Scope & { owner: OwnerRef; beforeStop?: () => Promise }) { const state = await repository.update(input, (record) => { - const owner = record.ledger.owners.find( - (value) => value.id === input.owner.ownerId, - ); + const owner = record.ledger.owners.find((value) => value.id === input.owner.ownerId); if (record.id !== input.owner.computerId || !owner) throw new ComputerError("not_found", "Computer owner not found"); if (owner.generation !== input.owner.generation) return null; - if (owner.phase !== "retired") owner.phase = "retiring"; - return { record: structuredClone(record), owner: structuredClone(owner) }; + if (retirementGraceOpen(owner)) + throw new ComputerError("conflict", "Computer graceful retirement is pending"); + const retirementDeadline = owner.phase === "warm" && owner.deadline + ? Math.min(now().getTime() + RETIREMENT_GRACE_MS, Date.parse(owner.deadline) + RETIREMENT_GRACE_MS) + : now().getTime() + RETIREMENT_GRACE_MS; + const graceful = owner.phase !== "retiring" && owner.phase !== "retired" && + owner.kind === "runner" && !!owner.process && !!input.beforeStop && retirementDeadline > now().getTime(); + if (owner.phase !== "retired") { + owner.phase = "retiring"; + owner.retirementDeadline = graceful ? new Date(retirementDeadline).toISOString() : null; + } + return { record: structuredClone(record), owner: structuredClone(owner), graceful }; }); if (!state) return { retired: false }; if (state.owner.phase === "retired") return { retired: true }; + if (state.graceful) { + let timer: ReturnType | undefined; + try { + await Promise.race([ + (async () => { + await backend.advance(state.record, state.owner); + if (retirementGraceOpen(state.owner)) await input.beforeStop!(); + })(), + new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Date.parse(state.owner.retirementDeadline!) - now().getTime())); }), + ]); + } catch { + // Graceful provider shutdown is best effort; physical retirement is mandatory. + } finally { if (timer) clearTimeout(timer); } + await repository.update(input, (record) => { + exactOwner(record, input.owner).retirementDeadline = null; + }); + } if (state.owner.kind === "runner") { const status = await backend.inspect(state.record); if (!["stopped", "archived"].includes(status.state)) @@ -526,6 +577,7 @@ finally: const owner = exactOwner(record, input.owner); owner.phase = "retired"; owner.deadline = null; + owner.retirementDeadline = null; }); return { retired: true }; } @@ -885,7 +937,8 @@ finally: } record = await repository.get(record); for (const owner of liveOwners(record.ledger)) - if (owner.phase === "retiring" || expired(owner, now())) + if (owner.phase === "retiring" ? !retirementGraceOpen(owner) + : expired(owner, now()) && !warmShutdownGraceOpen(owner)) await retire({ ...record, owner: ref(record, owner) }); await repository.update(record, (current) => { current.ledger.owners = current.ledger.owners.filter( diff --git a/server/src/modules/computers/domain/ledger.ts b/server/src/modules/computers/domain/ledger.ts index 136e0c444a6..c433e576b81 100644 --- a/server/src/modules/computers/domain/ledger.ts +++ b/server/src/modules/computers/domain/ledger.ts @@ -23,6 +23,8 @@ export interface Owner { port: number; deadline: string | null; absoluteDeadline: string | null; + /** Bounded graceful shutdown reservation; only pinned process control remains valid. */ + retirementDeadline?: string | null; process: ProcessClaim | null; } export interface Ledger { diff --git a/server/src/services/computer-environment-driver.ts b/server/src/services/computer-environment-driver.ts index fd1e0ef8dcd..505c2885ca7 100644 --- a/server/src/services/computer-environment-driver.ts +++ b/server/src/services/computer-environment-driver.ts @@ -121,8 +121,8 @@ export async function computerExecutionTarget(db: Db, lease: EnvironmentLease, i workspaceRealization: { mode: "in_place", authoritativeRoot: binding.remoteCwd, pathAliases: [], outboundRestorePaths: [] }, launch: binding.launch, inspectProcess: binding.inspectProcess, retainWarm: (idleTimeoutMs) => computers.retainWarm({ ...scope, owner, idleTimeoutMs }), - retire: async () => { - const result = await computers.retire({ ...scope, owner }); + retire: async (options) => { + const result = await computers.retire({ ...scope, owner, beforeStop: options?.beforeStop }); if (result.retired) await environmentService(db).releaseLease(lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }) }); return result.retired; From 1c705e099152548a38d3c396da2227eeb50c31eb Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 11:21:34 -0500 Subject: [PATCH 6/9] Wait for inbox retry response before leaving the page Co-Authored-By: Paperclip --- tests/e2e/legacy-failure-continuation.spec.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/e2e/legacy-failure-continuation.spec.ts b/tests/e2e/legacy-failure-continuation.spec.ts index dc7875e862b..6645935cbab 100644 --- a/tests/e2e/legacy-failure-continuation.spec.ts +++ b/tests/e2e/legacy-failure-continuation.spec.ts @@ -99,9 +99,21 @@ for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "q } else if (action === "message") { await page.getByRole("textbox", { name: "editable markdown" }).fill("Please continue the pending follow-up."); await page.getByRole("button", { name: "Send", exact: true }).click(); + } else if (action === "inbox_retry") { + // Navigation can cancel the mutation before its request is sent. + const [response] = await Promise.all([ + page.waitForResponse((response) => { + const request = response.request(); + return request.method() === "POST" + && new URL(response.url()).pathname.endsWith(`/agents/${agent.id}/wakeup`) + && request.postDataJSON()?.failedRunId === sourceRunId; + }), + page.getByRole("button", { name: "Retry", exact: true }).click(), + ]); + expect(response.ok(), `${response.status()} ${await response.text()}`).toBe(true); + await page.goto(taskUrl); } else { await page.getByRole("button", { name: action === "thread_retry" ? "Try again" : "Retry", exact: true }).click(); - if (action === "inbox_retry") await page.goto(taskUrl); } await expect(page.getByText("Answered the pending follow-up once.", { exact: false })).toBeVisible({ timeout: 45_000 }); await expect(page.getByRole("status", { name: "Task recovery" })).toHaveCount(0); From da30252a5e49543e14700d6f47361c596d319998 Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 11:32:04 -0500 Subject: [PATCH 7/9] Compare project plans with the first started execution Co-Authored-By: Paperclip --- tests/e2e/agent-chat-projects.spec.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/e2e/agent-chat-projects.spec.ts b/tests/e2e/agent-chat-projects.spec.ts index d4979449e37..c8fcdc2345e 100644 --- a/tests/e2e/agent-chat-projects.spec.ts +++ b/tests/e2e/agent-chat-projects.spec.ts @@ -124,12 +124,19 @@ test("split handoff commits relevant plans before execution and never creates ch const runs = await json( await request.get(`/api/companies/${f.company.id}/heartbeat-runs`), ); - const run = runs.find( + const taskRuns = runs.filter( (run: any) => run.contextSnapshot?.issueId === task.id, ); - expect(run).toBeTruthy(); + expect(taskRuns.length).toBeGreaterThan(0); + const startedAt = taskRuns + .filter((run: any) => run.startedAt != null) + .map((run: any) => Date.parse(run.startedAt)); + // A newer queued/cancelled run need not have started. Preserve the + // invariant against the first actual execution, not list ordering. + expect(startedAt.length).toBeGreaterThan(0); + expect(startedAt.every(Number.isFinite)).toBe(true); expect(Date.parse(plan.updatedAt)).toBeLessThanOrEqual( - Date.parse(run.startedAt), + Math.min(...startedAt), ); } expect( From 80967271176f9f78352f8ea0145079475bc91334 Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 11:44:36 -0500 Subject: [PATCH 8/9] test(boat): keep remote acceptance extensions in stacked PR Preserve the two existing additive runtime acceptance suites in the stacked feature PR while keeping browser synchronization fixes in the independently checked core branch. Co-Authored-By: Paperclip --- .../src/server/execute.remote.test.ts | 25 ------------ .../heartbeat/runtime-execution.test.ts | 39 ------------------- 2 files changed, 64 deletions(-) diff --git a/packages/adapters/claude-local/src/server/execute.remote.test.ts b/packages/adapters/claude-local/src/server/execute.remote.test.ts index 58118a838e6..cbb6ed55013 100644 --- a/packages/adapters/claude-local/src/server/execute.remote.test.ts +++ b/packages/adapters/claude-local/src/server/execute.remote.test.ts @@ -231,31 +231,6 @@ describe("claude remote execution", () => { })); }); - it("keeps an authoritative remote workspace in place while delivering managed Claude assets", async () => { - const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-claude-in-place-")); - cleanupDirs.push(rootDir); - await execute({ - runId: "run-in-place", - agent: { id: "agent-1", companyId: "company-1", name: "Claude", adapterType: "claude_local", adapterConfig: {} }, - runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null }, - config: { engine: "cli", command: "claude", cwd: "/stale-host-cwd" }, - context: { paperclipWorkspace: { cwd: "/remote-only-agent-home", source: "agent_home" } }, - executionTarget: { - kind: "remote", transport: "ssh", remoteCwd: "/old-copied-workspace", - workspaceRealization: { mode: "in_place", authoritativeRoot: "/persistent-project", pathAliases: [], outboundRestorePaths: [] }, - spec: { host: "127.0.0.1", port: 2222, username: "fixture", remoteWorkspacePath: "/persistent-project", remoteCwd: "/persistent-project", - privateKey: "PRIVATE KEY", knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA", strictHostKeyChecking: true }, - }, - onLog: async () => {}, - }); - expect(prepareWorkspaceForSshExecution).not.toHaveBeenCalled(); - expect(restoreWorkspaceFromSshExecution).not.toHaveBeenCalled(); - expect(syncDirectoryToSsh).toHaveBeenCalledTimes(2); - expect(syncDirectoryToSsh).toHaveBeenCalledWith(expect.objectContaining({ remoteDir: "/persistent-project/.paperclip-runtime/claude/skills" })); - const call = runChildProcess.mock.calls[0] as unknown as [string, string, string[], { remoteExecution: { remoteCwd: string } }]; - expect(call[3].remoteExecution.remoteCwd).toBe("/persistent-project"); - }); - it("does not resume saved Claude sessions for remote SSH execution without a matching remote identity", async () => { const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-claude-remote-resume-")); cleanupDirs.push(rootDir); diff --git a/server/src/services/heartbeat/runtime-execution.test.ts b/server/src/services/heartbeat/runtime-execution.test.ts index be39cf56883..6fdf8fa0e9b 100644 --- a/server/src/services/heartbeat/runtime-execution.test.ts +++ b/server/src/services/heartbeat/runtime-execution.test.ts @@ -1,5 +1,4 @@ import { randomUUID } from "node:crypto"; -import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -219,44 +218,6 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () = expectCleanup(input); }); - it.each([true, false])("validates computer worktrees remotely before finalization (matching branch: %s)", async matches => { - const { input, adapter } = await fixture(); - const remoteCwd = "/home/user/paperclip/company/projects/project/task"; - const runner: CommandManagedRuntimeRunner = { - execute: vi.fn(async () => ({ exitCode: 0, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString(), - stdout: matches ? "paperclip/task\n" : "other-task\n", stderr: "" })), - }; - input.workspace.executionTarget = { - kind: "remote", transport: "computer", remoteCwd, runner, processRunner: runner, - listenerPort: 43100, - resourceAuthority: { kind: "computer-owner", computerId: randomUUID(), ownerId: randomUUID(), generation: 1 }, - fileAuthority: { kind: "remote-persistent", placementId: randomUUID(), root: remoteCwd, agentHome: "/home/user/paperclip/company/agents/agent" }, - launch: vi.fn(), inspectProcess: vi.fn(async () => ({ running: false, claim: null })), - retainWarm: vi.fn(), retire: vi.fn(async () => true), computerTool: { command: "computer", args: [] }, - }; - Object.assign(input.workspace.executionWorkspace, { - cwd: remoteCwd, worktreePath: remoteCwd, strategy: "git_worktree", branchName: "paperclip/task", - }); - adapter.execute.mockImplementationOnce(async ctx => { - expect(ctx.stopRemoteStartup).toBeTypeOf("function"); - await expect(ctx.stopRemoteStartup!()).rejects.toThrow("Remote startup stop requires a cancelled run"); - expect(input.services.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); - return { exitCode: 0, signal: null, timedOut: false }; - }); - if (matches) { - await expect(executeHeartbeatRuntime(db, input)).resolves.toMatchObject({ dispatched: true }); - expect(await finalizations()).toMatchObject([{ status: "succeeded" }]); - } else { - await expect(executeHeartbeatRuntime(db, input)).rejects.toThrow("computer_workspace_branch_mismatch"); - expect(await finalizations()).toMatchObject([{ status: "failed" }]); - } - expect(runner.execute).toHaveBeenCalledOnce(); - expect(runner.execute).toHaveBeenCalledWith(expect.objectContaining({ - command: "git", args: ["symbolic-ref", "--quiet", "--short", "HEAD"], cwd: remoteCwd, bypassSession: true, - })); - expectCleanup(input); - }); - it("retains a failed sandbox restore even when persisting its receipt throws", async () => { const { input, adapter, run } = await fixture(); input.workspace.executionTarget = { kind: "remote", transport: "sandbox", remoteCwd: home }; From 94ddd82b9f0a4c990296d4602f4ab83712b592a5 Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 11:45:33 -0500 Subject: [PATCH 9/9] fix(boat): settle runner authority before idle retirement Reserve exact computer generations for graceful suspension, keep provider checkpoints on their persistent remote authority, and fence failed prelaunch attempts before retry. Recover previously retired quiescent Codex checkpoints only with exact ownership and unchanged-byte evidence. Co-Authored-By: Paperclip --- .../native-session-executor.test.ts | 199 +++++++++++++++++- .../native-runtime/native-session-executor.ts | 193 +++++++++++++++-- 2 files changed, 373 insertions(+), 19 deletions(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 272976eb92d..d40cf055daa 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1,4 +1,4 @@ -import { nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js"; +import { compareAndSealRetiredComputerCheckpoint, retiredComputerCheckpointIsSettled, retireUnlaunchedComputerAttempt, nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js"; import { prepareHeartbeatGitHubLaunchers } from "../heartbeat-github-launchers.js"; import { gunzipSync } from "node:zlib"; import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js"; @@ -7698,7 +7698,7 @@ describe("native warm session supervision", () => { const name = `computer-owner-${suffix}`; const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name, executionWorkspaceId: name }, session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; - const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async () => true); + const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); const target = { kind: "remote" as const, transport: "computer" as const, environmentId: "shared-computer", remoteCwd: `/home/user/${name}`, listenerPort: suffix === "a" ? 45001 : 45002, resourceAuthority: { kind: "computer-owner", computerId: "computer", ownerId: name, generation: 1 }, @@ -7731,7 +7731,7 @@ describe("native warm session supervision", () => { const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name, executionWorkspaceId: name }, session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; const firstClose = vi.fn(async () => undefined), secondClose = vi.fn(async () => undefined); - const firstRetire = vi.fn(async () => true), secondRetire = vi.fn(async () => true); + const firstRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }), secondRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`, resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: "prior-owner", generation: 1 }, retainWarm: vi.fn(async () => undefined), retire: firstRetire }; @@ -7768,7 +7768,7 @@ describe("native warm session supervision", () => { const detachControllerForRestart = vi.fn(async () => undefined); const session = { close, detachControllerForRestart }; let generation = 1; - const retire = vi.fn(async () => generation === 1); + const retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { if (generation !== 1) return false; await options?.beforeStop?.(); return true; }); const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`, resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, retainWarm: vi.fn(async () => undefined), retire }; @@ -7796,14 +7796,14 @@ describe("native warm session supervision", () => { expect(close).not.toHaveBeenCalled(); expect(detachControllerForRestart).not.toHaveBeenCalled(); const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; - const nextRetire = vi.fn(async () => true); + const nextRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: name, runnerEnvironment: await environmentForRun(next.binding.runId), runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, generation: 2 }, retire: nextRetire } as never }); await closeWarmNativeSessionsForRun({ runId: next.binding.runId, reason: "fixture cleanup" }); expect(nextRetire).toHaveBeenCalledOnce(); - expect(detachControllerForRestart).toHaveBeenCalledOnce(); - expect(close).not.toHaveBeenCalled(); + expect(detachControllerForRestart).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalledOnce(); } finally { vi.useRealTimers(); } }); @@ -13512,6 +13512,49 @@ describe("runnerd provider runtime wiring", () => { } finally { await rm(root, { recursive: true, force: true }); } }); + it("keeps computer checkpoints remote through close and the next session preparation", async () => { + const remoteRoot = "/remote/persistent-agent"; + const runnerId = "persistent-computer-runner"; + const runnerState = { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended", runnerInstanceId: runnerId, + normalizedSessionId: execution.session.normalizedSessionId, runId: execution.binding.runId }; + const providerState = { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "durable-thread", + activeProviderTurnId: null, config: { provider: "codex", driver: "codex_app_server" } }; + const syncOut = vi.fn(async () => { throw new Error("persistent checkpoint must not copy back"); }); + const syncIn = vi.fn(async () => { throw new Error("persistent checkpoint must not restore host history"); }); + const remoteExecute = vi.fn(async (command: { command: string; args?: string[] }) => { + const script = command.args?.[1] ?? ""; + let stdout = ""; + if (command.args?.[0] === "--build-metadata") stdout = JSON.stringify({ + schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", packageName: "@paperclipai/paperclip-runner", + binaryContractVersion: 2, durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"], + }); + else if (command.args?.[0] === "--version") stdout = "codex-cli 0.160.0"; + else if (script.includes("command -v paperclip-runnerd")) stdout = "/usr/bin/paperclip-runnerd\n"; + else if (script.includes("command -v codex")) stdout = "/usr/bin/codex\n"; + else if (script.includes("base64 <")) stdout = Buffer.from(JSON.stringify(script.endsWith("codex-provider-state.json'") ? providerState : runnerState)).toString("base64"); + if (script.includes("tar ")) throw new Error("persistent checkpoint must not archive"); + return { exitCode: 0, timedOut: false, signal: null, stdout, stderr: "" }; + }); + const target = { kind: "remote", transport: "computer", environmentId: "environment", leaseId: "lease", providerKey: "boat", + remoteCwd: remoteRoot, listenerPort: 43127, effectiveCapabilities: { runnerWebSocketIngress: true }, + fileAuthority: { kind: "remote-persistent", root: remoteRoot, agentHome: remoteRoot, placementId: "placement" }, + runner: { execute: remoteExecute, syncIn, syncOut }, processRunner: { execute: remoteExecute, syncIn, syncOut }, + getRunnerIngressEndpoint: async () => ({ url: "wss://example.test/runner", close: async () => undefined }) }; + await createRunnerdBackend({ db: leaseDb(execution), execution, runnerInstanceId: runnerId, + runnerIngressAuthorized: true, runnerExecutionTarget: target as never }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const transport = state.createTransport.mock.calls.at(-1)![0] as RunnerTransportOptions & { + controlPlaneRegistration: (authority: unknown) => Promise<{ checkpoint: (settlement: string) => Promise }>; + prepareExternalRunnerState: () => Promise; + }; + const registration = await transport.controlPlaneRegistration({}); + await expect(registration.checkpoint("settled")).resolves.toBeUndefined(); + expect(remoteExecute.mock.calls.some(([command]) => command.args?.[1]?.endsWith("codex-provider-state.json'"))).toBe(true); + await expect(transport.prepareExternalRunnerState()).resolves.toBeUndefined(); + expect(syncOut).not.toHaveBeenCalled(); expect(syncIn).not.toHaveBeenCalled(); + await expect(access(join(transport.stateDirectory!, "failover-backups", "current"))).rejects.toThrow(); + }); + it.each([ { override: undefined, expected: "@openai/codex@0.160.0" }, { override: "@openai/codex@0.159.0", expected: "@openai/codex@0.159.0" }, @@ -13792,3 +13835,145 @@ describe("computer provider-pack bootstrap policy", () => { expect(nativeSessionBootstrapTimeoutMs(provider, target)).toBe(expected); }); }); + +describe("computer idle authority transition", () => { + function settled() { + const identity = { runId: execution.binding.runId, normalizedSessionId: execution.session.normalizedSessionId!, + runnerInstanceId: "prior-runner", environmentLeaseId: "prior-lease", turnId: "turn", itemId: "item" }; + const current = { ...execution, binding: { ...execution.binding, runId: "next-run" } }; + const checkpoint = { driverKind: "codex_app_server", providerSessionId: "thread", activeTurnId: null, + pendingRuntimeRequests: [], identity: { ...execution.binding, sessionId: execution.session.normalizedSessionId } }; + return { identity, execution: current, priorExecution: execution, + runner: { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready", outbox: [], pendingTerminalDelivery: null }, + control: { identity, commands: [{ status: "completed" }], committedEvents: [{ eventType: "run.terminal", envelope: identity }] }, + provider: { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "thread", + config: { provider: "codex", driver: "codex_app_server" }, activeProviderTurnId: null, completedTurnAuthoritative: true }, + checkpoint, currentCheckpoint: { ...checkpoint, identity: { ...checkpoint.identity, runId: current.binding.runId } } }; + } + + it("requires a terminal provider checkpoint with matching prior and successor scope", () => { + expect(retiredComputerCheckpointIsSettled(settled())).toBe(true); + }); + it.each(["pending-command", "pending-event", "unsettled-provider", "wrong-run", "wrong-thread", "active-turn", "config-change", "acpx"])( + "does not manufacture suspension from %s evidence", (condition) => { + const input = settled(); + if (condition === "pending-command") input.control.commands[0]!.status = "pending"; + if (condition === "pending-event") (input.runner.outbox as unknown[]).push({ event: "unacked" }); + if (condition === "unsettled-provider") input.provider.completedTurnAuthoritative = false; + if (condition === "wrong-run") input.currentCheckpoint.identity.runId = "foreign"; + if (condition === "wrong-thread") input.currentCheckpoint.providerSessionId = "foreign"; + if (condition === "active-turn") Object.assign(input.currentCheckpoint, { activeTurnId: "active" }); + if (condition === "config-change") input.execution = { ...input.execution, provider: { ...input.execution.provider, model: "changed" } }; + if (condition === "acpx") input.execution = { ...input.execution, provider: { ...input.execution.provider, kind: "acpx" } } as typeof input.execution; + expect(retiredComputerCheckpointIsSettled(input)).toBe(false); + }); + + it.each(["unchanged", "runner-changed", "provider-changed", "symlink", "interrupted"])( + "atomically seals only the unchanged remote bytes (%s)", async (condition) => { + const root = await mkdtemp(join(tmpdir(), "computer-retired-cas-")); + const runnerPath = join(root, "runner.json"), providerPath = join(root, "provider.json"); + const runnerBytes = Buffer.from(JSON.stringify(settled().runner)), providerBytes = Buffer.from(JSON.stringify(settled().provider)); + await writeFile(runnerPath, runnerBytes); await writeFile(providerPath, providerBytes); + const runner = { execute: async (command: { command: string; args?: string[] }) => { + if (condition === "runner-changed") await writeFile(runnerPath, JSON.stringify({ lifecycle: "active" })); + if (condition === "provider-changed") await writeFile(providerPath, JSON.stringify({ activeTurn: "new" })); + if (condition === "symlink") { await rm(runnerPath); await symlink(providerPath, runnerPath); } + if (condition === "interrupted") return { exitCode: null, signal: "SIGTERM", timedOut: true, stdout: "", stderr: "" }; + try { return { exitCode: 0, signal: null, timedOut: false, stderr: "", stdout: execFileSync(command.command, command.args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; } + catch { return { exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "CAS refused" }; } + } }; + try { + const action = compareAndSealRetiredComputerCheckpoint({ runner: runner as never, runnerPath, providerPath, runnerBytes, providerBytes }); + if (condition === "unchanged") { + await expect(action).resolves.toBeUndefined(); + expect(JSON.parse(await readFile(runnerPath, "utf8"))).toEqual({ ...settled().runner, lifecycle: "suspended" }); + } else { + await expect(action).rejects.toThrow("runner_remote_retirement_checkpoint_cas_failed"); + expect(JSON.parse(await readFile(runnerPath, "utf8")).lifecycle).not.toBe("suspended"); + } + expect((await readdir(root)).filter(name => name.startsWith(".retired-checkpoint-"))).toEqual([]); + } finally { await rm(root, { recursive: true, force: true }); } + }); + + it.each(["unlaunched", "launched", "claimed", "unknown", "superseded"])( + "permits same-run admission retry only after exact prelaunch retirement (%s)", async condition => { + let active = true; + const retire = vi.fn(async () => { if (condition === "superseded") return false; active = false; return true; }); + const inspectProcess = vi.fn(async () => { + if (condition === "unknown") throw new Error("inspection unavailable"); + return { running: false, claim: condition === "claimed" ? { nonce: "prior-process" } : null }; + }); + const target = { kind: "remote", transport: "computer", inspectProcess, retire } as never; + const action = retireUnlaunchedComputerAttempt(target, condition === "launched"); + if (["unknown", "superseded"].includes(condition)) await expect(action).rejects.toThrow(); + else await expect(action).resolves.toBeUndefined(); + const admitSameRun = () => { if (active) throw new Error("Computer session already has an active turn"); }; + if (condition === "unlaunched") expect(admitSameRun).not.toThrow(); + else expect(admitSameRun).toThrow("active turn"); + if (["launched", "claimed", "unknown"].includes(condition)) expect(retire).not.toHaveBeenCalled(); + }); +}); + +describe("computer graceful idle reservation", () => { + it.each(["codex", "acpx"])("suspends %s before retiring descendants and admits the next idle turn", async kind => { + const name = `graceful-idle-${kind}`; + const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name }, + provider: kind === "codex" ? execution.provider : { kind: "acpx", agent: "claude", model: null }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; + let phase = "active"; + let checkpoint = "ready"; + const close = vi.fn(async () => { expect(phase).toBe("retiring"); checkpoint = "suspended"; }); + const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent", + resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, + retainWarm: async () => { phase = "warm"; }, + retire: vi.fn(async (options?: { beforeStop?: () => Promise }) => { + phase = "retiring"; + await options?.beforeStop?.(); + expect(checkpoint).toBe("suspended"); + phase = "retired"; + return true; + }) }; + const result = { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name, + normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1, + highestContiguousSourceSeq: 1, usage: null }; + state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close }); return result; }) + .mockImplementationOnce(async options => { expect(options.existingSession).toBeUndefined(); expect(checkpoint).toBe("suspended"); return result; }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, runnerExecutionTarget: target as never }); + await vi.advanceTimersByTimeAsync(60_000); + expect(phase).toBe("retired"); expect(close).toHaveBeenCalledOnce(); + const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; + await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: `${name}-fresh`, + runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, ownerId: "new-owner" } } as never }); + } finally { vi.useRealTimers(); } + }); + + it.each(["failed-close", "expired-reservation", "superseded"])("does not report clean close when %s", async condition => { + const name = `graceful-${condition}`; + const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; + const close = vi.fn(async () => { throw new Error("protocol close failed"); }); + const detach = vi.fn(async () => undefined); + let retired = false; + const retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { + if (condition === "superseded") return false; + if (condition === "failed-close") await options?.beforeStop?.().catch(() => undefined); + retired = true; + return true; + }); + state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close, detachControllerForRestart: detach }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name, + normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1, + highestContiguousSourceSeq: 1, usage: null }; }); + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, + runnerExecutionTarget: { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent", + resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, + retainWarm: async () => undefined, retire } as never }); + const result = await closeWarmNativeSessionsForRun({ runId: name, reason: "cancel exact task" }); + expect(result.failed).toBe(1); + expect(retired).toBe(condition !== "superseded"); + if (condition === "superseded") { expect(close).not.toHaveBeenCalled(); expect(detach).not.toHaveBeenCalled(); } + else expect(detach).toHaveBeenCalledOnce(); + }); +}); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 2129dc862b8..fb970884ff3 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -473,35 +473,51 @@ type WarmNativeSession = { lastActivityAt: string; }; +/** A scoped preparation failure is retryable only after exact retirement fences + * queued commands. A process claim or invoked launcher keeps normal recovery. */ +export async function retireUnlaunchedComputerAttempt( + target: AdapterExecutionTarget | null | undefined, + launchAttempted: boolean, +): Promise { + if (target?.kind !== "remote" || target.transport !== "computer" || launchAttempted) return; + const process = await target.inspectProcess(); + if (process.running || process.claim !== null) return; + if (!(await target.retire())) throw new NativeSessionCleanupQuarantinedError(); +} + class ComputerOwnerSupersededError extends Error { constructor() { super("computer_owner_retirement_superseded"); } } async function closeWarmNativeSession(entry: WarmNativeSession, reason: string, preserveInstructionsForRunId?: string) { - // Computer admission can advance while an old idle timer is firing. Only - // the exact durable owner may stop the runner or its controller transport. - if (entry.computerTarget && !(await entry.computerTarget.retire())) { + let closeFailure: unknown; + let closeCompleted = false; + const close = async () => { + try { await entry.session.close({ reason }); closeCompleted = true; } + catch (error) { closeFailure = error; throw error; } + }; + // Reserve the exact generation before protocol close. A winning admission + // must never receive a stale controller's suspend/kill command. The module + // always hard-retires descendants after the bounded graceful window. + if (entry.computerTarget && !(await entry.computerTarget.retire({ beforeStop: close }))) { throw new ComputerOwnerSupersededError(); } - // Revoke before awaiting process retirement/checkpoint IO. const stopping = entry.githubAccess?.stop(); try { try { - if (entry.computerTarget && entry.session.detachControllerForRestart) { - await entry.session.detachControllerForRestart(); - } else { - await entry.session.close({ reason }); + if (!entry.computerTarget) await close(); + if (closeFailure || !closeCompleted) { + await entry.session.detachControllerForRestart?.(); + throw closeFailure ?? new NativeSessionCleanupQuarantinedError(); } - } - catch (error) { + } catch (error) { try { await entry.instructionWorkingCopy?.retirementFailed?.(); } catch (receiptError) { throw new AggregateError([error, receiptError], "Warm instruction retirement and receipt both failed"); } throw error; } await entry.instructionWorkingCopy?.collectStopped(); if (entry.instructionCopy?.runId !== preserveInstructionsForRunId) await entry.instructionCopy?.collectStopped(); - } - finally { await stopping; } + } finally { await stopping; } } const warmNativeSessions = new Map(); @@ -8746,6 +8762,8 @@ async function executePaperclipNativeSessionWithinScope( }, } : input.execution; + let remoteLaunchAttempted = false; + let remoteBackendPreparationStarted = false; const leaseRenewal = startNativeSessionExecutionLeaseRenewal({ db: input.db, runId: input.execution.binding.runId, @@ -8773,6 +8791,7 @@ async function executePaperclipNativeSessionWithinScope( input.db, input.execution.binding, ); + remoteBackendPreparationStarted = input.useRunnerd === true && input.backend === undefined; const runnerdBackend = input.useRunnerd && input.backend === undefined ? await createRunnerdBackend({ @@ -8783,6 +8802,7 @@ async function executePaperclipNativeSessionWithinScope( execution: input.execution, runnerInstanceId: effectiveRunnerInstanceId, durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, + onRemoteLaunchAttempt: () => { remoteLaunchAttempted = true; }, trace, toolTrace, }) @@ -9168,6 +9188,15 @@ async function executePaperclipNativeSessionWithinScope( // with a retry or release the still-live runner's lease. throw new NativeControllerDetachedForRestartError(); } + if (remoteBackendPreparationStarted) { + try { + await retireUnlaunchedComputerAttempt(input.runnerExecutionTarget, remoteLaunchAttempted); + } catch { + // Failure to establish the exact tombstone leaves queued commands or + // a lost launch acknowledgement ambiguous. Never retry that owner. + error = new NativeSessionCleanupQuarantinedError(); + } + } const protocolIntegrityFailure = error instanceof NativeSessionProtocolIntegrityError ? error : null; const ownershipUnverified = @@ -10823,6 +10852,134 @@ export async function syncRemoteRunnerDirectoryOut(input: { } } +/** A dead computer runner may retain a ready checkpoint after controller loss. + * Match the local quiescent-recovery proof before sealing it for normal rotation. + */ +export function retiredComputerCheckpointIsSettled(input: { + execution: NativeExecutionInput; + priorExecution: NativeExecutionInput; + identity: RunnerdDurableIdentity; + runner: Record; + control: Record; + provider: Record; + checkpoint: Record; + currentCheckpoint: Record; +}): boolean { + const { execution, priorExecution, identity, runner, control, provider, checkpoint, currentCheckpoint } = input; + if (execution.provider.kind !== "codex" || priorExecution.provider.kind !== "codex") return false; + const events = control.committedEvents; + const commands = control.commands; + const terminal = record(record(Array.isArray(events) ? events.at(-1) : null).envelope); + const fields = ["runId", "normalizedSessionId", "runnerInstanceId", "environmentLeaseId", "turnId", "itemId"] as const; + if (runner.schema !== RUNNERD_STATE_SCHEMA || runner.lifecycle !== "ready" || + fields.some(key => runner[key] !== identity[key] || record(control.identity)[key] !== identity[key]) || + !Array.isArray(runner.outbox) || runner.outbox.length !== 0 || runner.pendingTerminalDelivery !== null || + !Array.isArray(commands) || commands.some(command => record(command).status !== "completed") || + !Array.isArray(events) || record(events.at(-1)).eventType !== "run.terminal" || + terminal.runId !== identity.runId || terminal.normalizedSessionId !== identity.normalizedSessionId || + provider.completedTurnAuthoritative !== true || priorExecution.binding.runId !== identity.runId || + priorExecution.binding.issueId !== execution.binding.issueId || + nativeSessionScopeKey(priorExecution) !== nativeSessionScopeKey(execution) || + nativeSessionConfigDigest(priorExecution) !== nativeSessionConfigDigest(execution)) return false; + const providerIdentity = providerSessionIdentityFromDurableProviderState({ execution: priorExecution, providerState: provider }); + if (!providerIdentity.providerSessionId) return false; + return [checkpoint, currentCheckpoint].every((value, index) => { + const binding = record(value.identity); + return value.providerSessionId === providerIdentity.providerSessionId && + value.driverKind === priorExecution.session.driverKind && value.activeTurnId === null && + Array.isArray(value.pendingRuntimeRequests) && value.pendingRuntimeRequests.length === 0 && + binding.runId === (index === 0 ? identity.runId : execution.binding.runId) && + binding.sessionId === identity.normalizedSessionId && binding.companyId === execution.binding.companyId && + binding.agentId === execution.binding.agentId && binding.issueId === execution.binding.issueId; + }); +} + +async function sealRetiredComputerRunnerState(input: { + db: Db; execution: NativeExecutionInput; root: string; + target: Extract; + runner: CommandManagedRuntimeRunner; stateDirectory: string; +}): Promise { + const identity = readRunnerdDurableIdentity(input.root); + if (!identity || identity.runId === input.execution.binding.runId || input.execution.provider.kind !== "codex") return; + if (!durableIdentityMatchesSession(identity, input.execution)) throw new Error("runner_remote_retirement_scope_mismatch"); + const controlPath = resolve(input.root, "control-plane", "control-plane-state.json"); + const controlBytes = readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large"); + const runnerPath = posix.join(input.stateDirectory, "runner-state.json"); + const providerPath = posix.join(input.stateDirectory, runnerProviderStateFilename(input.execution)); + const read = await input.runner.execute({ command: "python3", args: ["-c", String.raw` +import sys,os,stat,json,base64 +rows=[] +for p in sys.argv[1:]: + s=os.lstat(p) + if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state') + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217) + if len(data)>16777216:raise RuntimeError('unsafe recovery state') + rows.append(base64.b64encode(data).decode()) +print(json.dumps(rows))`, runnerPath, providerPath], bypassSession: true, timeoutMs: 10_000 }); + if (read.exitCode !== 0 || read.timedOut) throw new Error("runner_remote_retirement_state_unavailable"); + const [runnerBytes, providerBytes] = (JSON.parse(read.stdout) as string[]).map(value => Buffer.from(value, "base64")); + const runner = record(JSON.parse(runnerBytes!.toString("utf8"))); + if (runner.lifecycle === "suspended") return; + const runs = await input.db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, runnerProfileJson: heartbeatRuns.runnerProfileJson }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.execution.binding.companyId), + eq(heartbeatRuns.agentId, input.execution.binding.agentId), + inArray(heartbeatRuns.id, [identity.runId, input.execution.binding.runId]))); + const prior = runs.find(run => run.id === identity.runId); + const current = runs.find(run => run.id === input.execution.binding.runId); + if (!prior || !current || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(prior.status)) + throw new Error("runner_remote_retirement_authority_unverified"); + const profile = record(prior.runnerProfileJson); + const previous = parseNativeExecutionInput(profile.nativeExecutionInput); + if (!retiredComputerCheckpointIsSettled({ execution: input.execution, priorExecution: previous, identity, runner, + control: record(JSON.parse(controlBytes.toString("utf8"))), provider: record(JSON.parse(providerBytes!.toString("utf8"))), + checkpoint: record(profile.sessionCheckpoint), currentCheckpoint: record(record(current.runnerProfileJson).sessionCheckpoint) }) || + await verifyPriorRunnerdStateForSessionScope({ db: input.db, root: input.root, identity, execution: input.execution, + allowVerifiedBackup: false, allowRetainedWarmRunner: false, remoteRunnerState: true, runnerExecutionTarget: input.target }) !== "verified") + throw new Error("runner_remote_retirement_checkpoint_unsettled"); + // Recheck exact durable retirement after all awaited reads; never infer death + // from a missing PID or turn status. The compare-and-swap preserves ambiguity. + const workspace = readNativeComputerWorkspaceReference(profile.nativeComputerWorkspace); + if (!workspace || !input.target.environmentId || !(await computerService(input.db).isRetired({ + companyId: input.execution.binding.companyId, environmentId: input.target.environmentId, + owner: workspace.computerOwner, agentId: input.execution.binding.agentId, runId: identity.runId, + })) || !controlBytes.equals(readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large"))) + throw new Error("runner_remote_retirement_evidence_changed"); + await compareAndSealRetiredComputerCheckpoint({ runner: input.runner, runnerPath, providerPath, + runnerBytes: runnerBytes!, providerBytes: providerBytes! }); +} + +/** Exact retirement is checked by the caller; publication must still compare + * the complete bytes so a changed or interrupted checkpoint is never rotated. */ +export async function compareAndSealRetiredComputerCheckpoint(input: { + runner: CommandManagedRuntimeRunner; runnerPath: string; providerPath: string; + runnerBytes: Buffer; providerBytes: Buffer; +}): Promise { + const result = await input.runner.execute({ command: "python3", args: ["-c", String.raw` +import sys,os,stat,json,hashlib,tempfile +runner,provider,expected_runner,expected_provider=sys.argv[1:] +for p,digest in [(runner,expected_runner),(provider,expected_provider)]: + s=os.lstat(p) + if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state') + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217) + if len(data)>16777216:raise RuntimeError('unsafe recovery state') + if hashlib.sha256(data).hexdigest()!=digest:raise RuntimeError('recovery evidence changed') + if p==runner:state=json.loads(data) +state['lifecycle']='suspended' +fd,tmp=tempfile.mkstemp(prefix='.retired-checkpoint-',dir=os.path.dirname(runner)) +try: + with os.fdopen(fd,'w') as f:json.dump(state,f,separators=(',',':'));f.flush();os.fsync(f.fileno()) + # Recheck immediately before publication, including the provider checkpoint. + for p,digest in [(runner,expected_runner),(provider,expected_provider)]: + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:current=f.read(16777217) + if hashlib.sha256(current).hexdigest()!=digest:raise RuntimeError('recovery evidence changed') + os.replace(tmp,runner) +finally: + if os.path.exists(tmp):os.unlink(tmp) +`, input.runnerPath, input.providerPath, createHash("sha256").update(input.runnerBytes).digest("hex"), createHash("sha256").update(input.providerBytes).digest("hex")], + bypassSession: true, timeoutMs: 10_000 }); + if (result.exitCode !== 0 || result.timedOut) throw new Error("runner_remote_retirement_checkpoint_cas_failed"); +} + async function readRemoteRunnerState(input: { runner: CommandManagedRuntimeRunner; stateDirectory: string; @@ -11100,9 +11257,11 @@ export function createRemoteRunnerProcessLauncher(input: { onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise; trace?: NativeRunTrace; onRunnerProcessSpawned?: () => void; + onLaunchAttempt?: () => void; }): (spec: RunnerProcessLaunchSpec) => RunnerProcessHandle { const runner = input.runner; return (spec) => { + input.onLaunchAttempt?.(); let launchedIdentity: { nonce: string; pid: number; @@ -11404,6 +11563,7 @@ export async function createRunnerdBackend(input: { chatAttachmentReadScope?: NativeChatAttachmentReadScope; restartRecovery?: NativeRestartRecoveryClaim; durableEnvironmentLeaseId?: string; + onRemoteLaunchAttempt?: () => void; onSpawn?: (meta: { pid: number; processGroupId: number | null; @@ -13064,6 +13224,10 @@ async function createRunnerdBackendWithinSessionClaim( if (incompleteFailure) throw incompleteFailure; return; } + // The computer ledger and exact remote placement are the recovery authority. + // Its durable provider state stays on the persistent machine; importing the + // sandbox archive would create a second authority and delay bounded shutdown. + if (remoteTarget?.transport === "computer") return; const backupSpanAttributes = { provider: input.execution.provider.kind, harness: input.execution.session.driverKind, @@ -13207,6 +13371,10 @@ async function createRunnerdBackendWithinSessionClaim( runnerIngressAuthorized: input.runnerIngressAuthorized === true, }); await ensureRemoteRunner(false); + if (remoteTarget.transport === "computer" && remoteStateDirectory) { + await sealRetiredComputerRunnerState({ db: input.db, execution: input.execution, root, + target: remoteTarget, runner: remoteCommandRunner, stateDirectory: remoteStateDirectory }); + } } : undefined; const archiveExternalRunnerState = @@ -13277,6 +13445,7 @@ async function createRunnerdBackendWithinSessionClaim( onLog: input.onLog, trace: input.trace, onRunnerProcessSpawned: () => resolveRemoteRunnerProcessSpawned?.(), + onLaunchAttempt: input.onRemoteLaunchAttempt, }) : undefined; const runnerExecution: NativeExecutionInput = remoteTarget