fix(runner): preserve admitted remote provider pack across reattach and relaunch (#22850)

## 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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-25 04:44:10 -06:00
1 parent 9bb4789c57
commit 1ad5dd9dce
7 files changed
+844 -31

No files matched your search

@@ -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<typeof buildPackManifest>;
imageImmutable?: boolean;
currentManifest: ReturnType<typeof buildPackManifest>;
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<typeof createRunnerdBackend>[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<string, unknown>) => {
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<string, unknown>) => {
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<string, unknown>),
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<string, unknown>),
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<string, unknown>),
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 });