mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 12:50:37 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A remote agent run needs the provider pack (Node, OpenCode and the Runner bridge) inside its sandbox before the provider can start > - The server reuses a pack that is installed in the sandbox image only when its full manifest equals the server's own manifest > - The manifest includes `runnerSourceRevision`, which is the commit that built the server, so an image pack fails this check on every later server build, also when every file in the pack is the same > - The run then uploads the whole pack again, which cost about 15 s per task in a recent load test > - This pull request accepts an image pack whose sealed content equals the expected pack and that differs only in build provenance, and caches verified archive hashes in the server process > - The benefit is that a sandbox image stays usable across server releases that do not change the pack, and the server does less hashing on its main thread ## Linked Issues or Issue Description Refs #21781 (merged), which names the failed check on the run spans. **What existing behavior does this improve?** Selection of the remote provider pack for a new sandbox (`provider_pack.select`). **Subsystem affected** Server: native runtime, remote provider pack verification and upload. **Current behavior** `provider_pack.verify_preinstalled` compares the complete manifest of the image pack with the server's manifest. Any difference fails, including `runnerSourceRevision` and `runnerInputsDigest`, which only record where the pack was built. The run then uploads the full pack. The server also hashes the same archive or pack directory again for every task. **Proposed behavior** When the run is not bound to a saved pack and the operator did not select a custom pack, the remote verification accepts an image pack when (1) its own digest seals its payload, and (2) its schema and payload equal the expected pack after the two provenance fields are removed. Every artifact, the `dist` tree, the candidate trees, the package versions, the Node version, the target platform and the OpenCode version are still checked in the sandbox, against the same values. The server checks the reported manifest again and selects it through the pack authority, as the compatibility path already does. An upload still happens for different content, a corrupted or partial pack, or no pack. The server also remembers a verified transport archive (by path, inode, size and times), so it does not hash it again for the next task. **Reason and benefit** In the harness (fake sandbox, 150 ms per command, 300 ms + 10 MiB/s per transfer, 24 MiB pack), the cross-build case goes from 4.1 s and 24 MiB uploaded to 1.1 s and 0 bytes. Other cases do not change. **Breaking changes** None. A saved or reattached session, and an operator-selected custom pack, still require the exact pack identity. ## What Changed - `remote-provider-pack-verification.ts`: new `acceptProvenance` option. The remote script accepts a sealed pack with the same content and prints its manifest. The server checks that manifest (`sameContentManifest`) and returns it. A forged or different report fails with `installed_manifest_invalid`. - `native-session-executor.ts` (`prepareRemoteProviderPackOnTarget`): staged and preinstalled verification use the option when `acceptProvenanceDifferences` is set. The function returns the selected manifest. The run caller sets the option only through `providerPackProvenanceReuseAllowed` (not retained, no explicit custom pack, selectable authority), and selects a different manifest through the pack authority. - `provider-pack-layers.ts`: `verifyArchive` skips the hash for an archive it already verified with the same file identity. - `remote-provider-pack.ts`: `providerPackProvenanceReuseAllowed` gate, with tests for each case. - `provider-pack-selection-harness.test.ts`: new harness. Uploads go through the workspace confinement check of the Daytona sync guard. It runs the real remote verification in local processes, with modelled sandbox latency and transfer speed, for five cases, before and after. ## Verification - `cd server && npx vitest run src/services/native-runtime/provider-pack-selection-harness.test.ts src/services/native-runtime/provider-pack-archive.test.ts 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` passes. - `npx vitest run src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-artifact-preparation.test.ts src/services/native-runtime/remote-provider-pack-authority.test.ts` passes (1541 passed, 7 skipped). - Red/green: with the source changes reverted, the harness case `same_content_other_build` and the archive cache test fail. With the changes, they pass. - Harness output (load average about 9 on a shared machine; modelled time = wall time + modelled sandbox latency): | Case | Before | After | | --- | --- | --- | | Exact image pack | preinstalled, 1.1 s, 0 MiB | preinstalled, 1.0 s, 0 MiB | | Same content, other build | uploaded, 4.1 s, 24 MiB | preinstalled, 1.1 s, 0 MiB | | Different content | uploaded, 4.1 s, 24 MiB | uploaded, 4.0 s, 24 MiB | | Corrupted image pack | uploaded, 4.0 s, 24 MiB | uploaded, 4.1 s, 24 MiB | | No image pack | uploaded, 3.7 s, 24 MiB | uploaded, 3.8 s, 24 MiB | - The pack step runs no database statements. - `npx tsc --noEmit -p server/tsconfig.json` passes. ## Risks - This changes which provider pack the server accepts. It accepts a different manifest digest only when all content fields are equal and every file is hashed in the sandbox, and only for a run that is not bound to a saved pack. The selected manifest goes through the existing pack authority, so launch profiles and receipts bind the installed pack's own identity. - The archive hash cache trusts each archive file's identity (inode, size, times) on the server. The sandbox still checks the uploaded bundle digest and verifies every uploaded file, so a changed local file still fails closed. - This does not help when the image pack has other content (for example a different contract digest). See the hand-off notes for the image build. > 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 - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, 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 - [ ] 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
173 lines
10 KiB
TypeScript
173 lines
10 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 { prepareVerifiedRemoteProviderPack, 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.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"])("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("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);
|
|
});
|
|
});
|