From 1ad5dd9dcedd5af420fc844db8b4f05e735e5ead Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:44:10 -0600 Subject: [PATCH] fix(runner): preserve admitted remote provider pack across reattach and relaunch (#22850) 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 > - Native Paperclip Runner executes remote OpenCode and ACPX sessions in sandbox environments backed by immutable image provider packs and durable session state > - When a remote run reattaches, relaunches a settled runner, or resumes a warm runner after a controller restart or deploy on an ephemeral server, `prepareRemoteRunnerAssets` rejected the sandbox's immutable image pack with `exact_identity` and then probed a non-existent workspace-staged `provider-pack` path, failing with `exitCode=127` (`No such file or directory`) > - This happened for two reasons: the reattach/warm-recovery branch skipped the `artifactStorage && providerArtifacts` fast path used during cold startup, and when local `provider-pack-authority.json` was absent (`ENOENT`), the controller fell back to its newer bundled manifest instead of re-pinning against the durable verified admission receipt in PostgreSQL > - When an immutable image pack genuinely failed compatibility and no workspace-staged pack existed, swallowing the rejection also masked the real `exact_identity` or interface failure behind `exitCode=127` > - This pull request aligns reattach and warm-recovery provider-pack preparation with durable artifact storage and verified DB admission receipts while keeping all integrity and confinement checks fail-closed > - The benefit is reliable mid-run reattach, settled-runner relaunch, and warm-session recovery across deploys without sacrificing pack-identity verification ## Linked Issues or Issue Description **What happened?** During remote `reattach_remote_runner` or `remoteWarmRecovery` (for example after a hard controller restart or deploy on an ephemeral server), `prepareRemoteRunnerAssets` failed with `runner_remote_provider_artifact_incompatible: provider pack verification failed (exitCode=127; .../.paperclip-runtime/paperclip-runner/provider-pack/node_modules/node/bin/node: No such file or directory)` right after `provider_pack.compatibility` logged `installation_unprotected` on `workspace` and `exact_identity` on `image`. **Expected behavior** A reattach, settled-runner relaunch, or warm recovery on a reused sandbox must preserve the admitted provider pack: 1. When an OpenCode session already has durable `nativeProviderArtifacts`, reattach/relaunch must restore that admitted artifact bundle using any immutable image pack's `node` executable as bootstrap instead of demanding an exact-identity match on `/opt/paperclip-runner/provider-pack`. 2. When ephemeral local `provider-pack-authority.json` is absent (`ENOENT`) after a controller restart or deploy, the controller must re-pin an OS-protected immutable image pack whose self-sealed manifest cryptographically matches the verified `nativeProviderPackAdmission` receipt stored in PostgreSQL for that exact `(companyId, agentId, runId, sessionId, runnerInstanceId, environmentLeaseId)`. 3. When no valid receipt matches (or the installed pack genuinely mismatches), reattach must fail closed with a permanent `runner_remote_provider_artifact_incompatible` error that preserves the real `failureCheck` (such as `exact_identity`) instead of masking it behind `exitCode=127` on a missing workspace path. **Steps to reproduce** 1. Start a remote native OpenCode or ACPX session in a sandbox whose immutable `/opt/paperclip-runner/provider-pack` was built from an earlier revision than the replacement controller's bundled manifest (so no workspace-staged `.paperclip-runtime/paperclip-runner/provider-pack` exists). 2. Restart or deploy the controller onto a fresh ephemeral filesystem (so local `provider-pack-authority.json` is absent) while durable `nativeProviderArtifacts` or a verified `nativeProviderPackAdmission` receipt exists in PostgreSQL. 3. Reattach or relaunch the settled remote runner (`reattach_remote_runner`) or recover the warm runner (`remoteWarmRecovery`). On unfixed `master`, `prepareRemoteRunnerAssets` rejects `/opt/paperclip-runner/provider-pack` with `exact_identity` and fails with `exitCode=127` on the missing workspace path. **Paperclip version or commit** Reproduced on `origin/master` (`fb900bf0fe`). ## What Changed - **`server/src/services/native-runtime/remote-provider-pack.ts`**: - Added `verifiedProviderPackAdmissionReceipt()` to strictly validate a PostgreSQL `nativeProviderPackAdmission` receipt and its `verified` admission state against exact `(companyId, agentId, runId, sessionId, runnerInstanceId, environmentLeaseId)` and digest/revision formats. - Added `isMissingProviderPackBinaryError()` to identify only `exitCode=127` `pack_verifier_failed` errors from a missing staged `node` binary without matching exit-code-3 verification failures or transient unavailability errors. - **`server/src/services/native-runtime/remote-provider-pack-verification.ts`**: - Extended `verifyRemoteProviderPack` / `compatibleInstallation` with an optional `admittedReceipt` (honored only when `requireExactIdentity` is true). It continues to enforce `immutable === true`, root match, schema, self-sealed `manifest_digest`, target, `pins.opencode`, all artifact paths/SHA-256 formats, and ACPX agent profile presence while requiring exact cryptographic match to `providerPackDigest`, `opencodeProxySha256`, and `sourceRevision`. - **`server/src/services/native-runtime/native-session-executor.ts`** *(kept minimal by placing pure validation helpers in `remote-provider-pack.ts` and `remote-provider-pack-verification.ts`, since `native-session-executor.ts` already exceeds 1,000 lines)*: - Added the `if (artifactStorage && providerArtifacts)` fast path to the `reattach_remote_runner || remoteWarmRecovery` branch of `prepareRemoteRunnerAssets` (matching cold preparation) and recovered session `providerArtifacts` via `recordedSessionProviderArtifacts` when relaunching a settled runner (`!adoptedProcess`). - Tracked when `selectProviderPackAuthority` fell back to `resolveCurrentProviderPackManifest()` on local `ENOENT`, loaded the verified DB admission receipt in `useInstalledProviderPack()` (supporting both same-run `providerPackAdmissionSource` and prior-run `remoteWarmRecovery` receipts), and re-bound in-memory `providerPackAuthority` to the verified manifest while preserving `runnerArtifact`. - Surfaced immutable-pack incompatibility rejections when workspace-staged pack verification fails with `exitCode=127`, while preserving valid workspace-staged packs and real verification errors from tampered workspace packs. - Hardened the `bootstrap` immutable-pack lookup in `prepareRemoteRunner` to require a valid `nodeCommand.path`. - **Tests (`native-session-executor.test.ts`, `remote-provider-pack.test.ts`, `remote-provider-pack-verification.test.ts`)**: - Added red-green behavioral regressions (with sandbox path confinement) covering durable `providerArtifacts` settled-runner relaunch with a different image pack, mid-run deploy DB receipt recovery for both OpenCode and ACPX (`claude`), `remoteWarmRecovery` prior-run DB receipt recovery, and negative fail-closed integrity checks (`exact_identity` mismatch, `pending`/`unknown`/`wrong-lease`/`missing` receipts, unprotected `immutable: false` packs, valid and tampered workspace-staged packs). ## Verification - **Red -> Green proof**: - Before production edits, `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "remote provider pack reattach and relaunch after deploy or restart"` failed 8/9 cases with verbatim `runner_remote_provider_artifact_incompatible: provider pack verification failed (exitCode=127; timedOut=false; signal=none; env: '/workspace/.paperclip-runtime/paperclip-runner/provider-pack/node_modules/node/bin/node': No such file or directory)`. - After the fix (commit `e2e7138024`): - `npx tsc --noEmit -p server/tsconfig.json`: passed (0 errors). - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "remote provider pack reattach and relaunch after deploy or restart|uses the bundled Linux image authority|relaunches|reattach"`: **112/112 passed**. - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/remote-provider-pack.test.ts src/services/native-runtime/remote-provider-pack-verification.test.ts src/services/native-runtime/remote-provider-pack-authority.test.ts src/services/native-runtime/native-artifact-preparation.test.ts src/services/native-runtime/native-provider-pack-admission.test.ts src/services/native-runtime/provider-pack-selection-harness.test.ts`: **190/190 passed**. - `pnpm verify --explain`: selects `2375/2735` Vitest files due to transitive imports of `native-session-executor.ts`; required CI covers the full repository matrix. - **Verification environment & limits**: - Verified locally with unit/behavioral Vitest suites simulating sandbox confinement and immutable/writable pack inventories on macOS (`fb900bf0fe` + `e2e7138024`). Live Daytona sandbox reattach after a staging deploy is not exercised locally and awaits post-merge deployment. ## Risks - **Previous-release & upgrade safety**: State saved by prior releases carries forward cleanly — runs with local `provider-pack-authority.json`, durable `nativeProviderArtifacts`, or a verified PostgreSQL `nativeProviderPackAdmission` receipt re-pin to their exact admitted pack across mid-run deploys. Runs with none of those receipts remain at the current-release exact-identity gate and fail closed with permanent `runner_remote_provider_artifact_incompatible` (`failureCheck: "exact_identity"`), leaving saved session/checkpoint/workspace state intact. - **Security boundary**: `admittedReceipt` is only consulted when `requireExactIdentity` is true and local authority fell back on `ENOENT`, and only for OS-protected (`immutable: true`) installations whose self-sealed manifest digest matches the DB receipt's SHA-256 digest and exact run/session/runner/lease binding. Unprotected (`immutable: false`), unverified (`pending`/`unknown`), or mismatched packs continue to fail closed. - **Overall risk**: Low to medium — scoped strictly to remote provider-pack verification on `reattach_remote_runner` and `remoteWarmRecovery`; cold launch and local execution paths are unchanged. ## Model Used - Gemini 4 Neon (`gemini-4-neon-high`), via Antigravity agent with tool use (file inspection/editing, git worktree isolation, Vitest and TypeScript execution). ## 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 - [ ] 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 --------- Co-authored-by: Paperclip --- .../native-session-executor.test.ts | 531 +++++++++++++++++- .../native-runtime/native-session-executor.ts | 144 ++++- .../provider-pack-compatibility.ts | 19 +- .../remote-provider-pack-verification.test.ts | 36 ++ .../remote-provider-pack-verification.ts | 10 +- .../remote-provider-pack.test.ts | 71 ++- .../native-runtime/remote-provider-pack.ts | 64 +++ 7 files changed, 844 insertions(+), 31 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 54aae978417..1cdedc406b1 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -51,7 +51,7 @@ import { import { execFile, execFileSync, spawn, spawnSync } from "node:child_process"; import { tmpdir } from "node:os"; import { inspect } from "node:util"; -import { basename, dirname, join, relative } from "node:path"; +import { basename, dirname, join, posix, relative } from "node:path"; import { resolvePaperclipInstanceRoot } from "../../home-paths.js"; import { activityLog, @@ -3501,6 +3501,535 @@ describe("remote provider pack manifest", () => { } }); + describe("remote provider pack reattach and relaunch after deploy or restart", () => { + function buildPackManifest(revision: string, overrides?: { proxyChar?: string; contractChar?: string; nodeChar?: string }) { + const digest = "sha256:" + (overrides?.contractChar ?? "a").repeat(64); + const artifacts = Object.fromEntries(Object.entries({ + grokLauncher: "dist/providers/grok/launcher.cjs", nodeCommand: "node_modules/node/bin/node", + productionLock: "pnpm-lock.yaml", opencodeCommand: "node_modules/.bin/opencode", + opencodeExecutable: "node_modules/opencode-ai/bin/opencode.exe", + opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs", + }).map(([key, path]) => [key, { + path, + sha256: key === "opencodeProxy" && overrides?.proxyChar ? "sha256:" + overrides.proxyChar.repeat(64) + : key === "nodeCommand" && overrides?.nodeChar ? "sha256:" + overrides.nodeChar.repeat(64) + : digest, + }])) as Record<"grokLauncher" | "nodeCommand" | "productionLock" | "opencodeCommand" | "opencodeExecutable" | "opencodeProxy" | "acpxSidecar", { path: string; sha256: string }>; + const payload = { + compatibility: { opencode: 1, acpx: 1 }, contractDigest: digest, + target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: revision.repeat(40), + pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, + opencode: "1.18.34", acpx: "0.22.0", grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion, + claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }, + acpxProfileDigests: Object.fromEntries(["grok", "claude", "codex"].map(agent => + [agent, QUALIFIED_ACPX_PROFILES[agent as "grok" | "claude" | "codex"].commandDigest])), + distDigest: digest, artifacts, + bridgeDigest: "sha256:" + createHash("sha256").update(artifacts.opencodeProxy!.sha256 + "\n" + digest + "\n" + digest).digest("hex"), + }; + return { + schema: "paperclip-runner/remote-provider-pack/v1", + payload, + digest: "sha256:" + createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex"), + }; + } + + function assertConfinedTarget(allowedRoots: readonly string[], targetPath: string) { + const normalized = posix.normalize(targetPath); + if (!allowedRoots.some(root => normalized === root || normalized.startsWith(`${root}/`))) { + throw new Error(`sandbox path escapes allowed roots (${allowedRoots.join(", ")}): ${targetPath}`); + } + } + + async function setupReattachFixture(provider: "opencode" | "claude", options: { + imageManifest: ReturnType; + imageImmutable?: boolean; + currentManifest: ReturnType; + withLocalAuthority?: boolean; + }) { + const root = await mkdtemp(join(tmpdir(), `paperclip-reattach-pack-${provider}-`)); + onTestFinished(async () => { + state.bundledPackManifestPath = null; + state.bundledRunnerBinary = null; + await rm(root, { recursive: true, force: true }); + }); + state.bundledPackManifestPath = join(root, "provider-pack.json"); + state.bundledRunnerBinary = join(root, "linux-paperclip-runnerd"); + await writeFile(state.bundledPackManifestPath, JSON.stringify(options.currentManifest)); + const daemon = Buffer.alloc(64); + daemon.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); + daemon.writeUInt16LE(62, 18); + await writeFile(state.bundledRunnerBinary, daemon); + state.resolveRemoteRunnerBinary.mockResolvedValue(state.bundledRunnerBinary); + state.resolveRunnerBinary.mockReturnValue(state.bundledRunnerBinary); + const remoteExecution = { + ...execution, + binding: { ...execution.binding, runId: `run-reattach-${provider}-${randomUUID()}` }, + provider: provider === "opencode" ? { kind: "opencode", model: null } : { kind: "acpx", agent: "claude", model: null }, + workspace: { ...execution.workspace, cwd: root }, + session: { ...execution.session, normalizedSessionId: `reattach-${provider}-${randomUUID()}`, driverKind: provider === "opencode" ? "opencode_server" : "acpx_runtime" }, + } as unknown as NativeExecutionInputV1; + const identity = { + runId: remoteExecution.binding.runId, + normalizedSessionId: remoteExecution.session.normalizedSessionId!, + runnerInstanceId: `runner-${provider}`, + environmentLeaseId: "lease", + turnId: `turn_${randomUUID()}`, + itemId: `item_${randomUUID()}`, + }; + state.createBackend.mockClear(); + state.createTransport.mockClear(); + await createRunnerdBackend({ db: leaseDb(remoteExecution), execution: remoteExecution, runnerInstanceId: identity.runnerInstanceId }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const scopedRoot = state.createTransport.mock.calls.at(-1)![0].stateDirectory!; + await mkdir(join(scopedRoot, "control-plane"), { recursive: true }); + await writeFile(join(scopedRoot, "control-plane", "control-plane-state.json"), JSON.stringify(durableControlPlaneState(identity))); + const artifact = { version: "0.0.0", digest: "sha256:" + createHash("sha256").update(daemon).digest("hex") }; + if (options.withLocalAuthority) { + resolveRemoteProviderPackAuthority({ + stateDirectory: scopedRoot, + binding: { + companyId: remoteExecution.binding.companyId, agentId: remoteExecution.binding.agentId, + workspaceId: remoteExecution.binding.executionWorkspaceId, sessionId: identity.normalizedSessionId, + runnerInstanceId: identity.runnerInstanceId, environmentLeaseId: identity.environmentLeaseId, + remoteCwd: "/workspace", providerDigest: nativeSha256(remoteExecution.provider), + }, + reattach: false, current: () => options.imageManifest, runnerArtifact: () => artifact, + }).verified(); + } + const remoteCwd = "/workspace"; + const workspacePackRoot = `${remoteCwd}/.paperclip-runtime/paperclip-runner/provider-pack`; + const execute = vi.fn(async (request: { command: string; args?: string[] }) => { + const args = request.args ?? []; + if (args[2] === "paperclip-runner-recovery-check") return { exitCode: 45, timedOut: false, stderr: "", stdout: "" }; + if (args[0] === "--build-metadata") { + return { + exitCode: 0, timedOut: false, stderr: "", + 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"], + providerPacks: [ + { root: workspacePackRoot, manifest: null, immutable: false }, + { root: "/opt/paperclip-runner/provider-pack", manifest: options.imageManifest, immutable: options.imageImmutable ?? true }, + ], + }), + }; + } + if (request.command === `${workspacePackRoot}/node_modules/node/bin/node`) { + return { exitCode: 127, timedOut: false, signal: null, stdout: "", stderr: `env: '${request.command}': No such file or directory\n` }; + } + if (args[1]?.startsWith("const os=require")) { + return { exitCode: 0, timedOut: false, stderr: "", stdout: JSON.stringify({ home: "/home/runtime-account", uid: 1000 }) }; + } + if (args[1]?.includes("base64")) { + return { + exitCode: 0, timedOut: false, stderr: "", + stdout: Buffer.from(JSON.stringify({ + ...identity, lifecycle: "suspended", outbox: [], pendingTerminalDelivery: null, pendingProviderCleanup: null, warmTransition: null, + })).toString("base64"), + }; + } + if (args[1]?.includes("cat --")) { + return { + exitCode: 0, timedOut: false, stderr: "", + stdout: `nonce\n123\n2026-09-19T10:00:00.000Z\n${identity.runnerInstanceId}\nlinux:abcd-1234:100\n`, + }; + } + return { exitCode: 0, timedOut: false, stderr: "", stdout: "" }; + }); + const syncIn = vi.fn(async (operations: Array<{ files: Array<{ targetPath: string }> }>) => { + for (const operation of operations) { + for (const file of operation.files) { + assertConfinedTarget([remoteCwd, "/home/runtime-account/.paperclip-runtime/paperclip-runner/provider-artifacts"], file.targetPath); + } + } + }); + const syncOut = vi.fn(async (operations: Array<{ files: Array<{ sourcePath: string }> }>) => { + for (const operation of operations) { + for (const file of operation.files) assertConfinedTarget([remoteCwd], file.sourcePath); + } + }); + const recoveryInput: Parameters[0] = { + db: leaseDb(remoteExecution), + execution: remoteExecution, + runnerInstanceId: identity.runnerInstanceId, + runnerIngressAuthorized: true, + controllerPersistence: { bootId: "replacement-controller", runnerArtifact: artifact }, + runnerExecutionTarget: { + kind: "remote", transport: "sandbox", remoteCwd, + environmentId: "environment", leaseId: identity.environmentLeaseId, providerKey: "daytona", + effectiveCapabilities: { runnerWebSocketIngress: true }, + runner: { execute, syncIn, syncOut }, + sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" }, + } as never, + restartRecovery: { + kind: "reattach_remote_runner", runId: remoteExecution.binding.runId, + leaseOwner: "controller", controllerGeneration: 4, providerAttempt: 2, restartKind: "hard", recoveryRequestId: null, + remote: { providerLeaseId: "sandbox", remoteCwd }, + }, + }; + return { root, scopedRoot, remoteExecution, identity, artifact, execute, syncIn, syncOut, recoveryInput }; + } + + it("relaunches a settled OpenCode runner from durable providerArtifacts even when the sandbox image pack has a different digest and no workspace pack exists", async () => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2" }); + const newerImage = buildPackManifest("b", { nodeChar: "3", proxyChar: "4" }); + const current = buildPackManifest("c", { nodeChar: "5", proxyChar: "6" }); + const fixture = await setupReattachFixture("opencode", { imageManifest: newerImage, currentManifest: current }); + const launchRoot = `/home/runtime-account/.paperclip-runtime/paperclip-runner/provider-artifacts/${admitted.digest.slice(7)}`; + const artifactReceipt = { + schema: "paperclip.native-provider-artifacts.v1" as const, artifactId: randomUUID(), + closureDigest: "sha256:" + "9".repeat(64), providerPackDigest: admitted.digest, manifest: admitted, launchRoot, accountUid: 1000, + }; + const storageMode = vi.spyOn(harnessStorage, "durableNativeHarnessStorage").mockReturnValue({} as never); + const backupOwner = vi.spyOn(harnessStorage, "nativeHarnessBackupOwner").mockResolvedValue({} as never); + const restore = vi.spyOn(providerArtifactStorage, "restoreNativeProviderArtifacts").mockResolvedValue(undefined); + onTestFinished(() => { storageMode.mockRestore(); backupOwner.mockRestore(); restore.mockRestore(); }); + + await createRunnerdBackend({ + ...fixture.recoveryInput, + providerPackAdmissionSource: { runId: fixture.remoteExecution.binding.runId, receipt: null, state: null, artifacts: artifactReceipt }, + }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + expect(restore).toHaveBeenCalledWith(expect.objectContaining({ receipt: artifactReceipt })); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ + providerPackAuthorityDigest: admitted.digest, + providerNodeCommand: `${launchRoot}/${admitted.payload.artifacts.nodeCommand.path}`, + providerNodeCommandSha256: admitted.payload.artifacts.nodeCommand.sha256, + opencodeProxyPath: `${launchRoot}/${admitted.payload.artifacts.opencodeProxy.path}`, + opencodeCommand: `${launchRoot}/${admitted.payload.artifacts.opencodeExecutable.path}`, + }); + expect(fixture.execute.mock.calls.some(([request]) => request.command.includes("/.paperclip-runtime/paperclip-runner/provider-pack/"))).toBe(false); + }); + + it("relaunches a settled OpenCode runner when durable providerArtifacts are recovered from PostgreSQL without an initial backup or providerPackAdmissionSource", async () => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2" }); + const newerImage = buildPackManifest("b", { nodeChar: "3", proxyChar: "4" }); + const current = buildPackManifest("c", { nodeChar: "5", proxyChar: "6" }); + const fixture = await setupReattachFixture("opencode", { imageManifest: newerImage, currentManifest: current }); + const launchRoot = `/home/runtime-account/.paperclip-runtime/paperclip-runner/provider-artifacts/${admitted.digest.slice(7)}`; + const artifactReceipt = { + schema: "paperclip.native-provider-artifacts.v1" as const, artifactId: randomUUID(), + closureDigest: "sha256:" + "9".repeat(64), providerPackDigest: admitted.digest, manifest: admitted, launchRoot, accountUid: 1000, + }; + const storageMode = vi.spyOn(harnessStorage, "durableNativeHarnessStorage").mockReturnValue({} as never); + const backupOwner = vi.spyOn(harnessStorage, "nativeHarnessBackupOwner").mockResolvedValue({} as never); + const restore = vi.spyOn(providerArtifactStorage, "restoreNativeProviderArtifacts").mockResolvedValue(undefined); + onTestFinished(() => { storageMode.mockRestore(); backupOwner.mockRestore(); restore.mockRestore(); }); + + const dbWithRecordedArtifacts = new Proxy(fixture.recoveryInput.db, { + get(target, key, receiver) { + if (key !== "select") return Reflect.get(target, key, receiver); + return (fields?: Record) => { + if (fields && "runnerProfileJson" in fields && Object.keys(fields).length === 1) { + return { + from: () => ({ + where: () => ({ + limit: async () => [{ runnerProfileJson: { nativeProviderArtifacts: artifactReceipt } }], + }), + }), + }; + } + return target.select(fields as never); + }; + }, + }); + + await createRunnerdBackend({ + ...fixture.recoveryInput, + db: dbWithRecordedArtifacts, + }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + expect(restore).toHaveBeenCalledWith(expect.objectContaining({ receipt: artifactReceipt })); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ + providerPackAuthorityDigest: admitted.digest, + providerNodeCommand: `${launchRoot}/${admitted.payload.artifacts.nodeCommand.path}`, + providerNodeCommandSha256: admitted.payload.artifacts.nodeCommand.sha256, + opencodeProxyPath: `${launchRoot}/${admitted.payload.artifacts.opencodeProxy.path}`, + opencodeCommand: `${launchRoot}/${admitted.payload.artifacts.opencodeExecutable.path}`, + }); + expect(fixture.execute.mock.calls.some(([request]) => request.command.includes("/.paperclip-runtime/paperclip-runner/provider-pack/"))).toBe(false); + }); + + it.each(["opencode", "claude"] as const)( + "recovers the admitted immutable image pack for %s from the durable DB admission receipt when a deploy wipes local authority files", + async provider => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2", contractChar: "a" }); + const deployed = buildPackManifest("b", { nodeChar: "3", proxyChar: "4", contractChar: "b" }); + const fixture = await setupReattachFixture(provider, { imageManifest: admitted, currentManifest: deployed }); + expect(existsSync(join(fixture.scopedRoot, "provider-pack-authority.json"))).toBe(false); + const dbReceipt = { + schema: "paperclip.native-provider-pack-admission.v1", + stage: "session_admitted", + authority: "core_verified_selection", + companyId: fixture.remoteExecution.binding.companyId, + agentId: fixture.remoteExecution.binding.agentId, + runId: fixture.remoteExecution.binding.runId, + sessionId: fixture.identity.normalizedSessionId, + runnerInstanceId: fixture.identity.runnerInstanceId, + runnerEnvironmentLeaseId: fixture.identity.environmentLeaseId, + providerPackDigest: admitted.digest, + opencodeProxySha256: admitted.payload.artifacts.opencodeProxy!.sha256, + sourceRevision: admitted.payload.runnerSourceRevision, + }; + const dbState = { ...nativeProviderPackAdmissionPending(randomUUID()), state: "verified" as const }; + await createRunnerdBackend({ + ...fixture.recoveryInput, + providerPackAdmissionSource: { runId: fixture.remoteExecution.binding.runId, receipt: dbReceipt, state: dbState }, + }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ + providerPackAuthorityDigest: admitted.digest, + runnerArtifact: fixture.artifact, + providerNodeCommand: `/opt/paperclip-runner/provider-pack/${admitted.payload.artifacts.nodeCommand.path}`, + providerNodeCommandSha256: admitted.payload.artifacts.nodeCommand.sha256, + ...(provider === "opencode" + ? { opencodeCommand: `/opt/paperclip-runner/provider-pack/${admitted.payload.artifacts.opencodeExecutable.path}` } + : { acpxSidecarPath: `/opt/paperclip-runner/provider-pack/${admitted.payload.artifacts.acpxSidecar.path}` }), + }); + }, + ); + + it("fails closed with exact_identity instead of exitCode=127 when the image pack does not match the admitted DB receipt", async () => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2" }); + const wrongImage = buildPackManifest("d", { nodeChar: "7", proxyChar: "8" }); + const deployed = buildPackManifest("b", { nodeChar: "3", proxyChar: "4" }); + const fixture = await setupReattachFixture("opencode", { imageManifest: wrongImage, currentManifest: deployed }); + const dbReceipt = { + schema: "paperclip.native-provider-pack-admission.v1", + stage: "session_admitted", + authority: "core_verified_selection", + companyId: fixture.remoteExecution.binding.companyId, + agentId: fixture.remoteExecution.binding.agentId, + runId: fixture.remoteExecution.binding.runId, + sessionId: fixture.identity.normalizedSessionId, + runnerInstanceId: fixture.identity.runnerInstanceId, + runnerEnvironmentLeaseId: fixture.identity.environmentLeaseId, + providerPackDigest: admitted.digest, + opencodeProxySha256: admitted.payload.artifacts.opencodeProxy!.sha256, + sourceRevision: admitted.payload.runnerSourceRevision, + }; + const dbState = { ...nativeProviderPackAdmissionPending(randomUUID()), state: "verified" as const }; + const backendsBefore = state.createBackend.mock.calls.length; + const failure = await createRunnerdBackend({ + ...fixture.recoveryInput, + providerPackAdmissionSource: { runId: fixture.remoteExecution.binding.runId, receipt: dbReceipt, state: dbState }, + }).catch(error => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("runner_remote_provider_artifact_incompatible"); + expect((failure as Error).message).not.toContain("exitCode=127"); + expect((failure as { failureCheck?: string }).failureCheck).toBe("exact_identity"); + expect(state.createBackend).toHaveBeenCalledTimes(backendsBefore); + }); + + it.each(["pending", "unknown", "wrong-lease", "missing"] as const)( + "refuses to adopt an unpinned image pack during reattach when the DB admission receipt is %s", + async mode => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2" }); + const deployed = buildPackManifest("b", { nodeChar: "3", proxyChar: "4" }); + const fixture = await setupReattachFixture("opencode", { imageManifest: admitted, currentManifest: deployed }); + const dbReceipt = mode === "missing" ? null : { + schema: "paperclip.native-provider-pack-admission.v1", + stage: "session_admitted", + authority: "core_verified_selection", + companyId: fixture.remoteExecution.binding.companyId, + agentId: fixture.remoteExecution.binding.agentId, + runId: fixture.remoteExecution.binding.runId, + sessionId: fixture.identity.normalizedSessionId, + runnerInstanceId: fixture.identity.runnerInstanceId, + runnerEnvironmentLeaseId: mode === "wrong-lease" ? "other-lease" : fixture.identity.environmentLeaseId, + providerPackDigest: admitted.digest, + opencodeProxySha256: admitted.payload.artifacts.opencodeProxy!.sha256, + sourceRevision: admitted.payload.runnerSourceRevision, + }; + const dbState = mode === "missing" ? null + : { ...nativeProviderPackAdmissionPending(randomUUID()), state: mode === "pending" ? "pending" : mode === "unknown" ? "unknown" : "verified" }; + const backendsBefore = state.createBackend.mock.calls.length; + const failure = await createRunnerdBackend({ + ...fixture.recoveryInput, + providerPackAdmissionSource: { runId: fixture.remoteExecution.binding.runId, receipt: dbReceipt, state: dbState }, + }).catch(error => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("runner_remote_provider_artifact_incompatible"); + expect((failure as Error).message).not.toContain("exitCode=127"); + expect((failure as { failureCheck?: string }).failureCheck).toBe("exact_identity"); + expect(state.createBackend).toHaveBeenCalledTimes(backendsBefore); + }, + ); + + it("never trusts an unprotected image pack even when the DB admission receipt matches its manifest", async () => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2" }); + const deployed = buildPackManifest("b", { nodeChar: "3", proxyChar: "4" }); + const fixture = await setupReattachFixture("opencode", { imageManifest: admitted, imageImmutable: false, currentManifest: deployed }); + const dbReceipt = { + schema: "paperclip.native-provider-pack-admission.v1", + stage: "session_admitted", + authority: "core_verified_selection", + companyId: fixture.remoteExecution.binding.companyId, + agentId: fixture.remoteExecution.binding.agentId, + runId: fixture.remoteExecution.binding.runId, + sessionId: fixture.identity.normalizedSessionId, + runnerInstanceId: fixture.identity.runnerInstanceId, + runnerEnvironmentLeaseId: fixture.identity.environmentLeaseId, + providerPackDigest: admitted.digest, + opencodeProxySha256: admitted.payload.artifacts.opencodeProxy!.sha256, + sourceRevision: admitted.payload.runnerSourceRevision, + }; + const dbState = { ...nativeProviderPackAdmissionPending(randomUUID()), state: "verified" as const }; + const backendsBefore = state.createBackend.mock.calls.length; + await expect(createRunnerdBackend({ + ...fixture.recoveryInput, + providerPackAdmissionSource: { runId: fixture.remoteExecution.binding.runId, receipt: dbReceipt, state: dbState }, + })).rejects.toThrow("runner_remote_provider_artifact_incompatible"); + expect(state.createBackend).toHaveBeenCalledTimes(backendsBefore); + }); + + it("recovers the prior run's admitted immutable image pack during remoteWarmRecovery after a deploy wipes local authority files", async () => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2", contractChar: "a" }); + const deployed = buildPackManifest("b", { nodeChar: "3", proxyChar: "4", contractChar: "b" }); + const fixture = await setupReattachFixture("claude", { imageManifest: admitted, currentManifest: deployed }); + const { permissionPolicy: _permissionPolicy, ...claudeProfile } = QUALIFIED_ACPX_PROFILES.claude; + const warmExecution = { + ...fixture.remoteExecution, + schema: "paperclip.native-execution-input.v5" as const, + executionMode: "default" as const, + planningContext: null, + runtimeContext: nativeRuntimeContextFixture(), + provider: { kind: "acpx" as const, agent: "claude" as const, model: "claude-sonnet-4-6", permissionMode: "approve-all" as const, profile: claudeProfile }, + session: { ...fixture.remoteExecution.session, driverKind: "acpx_runtime" as const, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 300_000 } }, + } as unknown as NativeExecutionInputV1; + const priorRunId = `prior-warm-${randomUUID()}`; + const priorExecution = { ...warmExecution, binding: { ...warmExecution.binding, runId: priorRunId } }; + parseNativeExecutionInput(priorExecution); + const priorIdentity = { ...fixture.identity, runId: priorRunId }; + await writeFile(join(fixture.scopedRoot, "control-plane", "control-plane-state.json"), JSON.stringify({ + ...durableControlPlaneState(priorIdentity), + commands: [{ status: "completed" }], + committedEvents: [{ eventType: "run.terminal", envelope: priorIdentity }], + })); + await mkdir(join(fixture.scopedRoot, "runner"), { recursive: true }); + await writeFile(join(fixture.scopedRoot, "runner", "runner-state.json"), JSON.stringify(durableRunnerState(priorIdentity, "suspended"))); + const projections = vi.spyOn(controllerRecovery, "resolveNativeControllerRecovery").mockResolvedValue({ kind: "no_prior_execution" }); + onTestFinished(() => projections.mockRestore()); + const dbReceipt = { + schema: "paperclip.native-provider-pack-admission.v1", + stage: "session_admitted", + authority: "core_verified_selection", + companyId: warmExecution.binding.companyId, + agentId: warmExecution.binding.agentId, + runId: priorRunId, + sessionId: fixture.identity.normalizedSessionId, + runnerInstanceId: priorIdentity.runnerInstanceId, + runnerEnvironmentLeaseId: priorIdentity.environmentLeaseId, + providerPackDigest: admitted.digest, + opencodeProxySha256: admitted.payload.artifacts.opencodeProxy!.sha256, + sourceRevision: admitted.payload.runnerSourceRevision, + }; + const dbState = { ...nativeProviderPackAdmissionPending(randomUUID()), state: "verified" as const }; + const warmDb = new Proxy(fixture.recoveryInput.db, { + get(target, key, receiver) { + if (key !== "select") return Reflect.get(target, key, receiver); + return (fields?: Record) => { + if (fields && "receipt" in fields) { + return { from: () => ({ where: () => ({ limit: async () => [{ receipt: dbReceipt, state: dbState }] }) }) }; + } + if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) { + const result = Promise.resolve([{ status: "succeeded", runnerProfileJson: { nativeExecutionInput: priorExecution } }]); + const query = { then: result.then.bind(result), where: () => query, limit: () => query }; + return { from: () => query }; + } + return target.select(fields as never); + }; + }, + }); + const warmExecute = vi.fn(async (request: { command: string; args?: string[] }) => { + const args = request.args ?? []; + if (args[2] === "paperclip-runner-recovery-check") return { exitCode: 0, timedOut: false, stderr: "", stdout: "" }; + if (request.command === "sh" && args[1]?.includes("base64")) { + return { + exitCode: 0, timedOut: false, stderr: "", + stdout: Buffer.from(JSON.stringify({ + ...priorIdentity, lifecycle: "ready", activeTurnId: null, outbox: [], pendingTerminalDelivery: null, + pendingProviderCleanup: null, warmTransition: null, + })).toString("base64"), + }; + } + return fixture.execute(request); + }); + await createRunnerdBackend({ + ...fixture.recoveryInput, + execution: warmExecution, + db: warmDb, + controllerPersistence: undefined, + restartRecovery: undefined, + runnerExecutionTarget: { + ...(fixture.recoveryInput.runnerExecutionTarget as unknown as Record), + runner: { execute: warmExecute, syncIn: fixture.syncIn, syncOut: fixture.syncOut }, + } as never, + remoteWarmRecovery: { + identity: priorIdentity, + reuseProcess: true, + previousExecution: priorExecution, + checkpoint: {} as never, + remote: { providerLeaseId: "sandbox", remoteCwd: "/workspace" }, + revalidate: async () => undefined, + }, + }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ + providerPackAuthorityDigest: admitted.digest, + providerNodeCommand: `/opt/paperclip-runner/provider-pack/${admitted.payload.artifacts.nodeCommand.path}`, + acpxSidecarPath: `/opt/paperclip-runner/provider-pack/${admitted.payload.artifacts.acpxSidecar.path}`, + adoptExistingRunner: { pid: 123 }, + }); + }); + + it("keeps a valid workspace-staged pack working and preserves workspace verification errors when tampered", async () => { + const admitted = buildPackManifest("a", { nodeChar: "1", proxyChar: "2" }); + const otherImage = buildPackManifest("b", { nodeChar: "3", proxyChar: "4" }); + const fixture = await setupReattachFixture("opencode", { imageManifest: otherImage, currentManifest: admitted, withLocalAuthority: false }); + const workspacePackRoot = "/workspace/.paperclip-runtime/paperclip-runner/provider-pack"; + const validStagedExecute = vi.fn(async (request: { command: string; args?: string[] }) => { + if (request.command === `${workspacePackRoot}/node_modules/node/bin/node`) { + return { exitCode: 0, timedOut: false, signal: null, stdout: "verified\n", stderr: "" }; + } + if (request.command === `${workspacePackRoot}/node_modules/.bin/opencode`) { + return { exitCode: 0, timedOut: false, signal: null, stdout: "1.18.34\n", stderr: "" }; + } + return fixture.execute(request); + }); + await createRunnerdBackend({ + ...fixture.recoveryInput, + runnerExecutionTarget: { + ...(fixture.recoveryInput.runnerExecutionTarget as unknown as Record), + runner: { execute: validStagedExecute, syncIn: fixture.syncIn, syncOut: fixture.syncOut }, + } as never, + }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ + providerPackAuthorityDigest: admitted.digest, + providerNodeCommand: `${workspacePackRoot}/${admitted.payload.artifacts.nodeCommand.path}`, + }); + + const tamperedStagedExecute = vi.fn(async (request: { command: string; args?: string[] }) => { + if (request.command === `${workspacePackRoot}/node_modules/node/bin/node`) { + return { exitCode: 3, timedOut: false, signal: null, stdout: "\npaperclip-pack-check=artifact_digest:nodeCommand\n", stderr: "nodeCommand digest mismatch\n" }; + } + return fixture.execute(request); + }); + const tamperedFailure = await createRunnerdBackend({ + ...fixture.recoveryInput, + runnerExecutionTarget: { + ...(fixture.recoveryInput.runnerExecutionTarget as unknown as Record), + runner: { execute: tamperedStagedExecute, syncIn: fixture.syncIn, syncOut: fixture.syncOut }, + } as never, + }).catch(error => error); + expect(tamperedFailure).toBeInstanceOf(Error); + expect((tamperedFailure as { failureCheck?: string }).failureCheck).toBe("artifact_digest:nodeCommand"); + expect((tamperedFailure as Error).message).toContain("nodeCommand digest mismatch"); + }); + }); + it("accepts a fully digested pack and rejects artifact tampering", async () => { const root = await mkdtemp(join(tmpdir(), "paperclip-provider-pack-")); await mkdir(join(root, "dist", "cli"), { recursive: true }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index cd514fa6230..70dff79fb69 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -56,7 +56,7 @@ import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-pre import { notifyInstructionCollection } from "../instruction-collection-notifications.js"; import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js"; import { nativeProviderPackAdmissionFailureCode, prepareNativeProviderPackAdmission, rememberAdmittedNativeProviderPack, rememberRecoveredNativeProviderPack, recordNativeProviderPackAdmission, type NativeProviderPackAdmissionSource } from "./native-provider-pack-admission.js"; -import { type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js"; +import { type AdmittedProviderPackReceipt, type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js"; import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js"; import { NATIVE_SESSION_EXECUTION_LEASE_TTL_MS, lockNativeExecutionLeaseForReacquire, nativeExecutionLeaseHeldCondition, releaseUnstartedNativeExecutionClaim, startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "./native-execution-lease.js"; export { renewNativeSessionExecutionLease } from "./native-execution-lease.js"; @@ -148,7 +148,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; -import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, isMissingProviderPackBinaryError, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets, verifiedProviderPackAdmissionReceipt } from "./remote-provider-pack.js"; import { uploadVerifiedProviderPack } from "./provider-pack-upload.js"; import { selectRemotePiCompanion } from "./remote-pi-companion.js"; import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js"; @@ -17319,17 +17319,28 @@ async function createRunnerdBackendWithinSessionClaim( : remoteTarget ? remoteOpenCodeArtifacts?.runnerBinary || remoteClaudeRunnerBinary || input.runnerRemoteBinaryPath?.trim() || remotePiCompanion?.runnerBinary || (useBundledRemoteImageAssets ? await verifiedBundledRemoteRunnerBinary() : await resolvePaperclipRunnerBinaryAsync()) : await resolvePaperclipRunnerBinaryAsync(); - const selectProviderPackAuthority = (reattach: boolean) => requiresRemoteProviderPack ? resolveRemoteProviderPackAuthority({ - stateDirectory: root, - binding: { companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId, - workspaceId: providerPackWorkspaceId(input.execution.binding.executionWorkspaceId, input.execution.binding.runId, effectiveEnvironmentLeaseId), sessionId: nativeSessionKey(input.execution), - runnerInstanceId: effectiveRunnerInstanceId, environmentLeaseId: effectiveEnvironmentLeaseId, - remoteCwd: remoteTarget!.remoteCwd, providerDigest: nativeSha256(input.execution.provider) }, - reattach, - retainProviderPack: !providerArtifacts && (reattach || retainProviderPack), - runnerArtifact: () => readRunnerdArtifactBinding(controllerRunnerBinary), - current: () => providerArtifacts?.manifest as RemoteProviderPackManifest ?? resolveCurrentProviderPackManifest(), - }) : null; + let providerPackAuthorityFromFallback = false; + const providerPackAuthorityBinding = () => ({ + companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId, + workspaceId: providerPackWorkspaceId(input.execution.binding.executionWorkspaceId, input.execution.binding.runId, effectiveEnvironmentLeaseId), sessionId: nativeSessionKey(input.execution), + runnerInstanceId: effectiveRunnerInstanceId, environmentLeaseId: effectiveEnvironmentLeaseId, + remoteCwd: remoteTarget!.remoteCwd, providerDigest: nativeSha256(input.execution.provider), + }); + const selectProviderPackAuthority = (reattach: boolean) => { + providerPackAuthorityFromFallback = false; + return requiresRemoteProviderPack ? resolveRemoteProviderPackAuthority({ + stateDirectory: root, + binding: providerPackAuthorityBinding(), + reattach, + retainProviderPack: !providerArtifacts && (reattach || retainProviderPack), + runnerArtifact: () => readRunnerdArtifactBinding(controllerRunnerBinary), + current: () => { + if (providerArtifacts?.manifest) return providerArtifacts.manifest as RemoteProviderPackManifest; + providerPackAuthorityFromFallback = true; + return resolveCurrentProviderPackManifest(); + }, + }) : null; + }; let providerPackAuthority = adoptingPersistedRemoteRunner ? null : selectProviderPackAuthority(reattachProviderPack); let expectedProviderPackManifest: RemoteProviderPackManifest | null = providerPackAuthority?.manifest ?? providerArtifacts?.manifest as RemoteProviderPackManifest ?? null; @@ -17467,9 +17478,55 @@ async function createRunnerdBackendWithinSessionClaim( // standard app-image path is the default transport source, not an upgrade request. const explicitProviderPackSelection = Boolean(input.runnerRemoteProviderPackPath?.trim() && input.runnerRemoteProviderPackPath.trim() !== "/opt/paperclip-runner/provider-pack"); - const useInstalledProviderPack = async () => { + const loadAdmittedProviderPackReceipt = async (): Promise => { + if (!retainProviderPack || !providerPackAuthorityFromFallback || explicitProviderPackSelection) return undefined; + const candidateRunIds = [...new Set([ + ...(input.remoteWarmRecovery ? [input.remoteWarmRecovery.identity.runId] : []), + ...(input.providerPackAdmissionSource ? [input.providerPackAdmissionSource.runId] : []), + durableIdentity?.runId, + input.execution.binding.runId, + ].filter((value): value is string => typeof value === "string" && value.length > 0))]; + const sessionId = nativeSessionKey(input.execution); + for (const sourceRunId of candidateRunIds) { + let source: { receipt?: unknown; state?: unknown } | undefined = + input.providerPackAdmissionSource?.runId === sourceRunId ? input.providerPackAdmissionSource : undefined; + if (!source && input.db && typeof input.db.select === "function") { + try { + source = (await input.db.select({ + receipt: sql`${heartbeatRuns.runnerProfileJson}->'nativeProviderPackAdmission'`, + state: sql`${heartbeatRuns.runnerProfileJson}->'nativeProviderPackAdmissionState'`, + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, sourceRunId), + eq(heartbeatRuns.companyId, input.execution.binding.companyId), + eq(heartbeatRuns.agentId, input.execution.binding.agentId), + eq(heartbeatRuns.runtimeMode, "native"), + )).limit(1))[0]; + } catch { + source = undefined; + } + } + const verified = verifiedProviderPackAdmissionReceipt({ + receipt: source?.receipt, + state: source?.state, + companyId: input.execution.binding.companyId, + agentId: input.execution.binding.agentId, + runId: sourceRunId, + sessionId, + runnerInstanceId: sourceRunId === input.remoteWarmRecovery?.identity.runId + ? input.remoteWarmRecovery.identity.runnerInstanceId + : effectiveRunnerInstanceId, + environmentLeaseId: sourceRunId === input.remoteWarmRecovery?.identity.runId + ? input.remoteWarmRecovery.identity.environmentLeaseId + : effectiveEnvironmentLeaseId, + }); + if (verified) return verified; + } + return undefined; + }; + const useInstalledProviderPack = async (onImmutableRejected?: (error: unknown) => void) => { const expected = expectedProviderPackManifest; if (!expected || !remoteTarget || !remoteCommandRunner) return false; + const admittedReceipt = await loadAdmittedProviderPackReceipt(); for (const installation of remoteNativeArtifacts?.providerPackInventory() ?? []) { try { const manifest = await measureNativeRunnerSpan(input.trace, "provider_pack.compatibility", () => verifyRemoteProviderPackIdentity({ @@ -17479,14 +17536,29 @@ async function createRunnerdBackendWithinSessionClaim( requireExactIdentity: retainProviderPack || explicitProviderPackSelection, requireCurrentOpenCodeProxy: !retainProviderPack && runnerEnvironment?.PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS === "1", + ...(admittedReceipt ? { admittedReceipt } : {}), }), { attributes: { target: installation.root === stagedRemoteProviderPackRoot ? "workspace" : "image" } }); - if (!retainProviderPack) providerPackAuthority!.select(manifest); + if (!retainProviderPack) { + providerPackAuthority!.select(manifest); + } else if (admittedReceipt && providerPackAuthority && manifest.digest !== providerPackAuthority.manifest.digest) { + const preservedRunner = providerPackAuthority.runnerArtifact; + providerPackAuthority = resolveRemoteProviderPackAuthority({ + stateDirectory: root, + binding: providerPackAuthorityBinding(), + reattach: false, + retainProviderPack: false, + runnerArtifact: () => preservedRunner, + current: () => manifest, + }); + providerPackAuthorityFromFallback = false; + } expectedProviderPackManifest = manifest; activeRemoteProviderPackRoot = installation.root; providerPackVerified = true; return true; } catch (error) { if (error instanceof Error && error.name === "AbortError") throw error; + if (installation.immutable) onImmutableRejected?.(error); } } return false; @@ -17509,13 +17581,30 @@ async function createRunnerdBackendWithinSessionClaim( return; } await remoteNativeArtifacts?.verifyRemoteRunner(requiredMode, undefined, true); - if (requiresRemoteProviderPack && await useInstalledProviderPack()) { + if (artifactStorage && providerArtifacts) { + providerPackVerified = true; remotePrepared = true; return; } - if (requiresRemoteProviderPack && stagedRemoteProviderPackRoot) { - await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); - activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; + if (requiresRemoteProviderPack) { + let immutableRejection: unknown = null; + if (await useInstalledProviderPack(error => { immutableRejection ??= error; })) { + remotePrepared = true; + return; + } + if (stagedRemoteProviderPackRoot) { + try { + await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); + } catch (error) { + if (immutableRejection && isMissingProviderPackBinaryError(error)) { + throw immutableRejection; + } + throw error; + } + activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; + } else if (immutableRejection) { + throw immutableRejection; + } } remotePrepared = true; return; @@ -17571,7 +17660,8 @@ async function createRunnerdBackendWithinSessionClaim( signal: providerArtifactsSignal() }); const bootstrap = activeRemoteProviderPackRoot ? { root: activeRemoteProviderPackRoot, manifest: expectedProviderPackManifest } - : remoteNativeArtifacts?.providerPackInventory().find(pack => pack.immutable); + : remoteNativeArtifacts?.providerPackInventory().find(pack => + pack.immutable && typeof (pack.manifest as RemoteProviderPackManifest | null)?.payload?.artifacts?.nodeCommand?.path === "string"); if (!bootstrap) throw new Error("native_provider_artifacts_bootstrap_unavailable"); const bootstrapManifest = bootstrap.manifest as RemoteProviderPackManifest; openCodeLaunchArtifacts = await prepareRemoteOpenCodeArtifacts({ runner: remoteCommandRunner, @@ -18763,12 +18853,20 @@ async function createRunnerdBackendWithinSessionClaim( signalVerifiedRecoveryProcess(localRecoveryProcess, signal), } : undefined; - if (adoptingPersistedRemoteRunner && !adoptedProcess && requiresRemoteProviderPack) { + if (input.restartRecovery?.kind === "reattach_remote_runner" && !adoptedProcess && requiresRemoteProviderPack) { // Bind the relaunch to the pack this session was admitted with (the saved // authority, verified as an exact installed identity), never a newer one. relaunchesSettledRemoteRunner = true; - providerPackAuthority = selectProviderPackAuthority(true); - expectedProviderPackManifest = providerPackAuthority?.manifest ?? expectedProviderPackManifest; + if (artifactStorage && !providerArtifacts && durableBinding !== null && durableIdentityMatchesSession(durableIdentity, input.execution)) { + providerArtifacts = await recordedSessionProviderArtifacts(input.db, input.execution, durableIdentity.runId); + if (providerArtifacts) legacyProviderContinuity = false; + } + if (adoptingPersistedRemoteRunner || providerArtifacts) { + providerPackAuthority = selectProviderPackAuthority(true); + expectedProviderPackManifest = providerPackAuthority?.manifest + ?? providerArtifacts?.manifest as RemoteProviderPackManifest + ?? expectedProviderPackManifest; + } } if (adoptedProcess && remoteTarget) { const markSpawned = resolveRemoteRunnerProcessSpawned as (() => void) | null; diff --git a/server/src/services/native-runtime/provider-pack-compatibility.ts b/server/src/services/native-runtime/provider-pack-compatibility.ts index a7379f43131..0efc8f7b373 100644 --- a/server/src/services/native-runtime/provider-pack-compatibility.ts +++ b/server/src/services/native-runtime/provider-pack-compatibility.ts @@ -30,20 +30,32 @@ export function providerPackIncompatible(check: string, detail: string): Error & export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean }; export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string }; +export type AdmittedProviderPackReceipt = { + providerPackDigest: string; + opencodeProxySha256: string; + sourceRevision: string; +}; export function compatibleProviderPackInstallation( installation: ProviderPackInstallation, expected: T, packRoot: string, provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean, + admittedReceipt?: AdmittedProviderPackReceipt, ): T { const actual = installation.manifest as T | null; const payload = actual?.payload; const contract = expected.payload.compatibility?.[provider.kind]; + const pinnedReceipt = requireExactIdentity ? admittedReceipt : undefined; + const matchesPinnedReceipt = pinnedReceipt !== undefined + && actual?.digest === pinnedReceipt.providerPackDigest + && payload?.artifacts?.opencodeProxy?.sha256 === pinnedReceipt.opencodeProxySha256 + && payload?.runnerSourceRevision === pinnedReceipt.sourceRevision; const failed = !installation.immutable ? "installation_unprotected" : installation.root !== packRoot ? "installation_root" : !payload ? "manifest_missing" : actual.schema !== expected.schema ? "schema" : actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest" : canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target" + : pinnedReceipt ? (!matchesPinnedReceipt ? "exact_identity" : null) : requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null) : !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing" : payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision" @@ -69,7 +81,12 @@ export function compatibleProviderPackInstallation (installed as Record)[key] !== (selected as Record)[key])) { throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible"); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts index 4097b212c07..b532ad5ef4b 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts @@ -329,4 +329,40 @@ describe("installed provider pack compatibility", () => { expect(execute).not.toHaveBeenCalled(); }); + it("re-pins an immutable installation from a durable admittedReceipt across controller releases while rejecting mismatches and unprotected paths", async () => { + const admitted = manifest("a"); + admitted.payload.contractDigest = sha("old-contracts"); + admitted.payload.acpxProfileDigests = { claude: sha("old-claude") }; + const sealedAdmitted = reseal(admitted); + const deployed = manifest("b"); + deployed.payload.contractDigest = sha("new-contracts"); + deployed.payload.acpxProfileDigests = { claude: sha("new-claude") }; + const sealedDeployed = reseal(deployed); + const receipt = { + providerPackDigest: sealedAdmitted.digest, + opencodeProxySha256: sealedAdmitted.payload.artifacts.opencodeProxy!.sha256, + sourceRevision: sealedAdmitted.payload.runnerSourceRevision, + }; + const execute = vi.fn(); + const baseInput = { + runner: { execute }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack", + manifest: sealedDeployed, + installation: { root: "/opt/paperclip-runner/provider-pack", manifest: sealedAdmitted, immutable: true }, + requireExactIdentity: true, + admittedReceipt: receipt, + }; + await expect(verifyRemoteProviderPack({ ...baseInput, provider: { kind: "opencode" } })).resolves.toEqual(sealedAdmitted); + await expect(verifyRemoteProviderPack({ ...baseInput, provider: { kind: "acpx", agent: "claude" } })).resolves.toEqual(sealedAdmitted); + await expect(verifyRemoteProviderPack({ ...baseInput, provider: { kind: "acpx", agent: "codex" } })) + .rejects.toMatchObject({ failureCheck: "acpx_profile" }); + await expect(verifyRemoteProviderPack({ ...baseInput, provider: { kind: "opencode" }, + installation: { ...baseInput.installation, immutable: false } })).rejects.toMatchObject({ failureCheck: "installation_unprotected" }); + await expect(verifyRemoteProviderPack({ ...baseInput, provider: { kind: "opencode" }, + admittedReceipt: { ...receipt, providerPackDigest: sha("other-pack") } })).rejects.toMatchObject({ failureCheck: "exact_identity" }); + const tampered = { ...sealedAdmitted, payload: { ...sealedAdmitted.payload, runnerSourceRevision: "c".repeat(40) } }; + await expect(verifyRemoteProviderPack({ ...baseInput, provider: { kind: "opencode" }, + installation: { ...baseInput.installation, manifest: tampered } })).rejects.toMatchObject({ failureCheck: "manifest_digest" }); + expect(execute).not.toHaveBeenCalled(); + }); + }); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index 021fec76fbd..10137a14a83 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -4,9 +4,9 @@ import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/com import { runRemoteProviderVerification } from "./remote-provider-pack.js"; import { canonicalProviderPackJson, providerPackIncompatible, compatibleProviderPackInstallation, - type ProviderPackIdentity, type ProviderPackInstallation, type PackProvider } from "./provider-pack-compatibility.js"; + type ProviderPackIdentity, type ProviderPackInstallation, type PackProvider, type AdmittedProviderPackReceipt } from "./provider-pack-compatibility.js"; export { canonicalProviderPackJson, providerPackIncompatible, type ProviderPackIdentity, - type ProviderPackInstallation, type PackProvider } from "./provider-pack-compatibility.js"; + type ProviderPackInstallation, type PackProvider, type AdmittedProviderPackReceipt } from "./provider-pack-compatibility.js"; async function withProviderPackCheck(step: "pack" | "opencode", verify: () => Promise): Promise { try { @@ -20,7 +20,6 @@ async function withProviderPackCheck(step: "pack" | "opencode", verify: () => } } - /** * A Node expression defining `packIdentity(root)`: a digest of the kernel * identity of every entry under the pack's real root (path, mode, device, @@ -50,7 +49,7 @@ function sealKeyFor(seal: { targetKey: string } | undefined, packRoot: string, m const reportedIdentity = (stdout: string) => /paperclip-pack-identity=([a-f0-9]{64})/.exec(stdout)?.[1] ?? null; -export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false, seal }: { +export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false, admittedReceipt, seal }: { runner: CommandManagedRuntimeRunner; cwd: string; packRoot: string; @@ -60,6 +59,7 @@ export async function verifyRemoteProviderPack({ requireExactIdentity?: boolean; requireCurrentOpenCodeProxy?: boolean; acceptProvenance?: boolean; + admittedReceipt?: AdmittedProviderPackReceipt; /** * The exact sandbox this pack sits on. After one full verification the * server keeps the pack's kernel identity; later runs on the same sandbox @@ -69,7 +69,7 @@ export async function verifyRemoteProviderPack({ }): Promise { if (installation) { if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required"); - return compatibleProviderPackInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy); + return compatibleProviderPackInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy, admittedReceipt); } const providerNodeCommand = posix.join( packRoot, diff --git a/server/src/services/native-runtime/remote-provider-pack.test.ts b/server/src/services/native-runtime/remote-provider-pack.test.ts index 2e06ba4a490..d7f3609e70e 100644 --- a/server/src/services/native-runtime/remote-provider-pack.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack.test.ts @@ -4,7 +4,7 @@ import { promisify } from "node:util"; import { createNativeRunTrace } from "./native-run-trace.js"; import { COPILOT_CLOSURE_SHA256 } from "../../vendor/paperclip-runner/index.js"; import { readFileSync } from "node:fs"; -import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, antigravityProviderPackEntryRefusal, COPILOT_PROVIDER_PACK_CLOSURES, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, type RemoteProviderPackRelease, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, antigravityProviderPackEntryRefusal, COPILOT_PROVIDER_PACK_CLOSURES, isMissingProviderPackBinaryError, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, type RemoteProviderPackRelease, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets, verifiedProviderPackAdmissionReceipt } from "./remote-provider-pack.js"; describe("remote provider verification", () => { const ok = { exitCode: 0, timedOut: false, stdout: "verified", stderr: "", signal: null }; @@ -299,3 +299,72 @@ describe("standard remote provider pack discovery", () => { expect(verifyAndLink).toHaveBeenCalledTimes(2); }); }); + +describe("durable provider-pack admission receipt validation", () => { + const identity = { + companyId: "company-1", agentId: "agent-1", runId: "run-1", sessionId: "session-1", + runnerInstanceId: "runner-1", environmentLeaseId: "lease-1", + }; + const validState = { + schema: "paperclip.native-provider-pack-admission-state.v1", + state: "verified", + admissionEpoch: "12345678-1234-1234-1234-1234567890ab", + }; + const validReceipt = { + schema: "paperclip.native-provider-pack-admission.v1", + stage: "session_admitted", + authority: "core_verified_selection", + companyId: identity.companyId, + agentId: identity.agentId, + runId: identity.runId, + sessionId: identity.sessionId, + runnerInstanceId: identity.runnerInstanceId, + runnerEnvironmentLeaseId: identity.environmentLeaseId, + providerPackDigest: `sha256:${"a".repeat(64)}`, + opencodeProxySha256: `sha256:${"b".repeat(64)}`, + sourceRevision: "c".repeat(40), + }; + + it("extracts exact digests from a verified matching admission receipt", () => { + expect(verifiedProviderPackAdmissionReceipt({ ...identity, receipt: validReceipt, state: validState })).toEqual({ + providerPackDigest: validReceipt.providerPackDigest, + opencodeProxySha256: validReceipt.opencodeProxySha256, + sourceRevision: validReceipt.sourceRevision, + }); + }); + + it.each([ + ["pending state", { state: { ...validState, state: "pending" } }], + ["unknown state", { state: { ...validState, state: "unknown" } }], + ["missing state", { state: null }], + ["extra state key", { state: { ...validState, extra: true } }], + ["different runId", { receipt: { ...validReceipt, runId: "other-run" } }], + ["different runnerInstanceId", { receipt: { ...validReceipt, runnerInstanceId: "other-runner" } }], + ["different lease", { receipt: { ...validReceipt, runnerEnvironmentLeaseId: "other-lease" } }], + ["different session", { receipt: { ...validReceipt, sessionId: "other-session" } }], + ["extra receipt key", { receipt: { ...validReceipt, extra: true } }], + ["dirty sourceRevision", { receipt: { ...validReceipt, sourceRevision: `${"c".repeat(40)}-dirty` } }], + ["malformed digest", { receipt: { ...validReceipt, providerPackDigest: "sha256:short" } }], + ])("refuses %s", (_label, override) => { + expect(verifiedProviderPackAdmissionReceipt({ ...identity, receipt: validReceipt, state: validState, ...override })).toBeNull(); + }); + + it("identifies only exitCode=127 pack_verifier_failed errors as a missing staged pack binary", () => { + const missing = Object.assign( + new Error("runner_remote_provider_artifact_incompatible: provider pack verification failed (exitCode=127; timedOut=false; signal=none; env: '/w/node': No such file or directory)"), + { failureCheck: "pack_verifier_failed" }, + ); + const mismatch = Object.assign( + new Error("runner_remote_provider_artifact_incompatible: provider pack verification failed (exitCode=3; timedOut=false; signal=none; manifest mismatch)"), + { failureCheck: "manifest_mismatch:runnerSourceRevision" }, + ); + const unavailable = Object.assign( + new Error("runner_remote_provider_verification_unavailable: provider pack verification unavailable after 2 verification attempts"), + { failureCheck: "pack_verifier_unavailable" }, + ); + expect(isMissingProviderPackBinaryError(missing)).toBe(true); + expect(isMissingProviderPackBinaryError(mismatch)).toBe(false); + expect(isMissingProviderPackBinaryError(unavailable)).toBe(false); + expect(isMissingProviderPackBinaryError(new Error("other"))).toBe(false); + }); +}); diff --git a/server/src/services/native-runtime/remote-provider-pack.ts b/server/src/services/native-runtime/remote-provider-pack.ts index ae04605c462..ff4f77b8a79 100644 --- a/server/src/services/native-runtime/remote-provider-pack.ts +++ b/server/src/services/native-runtime/remote-provider-pack.ts @@ -226,3 +226,67 @@ export async function useVerifiedPreinstalledRemoteProviderPack(input: { } return false; } + +const ADMISSION_DIGEST_RE = /^sha256:[a-f0-9]{64}$/; +const ADMISSION_REVISION_RE = /^[a-f0-9]{40}$/; +const ADMISSION_EPOCH_RE = /^[a-f0-9-]{36}$/; +const ADMISSION_RECEIPT_KEYS = new Set([ + "schema", "stage", "authority", "companyId", "agentId", "runId", "sessionId", "runnerInstanceId", + "runnerEnvironmentLeaseId", "providerPackDigest", "opencodeProxySha256", "sourceRevision", "inheritedFromRunId", +]); + +/** + * Validates a DB-persisted provider-pack admission receipt and its verified + * state against the exact execution identity so ephemeral controllers can + * re-pin an immutable image pack after losing local authority files. + */ +export function verifiedProviderPackAdmissionReceipt(input: { + receipt: unknown; + state: unknown; + companyId: string; + agentId: string; + runId: string; + sessionId: string; + runnerInstanceId: string; + environmentLeaseId: string; +}): { providerPackDigest: string; opencodeProxySha256: string; sourceRevision: string } | null { + if (!input.state || typeof input.state !== "object" || Array.isArray(input.state)) return null; + const state = input.state as Record; + if (Object.keys(state).sort().join(",") !== "admissionEpoch,schema,state" + || state.schema !== "paperclip.native-provider-pack-admission-state.v1" + || state.state !== "verified" + || typeof state.admissionEpoch !== "string" || !ADMISSION_EPOCH_RE.test(state.admissionEpoch)) { + return null; + } + if (!input.receipt || typeof input.receipt !== "object" || Array.isArray(input.receipt)) return null; + const receipt = input.receipt as Record; + if (Object.keys(receipt).some(key => !ADMISSION_RECEIPT_KEYS.has(key)) + || receipt.schema !== "paperclip.native-provider-pack-admission.v1" + || receipt.stage !== "session_admitted" + || receipt.authority !== "core_verified_selection" + || receipt.companyId !== input.companyId + || receipt.agentId !== input.agentId + || receipt.runId !== input.runId + || receipt.sessionId !== input.sessionId + || receipt.runnerInstanceId !== input.runnerInstanceId + || receipt.runnerEnvironmentLeaseId !== input.environmentLeaseId + || typeof receipt.providerPackDigest !== "string" || !ADMISSION_DIGEST_RE.test(receipt.providerPackDigest) + || typeof receipt.opencodeProxySha256 !== "string" || !ADMISSION_DIGEST_RE.test(receipt.opencodeProxySha256) + || typeof receipt.sourceRevision !== "string" || !ADMISSION_REVISION_RE.test(receipt.sourceRevision) + || (receipt.inheritedFromRunId !== undefined && (typeof receipt.inheritedFromRunId !== "string" || !receipt.inheritedFromRunId))) { + return null; + } + return { + providerPackDigest: receipt.providerPackDigest, + opencodeProxySha256: receipt.opencodeProxySha256, + sourceRevision: receipt.sourceRevision, + }; +} + +/** True only when pack verification failed because the staged pack's node executable was absent (exitCode=127). */ +export function isMissingProviderPackBinaryError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + return error.message.startsWith("runner_remote_provider_artifact_incompatible:") + && nativeRunFailureCheck(error) === "pack_verifier_failed" + && error.message.includes("exitCode=127;"); +}