Files
PaperClipAI/server/src/services/native-runtime/remote-provider-pack-verification.test.ts
T
Dotta 8e8c1b9f4d fix(sandbox): scope staged provider-pack assets per provider and default Daytona disk to 20 GiB (#22981)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agents run inside remote Daytona sandboxes that require a
verified Runner provider pack
> - When a sandbox stages the provider pack into its workspace,
Paperclip copies, transfers, and verifies every
`provider-assets/<provider>` closure (~1.6 GB across pi, cursor,
copilot, kimi, and antigravity) even when the run only uses Claude,
Codex, OpenCode, or one provider
> - New image-backed Daytona sandbox environments also default to a 10
GiB disk, which leaves too little headroom for repository installs and
tests
> - This pull request stages and verifies only the
`provider-assets/<provider>` tree needed by the active run and raises
the Daytona plugin default disk size from 10 GiB to 20 GiB
> - The benefit is significantly more free workspace disk space, smaller
pack transfers, and safer default disk sizing without changing the
provider-pack archive format or breaking multi-provider workspace reuse

## Linked Issues or Issue Description

- Fixes: #19367
- Refs #19484
- Related: #19500 (ENOSPC fail-fast and full-sandbox recovery already
merged in #22068, #22239, #22383, #22466, and #22837), #22241
(deduplicated repeated bytes in staged packs)

## What Changed

- `server/src/services/native-runtime/provider-pack-compatibility.ts`:
add `requiredProviderAssetNames`, `isProviderAssetPathIncluded`, and
`providerAssetExcludeArgs` helpers that resolve the required
`provider-assets/<provider>` subset for a `PackProvider` (returning
unfiltered behavior when `provider` is omitted).
- `server/src/services/native-runtime/provider-pack-layers.ts`: filter
large layer entries by required provider assets before running the
remote reuse script and transferring missing layers, preserve
cross-provider image-twin reuse so core files can still reuse identical
bytes from excluded provider paths in the base image, and pass
`--exclude` flags to GNU `tar` for `overlay.tar.zst`.
- `server/src/services/native-runtime/provider-pack-archive.ts` and
`provider-pack-upload.ts`: forward `provider` and `manifest` into v1 and
v2 archive staging and exclude unused `provider-assets/*` during
extraction.
-
`server/src/services/native-runtime/remote-provider-pack-verification.ts`:
scope candidate asset tree digest checks to the active provider when
`provider` is passed and include `requiredAssets` in the verification
seal key so a pack verified for one provider cannot satisfy a seal check
for a different provider.
- `server/src/services/native-runtime/native-session-executor.ts` and
`server/src/services/kimi-connection-probe.ts`: pass the active
`PackProvider` to `prepareRemoteProviderPackOnTarget` and
`verifyRemoteProviderPackIdentity`.
- `packages/plugins/sandbox-providers/daytona/src/manifest.ts` and
`package.json`: raise the default `disk` allocation from `10` to `20`
GiB and bump the plugin version from `0.1.10` to `0.1.11` so
bundled-plugin boot reconciliation refreshes persisted manifests.
- Added unit and end-to-end tests in
`packages/plugins/sandbox-providers/daytona/src/plugin.test.ts`,
`server/src/services/native-runtime/provider-pack-archive.test.ts`,
`server/src/services/native-runtime/remote-provider-pack-verification.test.ts`,
and updated `server/src/__tests__/kimi-connection-probe.test.ts`.

## Verification

- **RED (before production edits):**
- `cd packages/plugins/sandbox-providers/daytona && npx vitest run
--config vitest.config.ts -t "bumps the plugin version|pre-fills
sizing|validates and passes the default 20 GiB"` — 3 failed (`0.1.10 !==
0.1.11`, `10 !== 20`).
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts -t "omits all
provider-assets|stages only the selected provider"` — 2 failed (unused
`provider-assets` staged on disk).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts -t
"verifies only the selected provider"` — 1 failed (`candidate_digest`
rejected Claude when `provider-assets/` was absent).
- **GREEN (after fix):**
  - `cd server && npx tsc --noEmit -p tsconfig.json` — passed.
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts` — **56/56
passed**, including an end-to-end upload+verify test proving unfiltered
staging writes >= 6 MiB of provider assets, Claude staging omits all 6
MiB (< 256 KiB total) and verifies cleanly, and switching the same
workspace to Cursor rejects the Claude seal (`candidate_digest`) and
re-stages only Cursor (2 MiB, excluding Kimi and Pi).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts
src/services/native-runtime/remote-provider-pack.test.ts
src/services/native-runtime/retained-provider-pack-source.test.ts
src/__tests__/kimi-connection-probe.test.ts` — all passed
(`remote-provider-pack-verification.test.ts` 34/34,
`remote-provider-pack.test.ts` 60/60, `kimi-connection-probe.test.ts`
39/39, `retained-provider-pack-source.test.ts` all passed).
- `cd packages/plugins/sandbox-providers/daytona && pnpm typecheck &&
npx vitest run --config vitest.config.ts` — typecheck passed; all 15
offline test files passed (641 passed, 8 live tests skipped;
`archive-stream-window.test.ts` timed out once during parallel CPU
contention and passed in 6.17s when re-run).
- `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/provider-pack-archive.test.ts
server/src/services/native-runtime/remote-provider-pack-verification.test.ts
server/src/__tests__/kimi-connection-probe.test.ts` — passed (110
nightly suites validated, 3 test files checked).
- `pnpm verify --base 2d06567795
--explain` exited 2 because
`packages/plugins/sandbox-providers/daytona/package.json` is a global CI
input; focused suites and package typechecks ran locally and sharded PR
CI supplies broad coverage.
- **Not run locally:** Live Daytona sandbox provisioning (requires
`DAYTONA_API_KEY`). Managed Cloud snapshot disk sizing is updated
separately in the Cloud repository.

## Risks

- Low risk. Archive schema v1 and v2 remain unchanged, so existing
Docker images and retained OCI release packs work without rebuilding.
- If a reusable workspace previously staged a pack for one provider (for
example Claude) and a later run on the same workspace uses a provider
with native assets (for example Cursor), the provider-scoped
verification seal misses, `verifyStaged` fails with `candidate_digest`,
and `prepareRemoteProviderPackOnTarget` cleanly re-stages with the
needed provider assets.
- Raising the Daytona plugin default `disk` to 20 GiB only affects new
image-backed environments created with the form default; existing saved
environments and snapshot-backed environments keep their existing
configuration.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Google Gemini (Antigravity agent) with shell, file editing, and local
test execution tools.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-11-25 15:33:44 -06:00

476 lines
31 KiB
TypeScript

import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { mkdir, mkdtemp, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { promisify } from "node:util";
import { readFileSync } from "node:fs";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { describe, expect, it, vi } from "vitest";
import { canonicalProviderPackJson, clearSealedProviderPacksForTest, PROVIDER_PACK_IDENTITY_FUNCTION, verifyRemoteProviderPack, type ProviderPackIdentity } from "./remote-provider-pack-verification.js";
const sha = (text: string) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
const manifest = (revision: string): ProviderPackIdentity => {
const payload = {
compatibility: { opencode: 1, acpx: 1 },
contractDigest: sha("contracts"),
pins: { opencode: "1.18.34", nodeMinimum: "24.11.0" },
target: { platform: "linux", architecture: "x64" },
runnerSourceRevision: revision.repeat(40),
artifacts: Object.fromEntries(Object.entries({
nodeCommand: "node_modules/node/bin/node", opencodeCommand: "node_modules/.bin/opencode",
productionLock: "pnpm-lock.yaml", opencodeExecutable: "node_modules/opencode-ai/bin/opencode.exe",
opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs",
grokLauncher: "dist/providers/grok/launcher.cjs",
}).map(([name, path]) => [name, { path, sha256: sha(`${revision}-${name}`) }])) as ProviderPackIdentity["payload"]["artifacts"],
};
return { schema: "paperclip-runner/remote-provider-pack/v1", payload, digest: sha(canonicalProviderPackJson(payload)) };
};
describe("installed provider pack compatibility", () => {
it("finishes both startup checks when a gateway recovers between verification attempts", async () => {
vi.useFakeTimers();
try {
const expected = manifest("b");
const availableAt = Date.now() + 1_000;
const execute = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
if (Date.now() < availableAt) throw new Error("Request failed with status code 502");
return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "",
stdout: request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n` : "verified" };
});
const verification = verifyRemoteProviderPack({ runner: { execute }, cwd: "/workspace",
packRoot: "/workspace/provider-pack", manifest: expected }).then(value => ({ value }), error => ({ error }));
await vi.advanceTimersByTimeAsync(999);
expect(execute).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(1);
expect(await verification).toEqual({ value: expected });
expect(execute).toHaveBeenCalledTimes(3);
expect(execute.mock.calls[2][0].args).toEqual(["--version"]);
} finally {
vi.useRealTimers();
}
});
it("reuses a protected pack across app revisions without executing verification commands", async () => {
const installed = manifest("a");
const current = structuredClone(installed);
current.payload.runnerSourceRevision = "b".repeat(40);
current.digest = sha(canonicalProviderPackJson(current.payload));
const root = await mkdtemp(join(tmpdir(), "installed-pack-compatibility-"));
await mkdir(dirname(join(root, installed.payload.artifacts.nodeCommand.path)), { recursive: true });
await symlink(process.execPath, join(root, installed.payload.artifacts.nodeCommand.path));
await writeFile(join(root, "provider-pack.json"), JSON.stringify(installed));
const execute = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
try {
const result = await promisify(execFile)(request.command, request.args ?? [], { cwd: root, timeout: 2_000 });
return { ...result, exitCode: 0, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString() };
} catch (error) {
const failed = error as Error & { code: number; stdout: string; stderr: string };
if (typeof failed.code !== "number") throw error;
return { stdout: failed.stdout, stderr: failed.stderr, exitCode: failed.code, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString() };
}
});
const input = { runner: { execute }, cwd: root, packRoot: root, manifest: current };
try {
// Exercise the old complete-manifest comparison in a real Node process.
// Only provenance changed; provider bytes and interface are identical.
await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({
message: expect.stringContaining("manifest mismatch"), failureCheck: "manifest_mismatch:runnerSourceRevision" });
expect(execute).toHaveBeenCalledOnce();
// The sealing variant of the verifier runs the same checks in a real Node process.
await expect(verifyRemoteProviderPack({ ...input, seal: { targetKey: "sandbox:env:real" } })).rejects.toMatchObject({
failureCheck: "manifest_mismatch:runnerSourceRevision" });
await expect(verifyRemoteProviderPack({ ...input, manifest: installed, seal: { targetKey: "sandbox:env:real" } })).rejects.toMatchObject({
failureCheck: "artifact_digest:nodeCommand" });
await expect(verifyRemoteProviderPack({ ...input, manifest: installed })).rejects.toMatchObject({
message: expect.stringContaining("nodeCommand digest mismatch"), failureCheck: "artifact_digest:nodeCommand" });
await rm(join(root, "provider-pack.json"));
await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({ failureCheck: "manifest_unreadable" });
const combined = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
const result = await execute(request);
return { ...result, stdout: `${result.stdout}${result.stderr}`, stderr: "" };
});
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: combined } }))
.rejects.toMatchObject({ failureCheck: "manifest_unreadable" });
await writeFile(join(root, "provider-pack.json"), JSON.stringify(installed));
execute.mockClear();
const selected = await verifyRemoteProviderPack({ ...input,
installation: { root, manifest: installed, immutable: true }, provider: { kind: "opencode" } });
expect(selected).toEqual(installed);
expect(execute).not.toHaveBeenCalled();
} finally {
await rm(root, { recursive: true, force: true });
}
});
const reseal = (pack: ProviderPackIdentity) => ({ ...pack, digest: sha(canonicalProviderPackJson(pack.payload)) });
const check = (installed: ProviderPackIdentity, options: { immutable?: boolean; requireExactIdentity?: boolean; requireCurrentOpenCodeProxy?: boolean } = {}) => {
const execute = vi.fn();
return verifyRemoteProviderPack({ runner: { execute }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack",
manifest: manifest("b"), installation: { root: "/opt/paperclip-runner/provider-pack", manifest: installed, immutable: options.immutable ?? true },
provider: { kind: "opencode" }, requireExactIdentity: options.requireExactIdentity,
requireCurrentOpenCodeProxy: options.requireCurrentOpenCodeProxy });
};
it.each([
["interface", "compatibility_revision"], ["contracts", "contract_digest"], ["platform", "target"], ["schema", "schema"],
["artifact_path", "artifact:nodeCommand"], ["digest", "manifest_digest"], ["legacy", "compatibility_revision"],
["legacy_contracts", "contract_digest_missing"],
])("names the failed check for an incompatible %s", async (field, failureCheck) => {
let pack = manifest("a");
if (field === "interface") pack.payload.compatibility!.opencode += 1;
if (field === "contracts") pack.payload.contractDigest = sha("other-contracts");
if (field === "legacy") delete pack.payload.compatibility;
if (field === "legacy_contracts") delete pack.payload.contractDigest;
if (field === "platform") pack.payload.target.architecture = "arm64";
if (field === "schema") pack.schema = "unknown";
if (field === "artifact_path") pack.payload.artifacts.nodeCommand.path = "../node";
pack = reseal(pack);
if (field === "digest") pack.digest = sha("corrupt");
await expect(check(pack)).rejects.toMatchObject({ failureCheck });
});
it("names unprotected, exact-identity and proxy rejections", async () => {
await expect(check(manifest("b"), { immutable: false })).rejects.toMatchObject({ failureCheck: "installation_unprotected" });
await expect(check(manifest("a"), { requireExactIdentity: true })).rejects.toMatchObject({ failureCheck: "exact_identity" });
await expect(check(manifest("a"), { requireCurrentOpenCodeProxy: true })).rejects.toMatchObject({ failureCheck: "opencode_proxy" });
const unpinned = manifest("b");
(unpinned.payload.pins as Record<string, unknown>).opencode = null;
await expect(check(reseal(unpinned))).rejects.toMatchObject({ failureCheck: "opencode_pin_missing" });
});
it.each(["interface", "contracts", "platform", "schema", "artifact_path", "digest", "legacy", "legacy_contracts"])("rejects an incompatible %s", async field => {
let pack = manifest("a");
if (field === "interface") pack.payload.compatibility!.opencode += 1;
if (field === "contracts") pack.payload.contractDigest = sha("other-contracts");
if (field === "legacy") delete pack.payload.compatibility;
if (field === "legacy_contracts") delete pack.payload.contractDigest;
if (field === "platform") pack.payload.target.architecture = "arm64";
if (field === "schema") pack.schema = "unknown";
if (field === "artifact_path") pack.payload.artifacts.nodeCommand.path = "../node";
pack = reseal(pack);
if (field === "digest") pack.digest = sha("corrupt");
await expect(check(pack)).rejects.toThrow("runner_remote_provider_artifact_incompatible");
});
it("accepts a reported installed manifest only when its sealed content equals the expected pack", async () => {
const expected = manifest("b");
const report = (installed: unknown) => vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => ({
exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "",
stdout: request.args?.[0] === "--version" ? "1.18.34\n"
: `\npaperclip-pack-manifest=${Buffer.from(JSON.stringify(installed)).toString("base64")}\n` }));
const input = { cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack", manifest: expected, acceptProvenance: true };
const otherBuild = manifest("b");
otherBuild.payload.runnerSourceRevision = "a".repeat(40);
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(reseal(otherBuild)) } })).resolves.toEqual(reseal(otherBuild));
const otherContent = reseal({ ...otherBuild, payload: { ...otherBuild.payload, contractDigest: sha("other") } });
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(otherContent) } }))
.rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" });
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report({ ...reseal(otherBuild), digest: sha("unsealed") }) } }))
.rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" });
await expect(verifyRemoteProviderPack({ ...input, acceptProvenance: false, runner: { execute: report(reseal(otherBuild)) } }))
.resolves.toEqual(expected);
});
it("does not reuse image packs when the controller's bundled pack records no contract digest", async () => {
const current = manifest("b");
delete current.payload.contractDigest;
const installed = manifest("a");
await expect(verifyRemoteProviderPack({ runner: { execute: vi.fn() }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack",
manifest: reseal(current), installation: { root: "/opt/paperclip-runner/provider-pack", manifest: installed, immutable: true },
provider: { kind: "opencode" } })).rejects.toThrow("interface or installation is incompatible");
});
it("keeps writable installations at the content-verification boundary", async () => {
await expect(check(manifest("b"), { immutable: false })).rejects.toThrow("installation is incompatible");
});
it("does not replace an admitted pack during reattachment", async () => {
await expect(check(manifest("a"), { requireExactIdentity: true })).rejects.toThrow("incompatible");
await expect(check(manifest("b"), { requireExactIdentity: true })).resolves.toEqual(manifest("b"));
});
it("requires the current proxy for requested OpenCode diagnostics", async () => {
const installed = manifest("a");
await expect(check(installed)).resolves.toEqual(installed);
await expect(check(installed, { requireCurrentOpenCodeProxy: true }))
.rejects.toThrow("requested OpenCode diagnostics");
installed.payload.artifacts.opencodeProxy = manifest("b").payload.artifacts.opencodeProxy;
await expect(check(reseal(installed), { requireCurrentOpenCodeProxy: true }))
.resolves.toEqual(reseal(installed));
});
it("ignores unrelated provider and dependency changes for OpenCode", async () => {
const pack = manifest("a");
pack.payload.compatibility!.acpx += 1;
pack.payload.pins.acpx = "different-version";
pack.payload.acpxProfileDigests = { codex: sha("different-codex") };
await expect(check(reseal(pack))).resolves.toEqual(reseal(pack));
});
it("treats the Runner image inputs digest as provenance", async () => {
// A pack built in the Runner image records which image it came from. The
// controller's own pack may record another image, or none.
const pack = manifest("a");
pack.payload.runnerInputsDigest = "c".repeat(64);
await expect(check(reseal(pack))).resolves.toEqual(reseal(pack));
// The field is part of the sealed payload, so it cannot change unnoticed.
await expect(check({ ...reseal(pack), payload: { ...pack.payload, runnerInputsDigest: "d".repeat(64) } }))
.rejects.toThrow("runner_remote_provider_artifact_incompatible");
});
it("checks only the selected ACPX profile", async () => {
const current = manifest("b"), installed = manifest("a");
current.payload.acpxProfileDigests = { claude: sha("claude"), codex: sha("codex") };
installed.payload.acpxProfileDigests = { claude: sha("claude"), codex: sha("other-codex") };
const input = { runner: { execute: vi.fn() }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack",
manifest: reseal(current), installation: { root: "/opt/paperclip-runner/provider-pack", manifest: reseal(installed), immutable: true },
provider: { kind: "acpx" as const, agent: "claude" } };
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(reseal(installed));
await expect(verifyRemoteProviderPack({ ...input, provider: { kind: "acpx", agent: "codex" } })).rejects.toThrow("profile is incompatible");
});
describe("sealed reuse on the same sandbox", () => {
const identityOf = async (root: string) => {
const { stdout } = await promisify(execFile)(process.execPath, ["-e",
`${PROVIDER_PACK_IDENTITY_FUNCTION};process.stdout.write(packIdentity(process.argv[1]))`, root]);
return stdout;
};
it("changes the identity for any same-size rewrite, even with its mtime restored", async () => {
const root = await mkdtemp(join(tmpdir(), "pack-identity-"));
try {
await mkdir(join(root, "dist"));
await writeFile(join(root, "dist", "file.js"), "original");
await symlink(join(root, "dist", "file.js"), join(root, "link.js"));
const sealed = await identityOf(root);
expect(sealed).toMatch(/^[a-f0-9]{64}$/);
expect(await identityOf(root)).toBe(sealed);
const before = await stat(join(root, "dist", "file.js"));
await new Promise(resolve => setTimeout(resolve, 20));
await writeFile(join(root, "dist", "file.js"), "tampered");
await utimes(join(root, "dist", "file.js"), before.atime, before.mtime);
expect(await identityOf(root)).not.toBe(sealed);
} finally { await rm(root, { recursive: true, force: true }); }
});
it("re-checks only the identity on a sealed sandbox and fully re-verifies after any change", async () => {
clearSealedProviderPacksForTest();
const expected = manifest("b");
let identity = "a".repeat(64);
const execute = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
const script = String(request.args?.[1] ?? "");
const stdout = request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n`
: script.includes("paperclip-pack-check") ? `verified\npaperclip-pack-identity=${identity}\n`
: `\npaperclip-pack-identity=${identity}\n`;
return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "", stdout };
});
const kinds = () => execute.mock.calls.map(([request]) => request.args?.[0] === "--version" ? "version"
: String(request.args?.[1]).includes("paperclip-pack-check") ? "full" : "identity");
const input = { runner: { execute }, cwd: "/workspace", packRoot: "/workspace/provider-pack", manifest: expected,
seal: { targetKey: "sandbox:env-1:sandbox-1" } };
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected);
expect(kinds()).toEqual(["full", "version"]);
execute.mockClear();
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected);
expect(kinds()).toEqual(["identity"]);
// Another sandbox, or no sandbox identity, never reuses the seal.
execute.mockClear();
await verifyRemoteProviderPack({ ...input, seal: { targetKey: "sandbox:env-1:sandbox-2" } });
await verifyRemoteProviderPack({ ...input, seal: undefined });
expect(kinds()).toEqual(["full", "version", "full", "version"]);
// A changed identity falls back to the complete verification.
execute.mockClear();
identity = "b".repeat(64);
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected);
expect(kinds()).toEqual(["identity", "full", "version"]);
// A pack that changed while it was hashed reports no identity and is not sealed.
execute.mockClear();
clearSealedProviderPacksForTest();
execute.mockImplementation(async (request) => ({ exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "",
stdout: request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n` : "verified\n" }));
await verifyRemoteProviderPack(input);
await verifyRemoteProviderPack(input);
expect(kinds()).toEqual(["full", "version", "full", "version"]);
});
});
it("rejects the published Grok pack from before native effort admission", async () => {
const profiles = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8"));
const current = manifest("b"), installed = manifest("a");
// Published builtin Grok profile 1 predates grokEffort and grokDisableWebSearch
// in session.open. Its launcher bytes equal today's, so its release digest
// matches; the pack predates contract digests, so that gate refuses it.
const published = "sha256:f0b698395a3704ed2ffaf84ea19bdb20c36c8a0a70b7c629c7b6ffe144e59e55";
expect(profiles.profiles.grok.commandDigest).toBe(published);
installed.payload.acpxProfileDigests = { grok: published };
delete installed.payload.contractDigest;
current.payload.acpxProfileDigests = { grok: profiles.profiles.grok.commandDigest };
const execute = vi.fn();
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack",
manifest: reseal(current), installation: { root: "/opt/paperclip-runner/provider-pack", manifest: reseal(installed), immutable: true },
provider: { kind: "acpx", agent: "grok" } })).rejects.toThrow("interface or installation is incompatible");
expect(execute).not.toHaveBeenCalled();
});
it("rejects an installed pack with another Grok release digest", async () => {
const profiles = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8"));
const current = manifest("b"), installed = manifest("a");
// The last source-bound Grok profile digest.
installed.payload.acpxProfileDigests = { grok: "sha256:5205c2197b94cfbd3e62fbeea027f2e80d092f736ca52656dda2f7044ba9a5ca" };
current.payload.acpxProfileDigests = { grok: profiles.profiles.grok.commandDigest };
const execute = vi.fn();
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack",
manifest: reseal(current), installation: { root: "/opt/paperclip-runner/provider-pack", manifest: reseal(installed), immutable: true },
provider: { kind: "acpx", agent: "grok" } })).rejects.toThrow("selected ACPX provider profile is incompatible");
expect(execute).not.toHaveBeenCalled();
});
it("reuses the current Grok profile across source-only changes and retains exact historical recovery authority", async () => {
const profiles = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8"));
const current = manifest("b"), installed = manifest("a");
for (const pack of [current, installed]) pack.payload.acpxProfileDigests = { grok: profiles.profiles.grok.commandDigest };
const execute = vi.fn();
const input = { runner: { execute }, cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack",
manifest: reseal(current), installation: { root: "/opt/paperclip-runner/provider-pack", manifest: reseal(installed), immutable: true },
provider: { kind: "acpx" as const, agent: "grok" } };
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(reseal(installed));
const historical = manifest("a");
historical.payload.acpxProfileDigests = { grok: "sha256:5205c2197b94cfbd3e62fbeea027f2e80d092f736ca52656dda2f7044ba9a5ca" };
await expect(verifyRemoteProviderPack({ ...input, manifest: reseal(historical),
installation: { ...input.installation, manifest: reseal(historical) }, requireExactIdentity: true })).resolves.toEqual(reseal(historical));
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();
});
it("verifies only the selected provider's asset tree and isolates seals per provider", async () => {
clearSealedProviderPacksForTest();
const root = await mkdtemp(join(tmpdir(), "pack-provider-scoped-verify-"));
try {
const write = async (relative: string, content: string, mode?: number) => {
const full = join(root, relative);
await mkdir(dirname(full), { recursive: true });
await writeFile(full, content, mode ? { mode } : undefined);
};
const shaFile = (content: string) => sha(content);
const treeSha = (fileName: string, content: string) =>
`sha256:${createHash("sha256").update(`file\0${fileName}\0${shaFile(content)}\n`).digest("hex")}`;
await mkdir(join(root, "node_modules/node/bin"), { recursive: true });
await symlink(process.execPath, join(root, "node_modules/node/bin/node"));
const nodeBytes = readFileSync(process.execPath);
const nodeSha = `sha256:${createHash("sha256").update(nodeBytes).digest("hex")}`;
const opencodeScript = "#!/bin/sh\necho 1.18.34\n";
await write("node_modules/.bin/opencode", opencodeScript, 0o755);
await write("pnpm-lock.yaml", "lock");
await write("node_modules/opencode-ai/bin/opencode.exe", "bin");
await write("dist/cli/opencode-app-server-proxy.cjs", "proxy");
await write("dist/cli/acpx-runtime-sidecar.cjs", "sidecar");
await write("dist/providers/grok/launcher.cjs", "grok");
for (const [pkg, version] of [
["acpx", "1.0.0"],
["@agentclientprotocol/claude-agent-acp", "1.0.0"],
["@agentclientprotocol/codex-acp", "1.0.0"],
["opencode-ai", "1.18.34"],
] as const) {
await write(`node_modules/${pkg}/package.json`, JSON.stringify({ version }));
}
const distDigest = `sha256:${createHash("sha256").update([
"directory\0cli\n",
`file\0cli/acpx-runtime-sidecar.cjs\0${shaFile("sidecar")}\n`,
`file\0cli/opencode-app-server-proxy.cjs\0${shaFile("proxy")}\n`,
"directory\0providers\n",
"directory\0providers/grok\n",
`file\0providers/grok/launcher.cjs\0${shaFile("grok")}\n`,
].join("")).digest("hex")}`;
const cursorPath = `provider-assets/cursor/${process.platform}-${process.arch}`;
const kimiPath = `provider-assets/kimi/${process.platform}-${process.arch}`;
const payload = {
compatibility: { opencode: 1, acpx: 1 },
contractDigest: sha("contracts"),
pins: {
opencode: "1.18.34",
nodeMinimum: "20.0.0",
acpx: "1.0.0",
claudeAcp: "1.0.0",
codexAcp: "1.0.0",
},
target: { platform: process.platform, architecture: process.arch },
runnerSourceRevision: "a".repeat(40),
distDigest,
providers: {
cursor: { path: cursorPath, sha256: treeSha("agent", "cursor-v1") },
kimi: { path: kimiPath, sha256: treeSha("agent", "kimi-v1") },
},
artifacts: {
nodeCommand: { path: "node_modules/node/bin/node", sha256: nodeSha },
productionLock: { path: "pnpm-lock.yaml", sha256: shaFile("lock") },
opencodeCommand: { path: "node_modules/.bin/opencode", sha256: shaFile(opencodeScript) },
opencodeExecutable: { path: "node_modules/opencode-ai/bin/opencode.exe", sha256: shaFile("bin") },
opencodeProxy: { path: "dist/cli/opencode-app-server-proxy.cjs", sha256: shaFile("proxy") },
acpxSidecar: { path: "dist/cli/acpx-runtime-sidecar.cjs", sha256: shaFile("sidecar") },
grokLauncher: { path: "dist/providers/grok/launcher.cjs", sha256: shaFile("grok") },
},
};
const expected = {
schema: "paperclip-runner/remote-provider-pack/v1",
payload,
digest: sha(canonicalProviderPackJson(payload)),
};
await write("provider-pack.json", JSON.stringify(expected));
const execute = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
try {
const result = await promisify(execFile)(request.command, request.args ?? [], { cwd: root, timeout: 10_000 });
return { ...result, exitCode: 0, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString() };
} catch (error) {
const failed = error as Error & { code: number; stdout: string; stderr: string };
if (typeof failed.code !== "number") throw error;
return { stdout: failed.stdout, stderr: failed.stderr, exitCode: failed.code, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString() };
}
});
const seal = { targetKey: "sandbox:env-1:scoped-provider" };
// Claude and OpenCode succeed even when provider-assets/ is absent.
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
provider: { kind: "acpx", agent: "claude" }, seal })).resolves.toEqual(expected);
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
provider: { kind: "opencode" }, seal })).resolves.toEqual(expected);
// Cursor must still reject when provider-assets/cursor is missing (and must NOT reuse Claude's seal).
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
provider: { kind: "acpx", agent: "cursor" }, seal })).rejects.toMatchObject({ failureCheck: "candidate_digest" });
// Materializing only Cursor passes Cursor verification while Kimi still rejects.
await write(`${cursorPath}/agent`, "cursor-v1");
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
provider: { kind: "acpx", agent: "cursor" }, seal })).resolves.toEqual(expected);
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
provider: { kind: "acpx", agent: "kimi" }, seal })).rejects.toMatchObject({ failureCheck: "candidate_digest" });
// Omitting provider still checks every declared provider asset tree.
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected, seal }))
.rejects.toMatchObject({ failureCheck: "candidate_digest" });
} finally {
await rm(root, { recursive: true, force: true });
}
});
});