Files
PaperClipAI/server/src/services/native-runtime/remote-provider-pack.test.ts
T
DottaandClaude Fable 5.2 78e4f4f130 feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The native Runner starts each agent harness and owns its lifecycle,
credentials and recovery
> - Google Antigravity is Google's only first-party coding harness, and
it is the harness for Gemini 4 Neon
> - The Runner had an Antigravity integration, but only as a pending
candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only,
closed unless an operator opened it for one company and one model
> - Cloud sandboxes run Linux and use API keys, so the candidate could
not run there, and it had one attended test cell
> - This pull request moves the integration to ACP server 1.5.2, makes
it run on Linux and with a Gemini API key, adds the tests the other ACPX
harnesses have, and removes the code paths that would block recovery
after release
> - The benefit is that the release of Antigravity becomes a small
declaration change after the live suites pass. The profile stays
`pending` in this pull request.

## Linked Issues or Issue Description

Refs #98
Refs #6559
Refs #8523
Refs #21121 (a separate legacy-style `agy_local` adapter that uses the
CLI print protocol; this pull request does not replace or include it)

## What Changed

**Runtime**
- Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is
`1.5.2-paperclip.2`.
- Verified patched closures for `darwin-arm64`, `linux-x64` and
`linux-arm64`. `darwin-x64` stays inventory-only.
- The patcher reads Mach-O and ELF builds. It signs macOS output only.
One admission source serves all platforms.
- Platform gates in TypeScript, Rust, the sidecar schema and the server
admit each host that has a verified closure.

**Auth and models**
- Gemini API-key auth reaches an exact-model session receipt. Admission
accepts a model only when the base model and the thinking level both
match the requested ID.
- API-key connections get a model list on local and cloud environments.
The list is generated at build time from the pinned runtime. The server
starts no process to read it.
- Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker
marks them "needs a paid Gemini API plan" for API-key connections.
- One shared module maps model ID to family and thinking level.
- `google/gemini-4-neon` is added to the OpenCode model list. A new
model audit is in `doc/adapter-model-audit-2026-11-22.md`.

**Lifecycle and failures**
- A provider error no longer completes the turn. The driver classifies
it: overloaded, rate limit, quota, auth rejected, model unavailable.
- Overload retries are bounded (3 attempts, about 14 seconds).
- A refused session reload maps to incompatible saved state, so the
automatic replacement conversation applies.
- Server gates that refused restart recovery, remote targets and shared
state for Antigravity now apply only while the profile is pending.
- A Google sign-in connection with a cloud environment is refused at
save and at Test, with a plain message.
- A released profile rejects candidate grants in TypeScript and in Rust.

**Launch cost and integrity (all native ACPX providers)**
- Each closure is verified one time into a sealed read-only store. Later
launches check file identities and hash the exact executable they start.
- Remote provider-pack verification is recorded per sandbox lease. Later
runs check kernel identity and fall back to the full hash on any
difference.
- Superseded stores are removed in the background after a launch.

**Provider pack and image**
- The provider pack carries Antigravity for `linux-x64` as a candidate
provider. It becomes an ordinary provider from the profile status alone.
- The Daytona image build accepts the candidate. A credential-free smoke
runs in the build.

**Tests and CI**
- New `antigravity-qualification` suite: 24 cells, local and Daytona.
- New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each
cell requires the exact model in the Runner receipt.
- Antigravity can run the `chat-features` cases with `--profile
runner-acpx-antigravity`.
- `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new
profile and derives candidate providers from the selected Daytona cells.

**Docs**
- `doc/plans/2026-11-22-antigravity-qualification.md` is the current
release contract, acceptance ledger and operator recipe.

## Verification

Commands that passed on the final revision:

- `pnpm build`
- Typecheck for all packages, including the runner-e2e test projects
- `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped;
386 node tests passed
- `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199
passed, 2 failed. The 2 failures are Codex transport timing tests that
pass alone and on `master`.
- `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`,
`node scripts/check-maps.mjs`
- Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64`
- UI picker tests: 397 of 397

Known failures that also fail on `master`:

- 11 runner package script tests (browser, Pi and package-boundary
checks)
- 6 `runtime-selection` tests that read an untracked local skill file

Live evidence, without a prompt:

- Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona
sandbox. The closure digests reproduce. A changed or missing file is
rejected.
- `initialize` reports 1.5.2. An API-key session returns a receipt for
exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both
platforms.
- All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt
under an API key.
- A session survives a process kill and resumes in a new process with
exact receipts, on both platforms.
- The server's remote path verifies the provider pack in a Daytona
sandbox.
- Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to
1.74 s on Linux x64, before the per-launch executable hash was restored
(about 60 ms on macOS; not measured on Linux).
- Remote pack verification on a reused sandbox lease: about 4.3 s to
about 0.25 s.

Live evidence, with a prompt, on an already-released harness:

- Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on
`darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both
native runs succeeded (25.5 s and 25.7 s). The process started from the
new launch store with no fallback warning.
- The same cell and `native-pending-controller-restart` failed in the
paid workflow on this branch and on `master` in the same way, before any
native start. The workflow does not install the Pi runtime for local
cells, so the agent setup check fails. That is a workflow gap, not part
of this change.

**Not run.** No Antigravity prompt completed on 1.5.2 on any platform.
The only Gemini key available is on the free tier, and Google returned
503 or 429 for each attempt on two days. These gates are open:

- All 24 `antigravity-qualification` cells
- Both model lineup suites, including inference on Gemini 4 Neon
- The attended Google sign-in journey on 1.5.2
- The chat cases under Antigravity
- Image pull time and startup time on a published image
- A native start on `linux-arm64`
- A live provider-death cell for Kimi, Pi or Copilot on the new launch
store (one ordinary Pi cell passed live; see above)

## Risks

- **The launch store changes how every native ACPX provider starts**
(Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two
defects in the first version (an executable swap was possible, and Pi
launches broke). Both are fixed with tests. One live Pi cell passed on
this branch on macOS. No live provider-death cell and no Linux cell ran
for those providers.
- The profile digest changes. Saved Antigravity candidate sessions and
existing candidate grants stop working. The new release refuses old
state by name and starts a replacement conversation.
- The Linux provider pack and the Daytona image grow by about 834 MB
(about 274 MB compressed) when Antigravity is included.
- The pack verification record is in server memory. The first run after
a server restart pays the full hash again.
- Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as
user rules. This is deliberate and matches Codex. Any other rule file is
refused.
- Orchestrator mode is not available. ACP server 1.5.2 does not expose
it.
- Antigravity stays `pending`. Normal users cannot run it until a later
change removes the pending status.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated
the work, with tool use.
- Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran
the tests, with tool use and code 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
- [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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 08:21:11 -06:00

302 lines
19 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, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, type RemoteProviderPackRelease, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } 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);
});
});