## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native recovery must keep admitted provider state and useful workspace files. > - OpenCode binds its saved session to exact executable paths and hashes. > - A replacement image can remove those files even when session data is saved. > - Retaining a manifest alone cannot restore the missing launch files. > - This pull request saves the qualified files before provider work and restores the same owned paths. > - The benefit is cold continuity without relaxing the Runner guard or replaying a prior turn. ## Linked Issues or Issue Description Refs #19558. That fix retains the selected pack for ordinary continuation. This change adds durable file retention for a cold allocation. Related #19487 adjusts the admission budget; it does not retain launch files. A search of open and closed OpenCode cold/durable artifact PRs found no duplicate. **What happened?** A saved OpenCode session could outlive the image that supplied its Node executable, proxy, and native executable. A new image supplied different bytes. The Runner then correctly refused the changed launch profile. The saved harness did not contain the old files. **Expected behavior** Core must save qualified launch files before the first turn. It must restore those exact files under the same owned account and absolute paths. Unknown ownership, missing files, and changed hashes must still stop recovery. **Steps to reproduce** Start an admitted remote OpenCode session. Save its workspace, encrypted checkpoint, and harness data. Destroy the original allocation and controller files. Restore into a new allocation with an image whose qualified proxy has different bytes. Resume the same session. The new opt-in local qualification command automates this path with actual OpenCode and a local synthetic model. ## What Changed - Store company-bound, encrypted launch objects and canonical run/backup references. Generate migration 0438 through the normal database workflow. - Stage qualified Node, proxy, and native OpenCode files under a private content-addressed OS-account home. Record the account UID and exact launch paths. Preserve the Rust profile guard. - Gate first provider work on durable capture under the current native claim. Bound Stop/deadline waits while the actual late transfer keeps its worker and scratch ownership until settlement. Restore cold caches with verified staging and atomic rename. Keep live reattachment and historical image-rooted sessions on their existing paths. - Reuse bounded canonical expiration owners. Atomically fence old checkpoint authority with a strict company/run-scoped retirement marker before external deletion. Keep its indexed cleanup anchor across failed deletes and restart. Preserve earlier resume handles and reject later header or source-consumer writes. Add no idle scan or network call inside a transaction. - Add storage, race, executor, filesystem, and actual Rust resume regressions. Add the opt-in local Linux qualification command and operating limits in `doc/opencode-cold-recovery.md`. ## Verification - RED before repair: real PostgreSQL/AES cold restore lacked the launch files; normal executor preparation chose the new image pack. Separate regressions exposed lost upload receipts, missing cache repair, last-owner retirement, an account-UID mismatch, and a resume-handle race during external deletion. Each expected failure was captured before its repair. - Local qualification before the final master integration: 1,169 executor tests, 233 storage/archive/admission/expiration tests, all seven server typecheck layers, migration safety, and the actual Rust cold-resume test passed. - The maintained Linux command passed with two cached immutable Paperclip images whose proxy hashes differ. It removed the original account/controller trees, restored the production published cwd under a new lease, resumed the same actual OpenCode session, kept a useful file and prior model context, and made one new synthetic model request. No external model call or network was available in either container. - The object-store fixture uses real encrypted StorageService streams with an independent owned local directory. It is not hosted S3 acceptance or a complete task HTTP/actor workflow. Historical tasks still require normal effects reconciliation and recovery after deployment. - Review regressions reproduced partial-cache publication, resume-versus-deletion, fresh-writer and source-consumer resurrection, and unbounded Stop/deadline waits before each repair. They now pass through real filesystem, encrypted storage, PostgreSQL, and SDK boundaries. File validation is split from database ownership (384/831 source lines). - Clean runtime head `aadab7acc69ff959678030db46ffe2dcfbefe28f`: the maintained actual OpenCode cold qualification passed with `dirty:false`. It preserved the provider session and recorded launch paths, restored useful workspace content and prior model context, and made exactly one resumed synthetic model request. The 314,560,000-byte launch capture took 23.118 seconds; the later harness was 833,536 bytes. Subsequent repairs change backup-reference retirement and governed continuity-cache classification; capture, restore, launch, and published-workspace inputs are unchanged, so that runtime receipt remains scoped to those paths. The continuity-break consumer is verified separately. - Retention repair `c14d386cecf7123257918ba6a8d47307df2da397`: 68/68 affected real PostgreSQL/AES storage tests and 15/15 focused executor authority/admission cases pass. All seven server typecheck layers pass (source layers and unchanged test shards, with the final 590-file test layer repeated after fixture edits). All review threads have evidence-backed resolutions. Its subsequent CI caught the separate lifecycle-classification gap described below. The refreshed Paperclip review reported paused work, not a completed new review. - Final head `4d1cd3e3309e328b11abc85adc6d78c6d0c7f55d`: all 19 focused root-entry/executor cases and all three source declaration layers pass. [Greptile reviewed this exact head at 5/5](https://github.com/paperclipai/paperclip/pull/19622#issuecomment-6695984874). Final-head [CI verification](https://github.com/paperclipai/paperclip/actions/runs/42308908167/job/128214100339) passes: 60 successful checks, five conditional skips, and the explicitly neutral paused Paperclip review. No check is pending or failing. - CI also caught the launch cache missing from the session-root lifecycle contract. Both the writer scan and a real governed-replacement consumer failed locally before repair: old launch bytes remained in the active root. The cache now archives with the prior session state; the consumer verifies exact bytes are preserved in the archive and absent from the active root. - The latest review found that backup retirement could delete an independent run pin while a selected session retained the checkpoint. A real PostgreSQL/AES regression failed before the repair. Backup-only ownership now uses a NULL-safe exact backup predicate; the run pin belongs to fenced checkpoint expiration. The regression verifies checkpoint decryption and launch-file restoration after pending-backup cleanup, followed by deletion only after removing the final resume handle. - An executor first-session case checks new-session durable capture through the real capture helper and receipt propagation into the actual harness manifest at the backup boundary. Real storage cases verify the run-profile receipt and canonical backup/run pins. - Sequential closure reuse and simultaneous first admission are different scopes. A deterministic two-uploader test measures both independent uploads, one verified ready winner, loser-only deletion, and usable restoration for both runs. Each capture is bounded to 512 MiB and five minutes; up to three pending receipts per run are retained. There is no claim of global single-flight capture or a company-wide egress bound. - Earlier optional warm-ownership verification encountered missing local binaries. After exact-source setup, all nine ownership assertions passed; two other suites encountered local PostgreSQL setup/teardown contention, so those interrupted attempts are not passes. Required current-head CI supplies the broad final coverage. No deployment or hosted historical recovery is claimed. ## Risks - This adds two tables and a forward migration. The file object is bounded to 512 MiB. Capture adds one initial transfer; later harness archives exclude those large files. Company-scoped ready objects are shared and retained until the last canonical owner retires. Concurrent initial admissions can duplicate bounded transfers; each keeps independent ownership and cancellation rather than waiting on another controller. A continuity break retains the controller cache with its prior state until normal session-root cleanup, adding up to one bounded launch closure per retired state. - Cold continuity requires the same qualified Linux platform, supported runtime dependencies, owned account UID/home, and published absolute cwd. A mismatch fails closed. No alias or Rust guard change is included. - Existing image-rooted profiles have no retained file object. This change cannot backfill missing historical binaries. A fresh governed session must reconcile prior effects first. - Live reattachment does not read artifact objects. Storage or provenance failures before a new turn hold admission. They do not grant new execution, model, tool, or replay authority. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and local browser tools. The exact served model ID and context window are not exposed in this session. No claim is made for unavailable model metadata. ## 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 <noreply@paperclip.ing>
8.8 KiB
OpenCode launch artifacts and cold recovery
OpenCode records the absolute paths and hashes of its Node executable, proxy, and native executable in its durable provider state. An image upgrade can change these files. A saved session must keep its admitted files. The Runner still rejects a different launch profile.
For a new managed remote OpenCode session with durable object storage, Core puts
these three qualified files in the runtime account's private, content-addressed
launch directory. Core reads the home and UID from the runtime OS account
database. It does not infer ownership from HOME, a workspace path, or a provider
response. The launch receipt records this UID, the absolute directory, the pack
manifest, and the encrypted artifact identity.
Core saves the files before it releases the first provider turn. Artifact capture uses the current native coordinator claim and the recorded Core admission. A brief admission lock waits for at most one second and checks the current owner after it acquires the lock. A stale, revoked, or unknown owner cannot publish. The artifact operation does not grant execution or tool authority.
The archive is limited to 512 MiB of launch files. Core streams files and checks hashes and file identity before and after capture. Pack-internal package links can resolve to regular source files. Links outside the selected pack are refused. The published launch directory contains regular files and private, owned parents. Node and OpenCode must be qualified native ELF executables. A script wrapper or a changed account fails closed. The selected runtime must still supply the qualified native executables' platform and system dependencies.
The artifact object uses authenticated encryption and a company-bound key wrapper. A company can reuse a ready object with the same file descriptor. Canonical run and harness-backup references keep the object alive. Large launch files are excluded from each later harness archive. A pending upload records its exact encrypted object reference before upload, so an interrupted reply can be retired without guessing an object key.
A ready company closure is reused. Concurrent first admissions may independently upload that closure: each admission retains its own cancellation, ownership fence, and pending receipt rather than depending on another controller's live transfer. Each capture has the 512 MiB limit and five-minute deadline; a run can retain at most three pending uploads. Publication selects one verified ready object under the closure lock. A loser pins that winner before deleting only its own object. This bounds each admitted run, not total simultaneous company egress. A burst can therefore transfer duplicate bytes; distributed upload election is not included.
On cold recovery, Core restores the canonical Runner checkpoint, workspace snapshot, and native harness data through their normal paths. It also verifies and decrypts the recorded launch files. The runtime must have the same owned account UID and absolute home. Core stages the exact files at the recorded content-addressed paths. It does not replace files in the current image.
Published workspaces retain their recorded directory basename across lease changes. A replacement allocation with the same provider base therefore keeps the native session's absolute cwd. The workspace service can restore files to a different base, but that alone does not authorize changing a native session's cwd. This change adds no directory aliases and makes no change to the Rust profile guard.
An explicitly governed continuity break archives the controller launch cache with the prior session state, receipt, and backups. The cache is not a new execution authority and must not remain active for the fresh provider session.
Live Runner reattachment does not download or replace the launch files. Historical sessions that recorded image-rooted paths keep those paths. This change cannot reconstruct files that were never saved. A governed fresh-session transition can use a new pack after existing effects and receipts are reconciled. It must not replay a previous turn or treat a missing result as proof that no effect occurred.
Artifact cleanup uses the existing bounded checkpoint and backup expiration owners. It requires closed work, settled native ownership, and exact stopped remote execution receipts. Backup retirement releases only that backup reference. The separate run reference lasts until fenced checkpoint expiration, including when an interrupted backup upload is retired while a resume handle still exists. A remaining backup or run reference keeps the object. A failed external delete keeps its receipt and reference for a later normal expiration attempt. There is no new idle scan or timer.
Checkpoint expiration checks current resume handles under its existing locks. It then fences old generations and atomically replaces the expired header with a versioned, company/run-scoped retirement marker. An earlier handle keeps the original checkpoint and files. After retirement, readers and header writers refuse the old checkpoint. Source consumers also check retirement in their existing ownership query, so a cached old snapshot cannot bypass the barrier. The marker stays in the existing header index until external artifact deletion succeeds, including after a server restart. No transaction waits for a network delete. Families with more than 100 related runs keep every pin and checkpoint. Missing object storage keeps the marker and pins for a later normal cleanup attempt.
The capture wait responds to Stop, startup completion, and the execution deadline. Native bulk transfer does not offer a cancellation signal. Core keeps that actual transfer registered as pending startup work after it stops waiting. The late operation can write only its private local scratch files. It cannot publish after the context closes. It removes its scratch files and releases its worker responsibility only after actual settlement. Stop does not imply that this transport has finished.
Local qualification
Run the focused server suites with the repository's supported pnpm version:
pnpm --filter @paperclipai/server exec vitest run --config vitest.config.ts \
src/services/native-runtime/native-harness-backup-storage.integration.test.ts \
src/services/native-runtime/native-harness-backup-archive.test.ts \
src/services/native-runtime/remote-opencode-artifacts.test.ts \
src/services/native-runtime/native-provider-pack-admission.test.ts \
src/services/native-runtime/native-provider-artifact-capture.test.ts \
src/services/native-runtime/native-runner-checkpoint-retirement.test.ts \
src/services/native-runtime/native-session-executor.test.ts \
src/__tests__/native-harness-backup-expiration.test.ts \
src/__tests__/native-harness-backup-expiration-config.test.ts
The opt-in Linux qualification requires two locally cached Paperclip images with
full immutable image IDs and different OpenCode proxy hashes. Both images must
have the same Linux architecture and the standard qualified provider pack. The
new image must include the packaged Runner binary at
/app/server/dist/vendor/paperclip-runner/bin/paperclip-runnerd.
Build the current checkout's Runner TypeScript SDK first. Use the local Docker
context that has the cached images:
pnpm --filter @paperclipai/paperclip-runner build:typescript
pnpm --filter @paperclipai/server exec tsx scripts/qualify-opencode-cold-recovery.mts \
--context desktop-linux \
--old-image "$OLD_IMAGE" \
--new-image "$NEW_IMAGE" \
--output /tmp/opencode-cold-recovery-result.json
The command accepts only full sha256: image IDs and a local Unix Docker
endpoint. It never pulls an image. It creates isolated PostgreSQL data and two
owned containers. The containers have no network, a read-only image filesystem,
resource limits, and a private fixture OS account. The synthetic model runs on
container loopback. No external model credential or API is used.
The command uses production workspace save/restore, encrypted checkpoint and harness storage, artifact publication, admission, SDK transport, Rust Runner, and actual OpenCode. It destroys the original allocation's account and controller files, changes the image and allocation lease, and restores the same provider session. It requires the useful workspace file and earlier model context to survive. Exactly one model request is allowed in each turn. The result records image IDs, pack digests, checkout revision and dirty state, lease identities, byte counts, session continuity, and useful output. The command removes only its own containers and PostgreSQL server. It retains its temporary evidence directory.
The independent object-store fixture uses the real StorageService and encrypted streams with an owned local directory outside both destroyed allocations. This qualifies the cold restore contract. It does not qualify a hosted S3 service, a task's HTTP/actor workflow, or completion of an existing hosted task.