Files
PaperClipAI/server/src/services/native-runtime/remote-provider-pack.test.ts
T
DottaandPaperclip 1ad5dd9dce 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>
2026-11-25 04:44:10 -06:00

371 lines
23 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { execFile } from "node:child_process";
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, 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 };
it("lets a transient gateway failure recover before spending the final verification attempt", async () => {
vi.useFakeTimers();
try {
const availableAt = Date.now() + 1_000;
const execute = vi.fn(async () => {
if (Date.now() < availableAt) throw new Error("Request failed with status code 502");
return ok;
});
const result = runRemoteProviderVerification(execute, "pack").then(
value => ({ value }), error => ({ error }),
);
await vi.advanceTimersByTimeAsync(999);
expect(execute).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(1);
expect(await result).toEqual({ value: ok });
expect(execute).toHaveBeenCalledTimes(2);
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});
it("still holds after two gateway failures without scheduling another attempt", async () => {
vi.useFakeTimers();
try {
const execute = vi.fn().mockRejectedValue(new Error("Request failed with status code 502"));
const result = runRemoteProviderVerification(execute, "pack").catch(error => error);
await vi.advanceTimersByTimeAsync(1_000);
expect(await result).toMatchObject({ message: "runner_remote_provider_verification_unavailable: pack unavailable after 2 verification attempts (Request failed with status code 502)" });
await vi.advanceTimersByTimeAsync(60_000);
expect(execute).toHaveBeenCalledTimes(2);
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});
it.each([
{ ...ok, exitCode: null, timedOut: true },
{ ...ok, exitCode: null },
{ ...ok, exitCode: 137, signal: "SIGKILL" },
])("retries an interrupted read without calling it incompatible: %j", async result => {
const execute = vi.fn().mockResolvedValueOnce(result).mockResolvedValueOnce(ok);
await expect(runRemoteProviderVerification(execute, "pack")).resolves.toEqual(ok);
expect(execute).toHaveBeenCalledTimes(2);
});
it("exhausts its own read budget after two inconclusive reads, including empty stderr", async () => {
const execute = vi.fn().mockResolvedValue({ ...ok, exitCode: null, timedOut: true });
await expect(runRemoteProviderVerification(execute, "pack"))
.rejects.toThrow("runner_remote_provider_verification_unavailable: pack unavailable after 2 verification attempts (exitCode=null; timedOut=true");
expect(execute).toHaveBeenCalledTimes(2);
});
it.each(["", "manifest mismatch", "dist tree digest mismatch"])("fails closed without retrying a completed rejection: %s", async stderr => {
const execute = vi.fn().mockResolvedValue({ ...ok, exitCode: 1, stderr });
await expect(runRemoteProviderVerification(execute, "pack")).rejects.toThrow("runner_remote_provider_artifact_incompatible: pack failed (exitCode=1");
expect(execute).toHaveBeenCalledOnce();
});
it("retains a bounded redacted rejection from a combined-output transport", async () => {
const execute = vi.fn().mockResolvedValue({ ...ok, exitCode: 1,
stdout: "Error: manifest mismatch\nANTHROPIC_API_KEY=secret-fixture-value", stderr: "" });
const failure = await runRemoteProviderVerification(execute, "pack").catch(error => error);
expect(failure.message).toContain("manifest mismatch");
expect(failure.message).not.toContain("secret-fixture-value");
expect(execute).toHaveBeenCalledOnce();
});
it("recovers a transport exception and propagates cancellation", async () => {
const execute = vi.fn().mockRejectedValueOnce(new Error("connection unavailable")).mockResolvedValueOnce(ok);
await expect(runRemoteProviderVerification(execute, "pack")).resolves.toEqual(ok);
const abort = new DOMException("cancelled", "AbortError");
execute.mockReset().mockRejectedValue(abort);
await expect(runRemoteProviderVerification(execute, "pack")).rejects.toBe(abort);
expect(execute).toHaveBeenCalledOnce();
});
it("retries after a real timed-out subprocess exits while unrelated work remains responsive", async () => {
let attempts = 0;
let responsive = false;
const unrelated = new Promise<void>(resolve => setTimeout(() => { responsive = true; resolve(); }, 5));
const result = await runRemoteProviderVerification(async () => {
attempts += 1;
try {
const result = await promisify(execFile)(process.execPath, ["-e", attempts === 1 ? "setInterval(()=>{},1000)" : "process.stdout.write('verified')"], { timeout: attempts === 1 ? 100 : 2_000 });
return { ...ok, ...result };
} catch (error) {
const failure = error as Error & { killed: boolean; signal: string; stdout: string; stderr: string };
if (!failure.killed) throw error;
return { ...ok, exitCode: null, timedOut: true, signal: failure.signal, stderr: failure.stderr };
}
}, "pack");
await unrelated;
expect({ attempts, responsive, stdout: result.stdout }).toEqual({ attempts: 2, responsive: true, stdout: "verified" });
});
});
describe("remote provider pack reuse", () => {
it("keeps a verified staged pack without consulting the image or uploading again", async () => {
const usePreinstalled = vi.fn();
const stageAndVerify = vi.fn();
expect(await prepareVerifiedRemoteProviderPack({
verifyStaged: async () => {}, usePreinstalled, stageAndVerify,
})).toBe("staged");
expect(usePreinstalled).not.toHaveBeenCalled();
expect(stageAndVerify).not.toHaveBeenCalled();
});
it.each(["missing pack", "manifest mismatch", "artifact hash mismatch"])(
"replaces a %s with a verified image pack",
async (reason) => {
const stageAndVerify = vi.fn();
expect(await prepareVerifiedRemoteProviderPack({
verifyStaged: async () => { throw new Error(reason); },
usePreinstalled: async () => true,
stageAndVerify,
})).toBe("preinstalled");
expect(stageAndVerify).not.toHaveBeenCalled();
},
);
it("uploads when neither existing pack is valid and fails closed if upload verification fails", async () => {
const stageAndVerify = vi.fn().mockRejectedValue(new Error("artifact hash mismatch"));
const input = {
verifyStaged: async () => { throw new Error("stale staged pack"); },
usePreinstalled: async () => false,
stageAndVerify,
};
await expect(prepareVerifiedRemoteProviderPack(input)).rejects.toThrow("artifact hash mismatch");
stageAndVerify.mockResolvedValue(undefined);
await expect(prepareVerifiedRemoteProviderPack(input)).resolves.toBe("uploaded");
});
it("records on the selection span why the image pack was not reused", async () => {
const trace = createNativeRunTrace({ runId: "provider-pack-select-run", startedAtMs: Date.now() });
const annotate = vi.spyOn(trace, "annotate");
const rejected = Object.assign(new Error("runner_remote_provider_artifact_incompatible: provider pack verification failed"),
{ failureCheck: "manifest_mismatch:runnerSourceRevision" });
await expect(prepareVerifiedRemoteProviderPack({
trace,
verifyStaged: async () => { throw new Error("missing"); },
usePreinstalled: onRejected => useVerifiedPreinstalledRemoteProviderPack({
candidates: ["/opt/paperclip-runner/provider-pack", "/home/operator/.local/share/paperclip-runner/provider-pack"], onRejected,
verifyAndLink: async root => {
throw root.startsWith("/opt/") ? rejected : Object.assign(new Error("missing"), { failureCheck: "manifest_unreadable" });
},
}),
stageAndVerify: async () => {},
})).resolves.toBe("uploaded");
expect(annotate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
stateSource: "uploaded", reason: "cached_packs_unverified", check: "manifest_mismatch:runnerSourceRevision" }));
annotate.mockClear();
await prepareVerifiedRemoteProviderPack({ trace, verifyStaged: async () => { throw new Error("missing"); },
usePreinstalled: async () => false, stageAndVerify: async () => {} });
expect(annotate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ check: "no_preinstalled_pack" }));
});
});
describe("same-content pack reuse across builds", () => {
it.each([
[{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: true }, true],
[{ retainProviderPack: true, explicitProviderPackSelection: false, authoritySelectable: true }, false],
[{ retainProviderPack: false, explicitProviderPackSelection: true, authoritySelectable: true }, false],
[{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: false }, false],
])("allows provenance-only differences only for an unbound run: %j", (input, allowed) => {
expect(providerPackProvenanceReuseAllowed(input)).toBe(allowed);
});
});
describe("ordinary ACPX image artifacts", () => {
const provider = (agent: string) => ({ kind: "acpx", agent, model: "selected-model" } as Parameters<typeof shouldUseBundledAcpxImageAssets>[0]["provider"]);
it.each(["cursor", "copilot", "kimi", "antigravity"])("selects bundled artifacts for remote %s without an operator override", agent => {
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(true);
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: false, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(false);
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: "/explicit/pack", provider: provider(agent) })).toBe(false);
});
it.each(["pi", "claude", "codex", "grok"])("does not change the artifact authority for %s", agent => {
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(false);
});
it("does not admit a non-ACPX provider through bundled image selection", () => {
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: null, provider: { kind: "codex", model: null } })).toBe(false);
});
});
describe("Google Antigravity image pack identity", () => {
const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"));
const profile = { agentServerVersion: "1.4.3", commandDigest: `sha256:${"c".repeat(64)}` };
const patchedClosures = { "linux-x64": "d".repeat(64) };
const entry = { version: profile.agentServerVersion, profileDigest: profile.commandDigest, closureDigest: `sha256:${"d".repeat(64)}` };
const base = { inventory: "providers" as const, target: { platform: "linux", architecture: "x64" }, inBoth: false,
entry, releasePending: false, profile, patchedClosures };
it("admits exactly the patched closures pinned in antigravity-distributions.json, never a vendor closure", () => {
const verified = Object.fromEntries(Object.entries(distributions.platforms as Record<string, { provisioning: string; closureSha256?: string }>)
.filter(([, platform]) => platform.provisioning === "verified-closure").map(([key, platform]) => [key, platform.closureSha256]));
expect(ANTIGRAVITY_PATCHED_CLOSURE_SHA256).toEqual(verified);
for (const [key, closure] of Object.entries(ANTIGRAVITY_PATCHED_CLOSURE_SHA256)) {
expect(closure).not.toBe(distributions.platforms[key].vendorClosureSha256);
}
});
it("admits the real linux-x64 image pack closure and refuses its vendor closure", () => {
const linux = distributions.platforms["linux-x64"];
const real = { ...base, patchedClosures: undefined, entry: { ...entry, closureDigest: `sha256:${linux.closureSha256}` } };
expect(antigravityProviderPackEntryRefusal(real)).toBeNull();
expect(antigravityProviderPackEntryRefusal({ ...real, entry: { ...real.entry, closureDigest: `sha256:${linux.vendorClosureSha256}` } }))
.toMatch(/patched closure/);
expect(antigravityProviderPackEntryRefusal({ ...real, entry: { ...real.entry, closureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}` } }))
.toMatch(/patched closure/);
});
it("lists the qualified entry under providers and the pending one under candidateProviders, never both", () => {
expect(antigravityProviderPackEntryRefusal(base)).toBeNull();
expect(antigravityProviderPackEntryRefusal({ ...base, releasePending: true, inventory: "candidateProviders" })).toBeNull();
expect(antigravityProviderPackEntryRefusal({ ...base, inventory: "candidateProviders" })).toMatch(/wrong pack inventory/);
expect(antigravityProviderPackEntryRefusal({ ...base, releasePending: true })).toMatch(/wrong pack inventory/);
expect(antigravityProviderPackEntryRefusal({ ...base, inBoth: true })).toMatch(/wrong pack inventory/);
});
it.each([
["the vendor closure", { entry: { ...entry, closureDigest: `sha256:${"e".repeat(64)}` } }],
["an unpinned Linux closure", { patchedClosures: {} }],
["another target", { target: { platform: "linux", architecture: "arm64" } }],
["an older profile", { entry: { ...entry, profileDigest: `sha256:${"f".repeat(64)}` } }],
["an older runtime version", { entry: { ...entry, version: "1.4.2" } }],
])("refuses %s", (_name, change) => {
expect(antigravityProviderPackEntryRefusal({ ...base, ...change })).not.toBeNull();
});
});
describe("remote provider pack entry expectation", () => {
const digest = (char: string) => `sha256:${char.repeat(64)}`;
const profile = (version: string, char: string) => ({ agentServerVersion: version, commandDigest: digest(char) });
const release: RemoteProviderPackRelease = {
profiles: { cursor: profile("c1", "1"), copilot: profile("p1", "2"), kimi: { ...profile("k1", "3"), qualificationStatus: "pending" }, antigravity: profile("a1", "4") },
cursorClosures: { "linux-x64": { closureSha256: "5".repeat(64) } },
kimiLinuxX64Closure: "6".repeat(64),
antigravityReleasePending: true,
antigravityPatchedClosures: { "linux-x64": "7".repeat(64) },
};
const target = { platform: "linux", architecture: "x64" };
const all = ["pi", "cursor", "copilot", "kimi", "antigravity"];
const entry = (provider: string, qualification: string, version: string, profileDigest: string, closure: string) => ({
version, profileDigest, closureDigest: `sha256:${closure}`, qualification, path: `provider-assets/${provider}/linux-x64`, sha256: digest("9"),
});
const check = (provider: string, inventory: "providers" | "candidateProviders", value: unknown, listed = { providers: inventory === "providers", candidateProviders: inventory === "candidateProviders" }) =>
remoteProviderPackEntryRefusal({ provider, inventory, allowedProviders: all, target, entry: value, listed, release });
it("checks Copilot against the Runner's canonical closure pins", () => {
expect(COPILOT_PROVIDER_PACK_CLOSURES).toEqual(COPILOT_CLOSURE_SHA256);
expect(Object.keys(COPILOT_PROVIDER_PACK_CLOSURES).sort()).toEqual(["darwin-arm64", "darwin-x64", "linux-x64"]);
});
it("admits each provider's entry only with this release's inventory, qualification, profile and closure", () => {
expect(check("pi", "providers", entry("pi", "qualified", "any", digest("8"), "8".repeat(64)))).toBeNull();
expect(check("cursor", "providers", entry("cursor", "qualified", "c1", digest("1"), "5".repeat(64)))).toBeNull();
expect(check("copilot", "providers", entry("copilot", "qualified", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!))).toBeNull();
expect(check("copilot", "candidateProviders", entry("copilot", "pending", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!))).toBeNull();
expect(check("kimi", "candidateProviders", entry("kimi", "pending", "k1", digest("3"), "6".repeat(64)))).toBeNull();
expect(check("antigravity", "candidateProviders", entry("antigravity", "pending", "a1", digest("4"), "7".repeat(64)))).toBeNull();
});
it("refuses with the same reasons the pack verifier reports", () => {
expect(check("grok", "providers", entry("grok", "qualified", "g", digest("1"), "1".repeat(64)))).toBe("invalid candidate identity");
expect(check("antigravity", "providers", entry("antigravity", "qualified", "a1", digest("4"), "7".repeat(64)))).toBe("invalid candidate identity");
expect(check("cursor", "providers", { ...entry("cursor", "qualified", "c1", digest("1"), "5".repeat(64)), extra: true })).toBe("invalid candidate identity");
expect(check("cursor", "providers", entry("cursor", "qualified", "c0", digest("1"), "5".repeat(64)))).toBe("Cursor profile or closure does not match this release");
expect(check("copilot", "providers", entry("copilot", "qualified", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!), { providers: true, candidateProviders: true }))
.toBe("Copilot profile or closure does not match this release");
expect(check("kimi", "candidateProviders", entry("kimi", "pending", "k1", digest("3"), "6".repeat(64)), { providers: true, candidateProviders: true }))
.toBe("Kimi profile or closure does not match this release");
expect(check("antigravity", "candidateProviders", entry("antigravity", "pending", "a1", digest("4"), "e".repeat(64))))
.toBe("Antigravity closure is not this release's patched closure");
});
});
describe("standard remote provider pack discovery", () => {
const roots = ["/opt/paperclip-runner/provider-pack", "/home/operator/.local/share/paperclip-runner/provider-pack"];
it.each(["old manifest", "modified artifact", "failed link"])("tries the matching home pack after %s rejects /opt", async reason => {
const verifyAndLink = vi.fn(async (root: string) => {
if (root === roots[0]) throw new Error(reason);
});
await expect(useVerifiedPreinstalledRemoteProviderPack({ candidates: roots, verifyAndLink })).resolves.toBe(true);
expect(verifyAndLink.mock.calls.map(([root]) => root)).toEqual(roots);
});
it("keeps the first matching pack without consulting another installation", async () => {
const verifyAndLink = vi.fn(async () => {});
await expect(useVerifiedPreinstalledRemoteProviderPack({ candidates: roots, verifyAndLink })).resolves.toBe(true);
expect(verifyAndLink).toHaveBeenCalledExactlyOnceWith(roots[0]);
});
it("fails closed when every standard installation is incompatible", async () => {
const verifyAndLink = vi.fn().mockRejectedValue(new Error("manifest mismatch"));
await expect(useVerifiedPreinstalledRemoteProviderPack({ candidates: roots, verifyAndLink })).resolves.toBe(false);
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);
});
});