mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-14 17:40:37 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native execution needs a compatible installed daemon and provider dependency. > - The Codex-default work found missing platform packages and clean-install startup failures. > - Release builds also repeat dependency compilation and run preparation serially. > - This prerequisite packages four daemon targets and verifies installed native startup. > - It also caches hosted Cargo dependencies and overlaps JavaScript preparation with compilation. > - Agent creation defaults and experimental gates stay at the current master behavior. ## Linked Issues or Issue Description Refs #15683. Refs #15555. Refs #15422. Refs #15926. Refs #15932. Extract runtime and installation support from #15683. This prerequisite has 65 changed files. Creation, onboarding, imports, UI runner selection and graduation remain in the dependent PR. Feature/access maps and the Storybook source catalog stay synchronized. Existing agents keep their execution choices. ## What Changed - Correct the existing runner test fixtures. Reserve owned credential quorum listeners through the existing bounded fixture helper. Keep foreign listeners intact, run actual credential staging once, and preserve its rejection and unchanged-auth assertions. Reuse the durable-resume outer-limit correction. Wait for actual warm-completion and held-authorization callback entry under the existing recovery deadline and surface early request errors. Preserve every semantic assertion. - Retain bounded installation failure diagnostics through the existing qualification receipt upload. Keep the original error, 10-minute deadline and all success checks. - Keep startup ownership until credential preparation and registration drain. Reject duplicate and post-close startup/resume work. Observe shutdown during normal and adopted authentication readiness. Preserve the primary failure and retain private state when cleanup is unconfirmed. - Package Linux x64/ARM64 and macOS Apple Silicon/Intel daemons. Verify target headers, source identities, manifests, and hashes before assembly and installation. - Reuse the existing release producer/consumer workflows. Cache Cargo dependencies by target, OS, compiler, lockfile, and contract inputs. Rebuild workspace binaries. Permit trusted cache writes only for canonical exact-source master pushes. - Overlap JavaScript preparation with native compilation. Join both commands and failure/cancellation cleanup before artifact verification. - Preserve shell positional arguments in the shared SSH runner and apply environment assignments correctly. Reject environment option keys. Six before/after controls and two real SSH subprocess paths pass with zero provider calls; this fix lands before both Codex and Claude defaults. - Admit verified suspended SSH backups during cold controller continuation, using the same full-scope, integrity and lifecycle checks as sandbox targets. Two positive SSH cases fail before; all 14 positive/negative matrix cases pass afterward. Active ownership and corrupt/malformed/nonempty state remain rejected. - Record measured sandbox platform facts through the existing explicit environment probe. Bind facts to the company, effective provider configuration, immutable OCI image and actual captured image binding. Check the returned cleanup receipt. Reject client-authored proof and stale or named boot identities. Creation and discovery allocate nothing. Preserve connection-only behavior. - Resolve the actual remote Codex target and preserve same-host development overrides. Preserve runtime artifact verification. Use actual protocol/model compatibility rather than a numerical CLI version fence. - Resolve the installed Codex login dependency on 64-bit Linux and Mac independently of the daemon libc baseline. Preserve account homes and safe errors. - Fix actual clean-install TOML table comparison. Preserve strict semantic checks, comments, private writes, and malformed-input rejection. Preserve primary startup failures and bounded cleanup. - Document GNU libc 2.39+ and stock Ubuntu sandbox prerequisites. Qualify ARM startup with a scoped distribution profile and unchanged global restrictions. Preserve Windows and Alpine deferral. - Preserve selected and saved native Codex reasoning effort in the existing UI builder, while excluding it from other providers. This small shared correction prevents import edits higher in the stack from dropping effort. - Reuse existing installed-package checks and assertions. Paperclip tarballs contain no Codex native payloads. Official npm dependencies supply the consumer's Codex binaries. All Docker and native builds stay remote. ## Verification Candidate: `271d434c170e74bdedde65d0b13059a55419c943`. It includes current master `e168512f7bdbb6af6ea01954c6d7ed80b91e903e` and preserves prior candidates through ordinary commits. Current [full CI](https://github.com/paperclipai/paperclip/actions/runs/38346601686) is successful on attempt 2. GitHub reports 54 successful checks and four conditional skips, including required verify and browser aggregates, workspace typecheck/tests/build, Linux DB controls, both runner shards and [isolated native compilation](https://github.com/paperclipai/paperclip/actions/runs/38346601609). Fresh current-head Greptile is 5/5 with all four threads resolved. The passing build's clean Grok/Codex report records CI merge source `7a82a37438e6e448abc7cc5caa60dc2519a97be0`, 18 installed packages, omitted Codex payloads, official host-only npm dependencies and zero provider calls. Pi setup and its no-prompt lease verification also pass. The first attempt's single 60-second Node archive download timeout remains retained; its DNS/TLS/download cause remains unknown. One unchanged-source retry was requested through the normal Build-job dialog with debug logging disabled. GitHub's attempt 2 graph reports the other CI jobs as well; no second retry or source/deadline relaxation was made. The [final exact-source package campaign](https://github.com/paperclipai/paperclip/actions/runs/38347027535) is successful on literal `271d434c170e74bdedde65d0b13059a55419c943`. It passes all four native producers, public Linux package assembly and clean installed consumers on Apple Silicon, Intel Mac and Linux ARM64. The nine qualification-mode skips are intentional; full CI above covers their ordinary gates. Native builds and Docker assembly ran remotely. The predecessor [`dae808` package campaign](https://github.com/paperclipai/paperclip/actions/runs/38342104102) remains literal historical evidence. Only tests and the dated record differ from that source; runtime, package and workflow code is unchanged. The reused credential fixture correction passes all 42 canonical Node 24 controls with synthetic data and independent matching-source review, and the current hosted runner shard passes. Production credential behavior is unchanged. **Merge hold:** current-source CI, fresh 5/5 review and exact-source package qualification pass. Actual code-owner approval and normal protected merge remain pending. No slice has merged or deployed. GitHub CLI authentication needs refresh; the normal signed-in embedded GitHub UI provided this status without credential workarounds. - The master merge preserves both Storybook source-review appendices and the guarded test-home cleanup. All six existing cleanup controls pass without skips. Master's isolated-home helper/test/setup are byte-identical. The two existing whitespace lines in master's unrelated privacy test remain outside this PR's diff. - Canonical Node 24 passes all 24 existing public-install helper tests. Three narrow added cases prove bounded/redacted failure metadata, symlink exclusions, original exception identity, failed diagnostic writes and no false failure on success. The Mac installer now uses `--timing`; at most two 16 KiB tails and 32 structured entries per tail enter the existing receipt upload. Raw argv, URLs, environment, error text and stacks are omitted. A failed receipt explicitly remains FAILED/unqualified/runtime-not-attempted. The 600,000 ms install deadline and every real package/hash/payload/lock/lifecycle/runtime oracle are unchanged. - Canonical Node 24 reproduces the durable-resume outer timeout under controlled fake latency. Only its outer test limit changes to 15 seconds; internal 500 ms/5 second deadlines and usage/effect assertions remain. Controlled warm-recovery and before-bootstrap authorization scheduling delays reproduce their callback polling failures, while the explicit entry signals pass. Early recovery errors surface unchanged. Independent review is clear. Historical mock binaries support the fixture controls; fresh full hosted CI remains decisive. The original hosted callback failure cause is inconclusive. - The composed runner/surfaces/server/E2E TypeScript checks pass. Map checks pass 35 areas/171 capability IDs. Token gates pass. The existing Storybook catalog passes 223 files/2,210 stories; story IDs and classifications remain intact. The current master had 25 inherited stale fingerprints from three changed map recipes. Only those guarded fingerprints and a source-only review note change; all 92 non-map story/component/fixture inputs remain unchanged. Existing classifications are retained. This proves source structure, not visual or live acceptance. - The 65-file contribution audit has no code file crossing from below 1,000 lines to above the limit. Earlier comment cleanup preserves executable emissions, parsed workflows and action pins. Independent cleanup/catalog and three-file reporting reviews are clear. No new workflow, suite, grader or local native/Docker build was added. **Prior `dae808` gate evidence:** fresh Greptile is 5/5 with four resolved threads, isolated native compilation and the browser aggregate pass. Its first runner shard passes the previous two corrections but fails a different held-authorization cell at the implicit one-second polling deadline. It records 1,672 passes/one failure/three skips. This candidate applies the verified entry-signal correction without changing production deadlines or any semantic assertions. Its original hosted cause remains inconclusive until fresh CI. **Previous-source evidence, kept literal:** the [exact `16a532` package campaign](https://github.com/paperclipai/paperclip/actions/runs/38338806076) passes all four native producers, public Linux package assembly, Apple Silicon, Intel Mac and Linux ARM64 installed consumers. Its fresh review is 5/5 with all four threads resolved. Full CI records 52 successful checks, four conditional skips and the two fixture failures corrected here. This is not a green full-CI candidate or proof for the new source. `64c074fb8da1b31f8d6042c4fef48dc4164e759b` passed [full CI](https://github.com/paperclipai/paperclip/actions/runs/38332726938), 54 checks/four conditional skips, [isolated native compilation](https://github.com/paperclipai/paperclip/actions/runs/38332726787/job/115085895328), and fresh Greptile 5/5/all four resolved threads. The hosted transport suite passed 246 tests and startup trust passed 22, closing that source's local fake-binary limitation. These are historical after reconciliation. The [previous exact-source package campaign](https://github.com/paperclipai/paperclip/actions/runs/38332921463) built all four platform daemons and passed public Linux package assembly plus Apple Silicon and Linux ARM64 installed consumers. **Intel Mac failed:** its initial scripts-disabled npm install timed out before lifecycle/runtime assertions. The underlying download/resolution/host cause is unknown because the old helper deleted the npm logs. This is the concrete baseline for the diagnostic change. The failed campaign remains failed; no all-platform signoff or automatic retry is claimed. The earlier `a200495` [four-target campaign](https://github.com/paperclipai/paperclip/actions/runs/38283695248) and [scoped ARM qualification](https://github.com/paperclipai/paperclip/actions/runs/38291535914) remain component evidence. Cargo restores were cold misses; no warm-cache speedup is claimed. Paperclip tarballs contain no Codex payloads. Official npm dependencies supply Codex on the user's platform. Current-source full workspace typecheck/tests/build, Linux DB controls, static/Rust/native tests, all browser shards and exact-source package consumers must pass. New-agent defaults and final managed onboarding belong to #15683. Actual private Cloud composition, warm/cold signup, task/follow-up and rollback compatibility remain later release gates. Source audits found that ordinary managed onboarding does not run the saved platform probe and Cloud distributes named snapshots without a verified final boot-image binding. These dependent release blockers remain open; prequalified E2E fixtures do not close them. Master adds task-workspace migrations; the final image/migrator and previous-image checks must include them. ARM paid task/follow-up and ordinary OS APT installation are not proven. ## Risks - Multi-target packages require source and header agreement. Missing or mismatched artifacts fail explicitly. Existing execution choices remain unchanged. - Linux requires GNU libc 2.39+ and compatible sandbox prerequisites. The scoped hosted ARM preparation does not qualify arbitrary containers or kernels. Windows, 32-bit ARM, and Alpine remain deferred. - Only dependency crates are cached. Preview jobs cannot write trusted caches. Concurrent command cleanup must preserve the primary failure. - Native-free Paperclip packaging retains official Codex npm dependencies. No Codex payload bundling, schema migration, automatic agent migration, or production deployment is included. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and parallel agents. The exact serving model snapshot and context-window size are not exposed. ## 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
190 lines
16 KiB
TypeScript
190 lines
16 KiB
TypeScript
import { execFileSync } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import { chmod, lstat, mkdtemp, mkdir, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { tmpdir } from "node:os";
|
|
import { afterEach, expect, it } from "vitest";
|
|
import { runnerMatrix } from "./catalog.js";
|
|
import { assertInstalledCliSelection, installedCliKeys, probeInstalledCodexStartup, verifyInstalledCli } from "./installed-cli.js";
|
|
import { buildPaperclipServerEnvironment, buildRunnerE2EProcessEnvironment } from "./harness-env.js";
|
|
const cells = runnerMatrix.filter(e => e.profile.id === "runner-acpx-pi");
|
|
const roots: string[] = [];
|
|
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
|
|
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
async function fixture() {
|
|
const root = await realpath(await mkdtemp(join(tmpdir(), "e2e-installed-cli-"))); roots.push(root);
|
|
const cli = join(root, "node_modules/paperclipai"); const server = join(root, "node_modules/@paperclipai/server");
|
|
await mkdir(join(cli, "dist"), { recursive: true }); await mkdir(join(server, "dist"), { recursive: true });
|
|
await writeFile(join(cli, "package.json"), JSON.stringify({ name: "paperclipai", version: "1.2.3", type: "module", bin: { paperclipai: "./dist/index.js" } }));
|
|
await writeFile(join(server, "package.json"), JSON.stringify({ name: "@paperclipai/server", version: "1.2.3", type: "module", exports: { ".": { import: "./dist/index.js" } } }));
|
|
await writeFile(join(cli, "dist/index.js"), "// installed public CLI"); await writeFile(join(server, "dist/index.js"), "// installed public server");
|
|
const env = { PAPERCLIP_RUNNER_E2E_INSTALLED_CLI: join(cli, "dist/index.js"), PAPERCLIP_RUNNER_E2E_INSTALLED_CLI_SHA256: hash("// installed public CLI"), PAPERCLIP_RUNNER_E2E_INSTALLED_SERVER_ROOT: server, PAPERCLIP_RUNNER_E2E_INSTALLED_SERVER_SHA256: hash("// installed public server") };
|
|
return { root, cli, server, env };
|
|
}
|
|
it("admits all26 current Pi cases through pinned installed public CLI/server with no overrides", async () => {
|
|
const { env, server } = await fixture(); expect(cells).toHaveLength(26);
|
|
for (const cell of cells) expect(await verifyInstalledCli(env, [cell])).toMatchObject({ serverRoot: server, defaultRuntimeResolution: true, qualificationOverride: false });
|
|
});
|
|
it("admits existing Codex onboarding, useful-file revision and restart journeys without broadening other cells", async () => {
|
|
const { env, server } = await fixture();
|
|
for (const id of ["first-task.runner-codex.local.task-card-accept", "everyday-workflows.runner-codex.local.build-revise", "agent-chat.runner-codex.local.continuity-restart"]) {
|
|
const cell = runnerMatrix.find(e => e.id === id)!;
|
|
expect(cell).toBeDefined();
|
|
expect(await verifyInstalledCli(env, [cell])).toMatchObject({ serverRoot: server, defaultRuntimeResolution: true, qualificationOverride: false });
|
|
for (const key of ["PAPERCLIP_RUNNER_BINARY", "NODE_PATH"]) expect(() => assertInstalledCliSelection({ ...env, [key]: "foreign" }, [cell])).toThrow("forbids");
|
|
}
|
|
for (const id of ["first-task.legacy-codex.local.task-card-accept", "first-task.runner-codex.local.interview-first-response", "everyday-workflows.runner-codex.daytona.build-revise"]) {
|
|
const cell = runnerMatrix.find(e => e.id === id)!;
|
|
expect(cell).toBeDefined();
|
|
expect(() => assertInstalledCliSelection(env, [cell])).toThrow("explicit supported Pi or Codex");
|
|
}
|
|
});
|
|
it("qualified providers drop ambient admission while pending Copilot retains its exact gate", () => {
|
|
for (const cell of cells) expect(buildRunnerE2EProcessEnvironment({ PAPERCLIP_RUNNER_ACPX_QUALIFICATION: "ambient" }, [cell]).PAPERCLIP_RUNNER_ACPX_QUALIFICATION).toBeUndefined();
|
|
for (const agent of ["copilot"]) {
|
|
const cell = runnerMatrix.find(e => e.profile.qualificationCandidate === agent)!;
|
|
expect(JSON.parse(buildRunnerE2EProcessEnvironment({}, [cell]).PAPERCLIP_RUNNER_ACPX_QUALIFICATION!)).toEqual([{ agent, model: cell.profile.model }]);
|
|
}
|
|
const changed = { ...cells[0]!, profile: { ...cells[0]!.profile, model: "custom/explicit-model" } };
|
|
expect(buildRunnerE2EProcessEnvironment({}, [changed]).PAPERCLIP_RUNNER_ACPX_QUALIFICATION).toBeUndefined();
|
|
});
|
|
it("rejects partial authority, unsupported cells and every runtime/path override", async () => {
|
|
const { env } = await fixture();
|
|
for (const key of installedCliKeys) { const changed = { ...env, [key]: undefined }; await expect(verifyInstalledCli(changed, [cells[0]!])).rejects.toThrow("complete pins"); }
|
|
expect(() => assertInstalledCliSelection(env, [])).toThrow("explicit supported Pi");
|
|
expect(() => assertInstalledCliSelection(env, [runnerMatrix.find(e => e.profile.qualificationCandidate === "cursor")!])).toThrow("explicit supported Pi");
|
|
for (const key of ["PAPERCLIP_RUNNER_BINARY", "PAPERCLIP_RUNNER_REMOTE_BINARY_PATH", "PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "PAPERCLIP_RUNNER_ACPX_QUALIFICATION", "PAPERCLIP_ACPX_BUILTIN_ROOT", "PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", "PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST", "NODE_OPTIONS", "NODE_PATH"]) await expect(verifyInstalledCli({ ...env, [key]: "foreign" }, [cells[0]!])).rejects.toThrow("forbids");
|
|
});
|
|
it("rejects stale bytes and another server root instead of falling back to source", async () => {
|
|
const f = await fixture(); const other = await fixture();
|
|
await expect(verifyInstalledCli({ ...f.env, PAPERCLIP_RUNNER_E2E_INSTALLED_SERVER_ROOT: other.server }, [cells[0]!])).rejects.toThrow("foreign server");
|
|
await expect(verifyInstalledCli({ ...f.env, PAPERCLIP_RUNNER_E2E_INSTALLED_CLI_SHA256: "0".repeat(64) }, [cells[0]!])).rejects.toThrow("reviewed pins");
|
|
await writeFile(join(f.server, "dist/index.js"), "changed");
|
|
await expect(verifyInstalledCli(f.env, [cells[0]!])).rejects.toThrow("reviewed pins");
|
|
});
|
|
it("rejects linked entrypoints and source-export package identities", async () => {
|
|
const f = await fixture(); const other = await fixture();
|
|
await rm(join(f.cli, "dist/index.js")); await symlink(join(other.cli, "dist/index.js"), join(f.cli, "dist/index.js"));
|
|
await expect(verifyInstalledCli(f.env, [cells[0]!])).rejects.toThrow("canonical and unlinked");
|
|
await rm(join(f.cli, "dist/index.js")); await writeFile(join(f.cli, "dist/index.js"), "// installed public CLI");
|
|
await writeFile(join(f.server, "package.json"), JSON.stringify({ name: "@paperclipai/server", version: "1.2.3", exports: { ".": "./src/index.ts" } }));
|
|
await expect(verifyInstalledCli(f.env, [cells[0]!])).rejects.toThrow("public package identity");
|
|
});
|
|
it("keeps installed proof inputs out of the production server environment", async () => {
|
|
const { env } = await fixture(); const server = buildPaperclipServerEnvironment(env);
|
|
for (const key of installedCliKeys) expect(server[key]).toBeUndefined();
|
|
await expect(verifyInstalledCli({}, [])).resolves.toBeUndefined();
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")("rejects a FIFO entrypoint without waiting for a writer", async () => {
|
|
const f = await fixture(); await rm(f.env.PAPERCLIP_RUNNER_E2E_INSTALLED_CLI);
|
|
execFileSync("/usr/bin/mkfifo", [f.env.PAPERCLIP_RUNNER_E2E_INSTALLED_CLI], { timeout: 5000, env: {} });
|
|
await expect(verifyInstalledCli(f.env, [cells[0]!])).rejects.toThrow("bounded regular file");
|
|
});
|
|
|
|
it("uses the direct public Playwright JS bin without bin-shim Node injection", async () => {
|
|
const { runnerE2EPlaywrightInvocation } = await import("./web-server-command.js");
|
|
const f = await fixture(); const cli = join(f.root,"node_modules/@playwright/test/cli.js");
|
|
await mkdir(join(f.root,"node_modules/@playwright/test"),{recursive:true});
|
|
await writeFile(cli,"console.log(JSON.stringify({nodePath:process.env.NODE_PATH??null,nodeOptions:process.env.NODE_OPTIONS??null,args:process.argv.slice(2)}))");
|
|
const invocation = runnerE2EPlaywrightInvocation(f.root,["--version"],true);
|
|
expect(invocation.command).toBe(process.execPath);
|
|
expect(JSON.parse(execFileSync(invocation.command,invocation.args,{env:{},timeout:5000,encoding:"utf8"}))).toEqual({nodePath:null,nodeOptions:null,args:["--version"]});
|
|
expect(runnerE2EPlaywrightInvocation(f.root,["--version"],false)).toEqual({command:"pnpm",args:["exec","playwright","--version"]});
|
|
for (const key of ["NODE_PATH","NODE_OPTIONS"]) expect(()=>assertInstalledCliSelection({...f.env,[key]:""},[cells[0]!])).toThrow("ambient Node injection");
|
|
});
|
|
|
|
it("startup-only accepts only explicit uncredentialed local hello and zero retries", async () => {
|
|
const { assertInstalledStartupOnly } = await import("./installed-cli.js");
|
|
const { parseRunnerSelectors } = await import("./selectors.js");
|
|
const f=await fixture(); const cell=cells.find(e=>e.id==="extended-harnesses.runner-acpx-pi.local.hello-complete")!;
|
|
const options=parseRunnerSelectors(["--installed-startup-only","--id",cell.id,"--max-automatic-retries","0"]);
|
|
expect(options.installedStartupOnly).toBe(true);expect(()=>assertInstalledStartupOnly(f.env,[cell],options)).not.toThrow();
|
|
for(const delta of [{maxAutomaticRetries:1},{maxParallel:2},{ui:true},{debug:true},{headed:true},{list:true},{matrixJson:true},{ids:[]}])expect(()=>assertInstalledStartupOnly(f.env,[cell],{...options,...delta})).toThrow("startup-only");
|
|
expect(()=>assertInstalledStartupOnly(f.env,[cells.find(e=>e.environment.id==="daytona")!],options)).toThrow("startup-only");
|
|
expect(()=>assertInstalledStartupOnly({...f.env,OPENROUTER_API_KEY:"dummy-not-a-real-key"},[cell],options)).toThrow("credential inputs");
|
|
expect(()=>assertInstalledStartupOnly({...f.env,KIMI_MODEL_API_KEY:"dummy-not-a-real-key"},[cell],options)).toThrow("credential inputs");
|
|
expect(()=>assertInstalledStartupOnly({},[cell],options)).toThrow("startup-only");
|
|
});
|
|
|
|
async function startupFixture(mode: "normal" | "wrong-model" | "ambient-codex" | "startup-and-cleanup-failed" | "cleanup-failed" = "normal") {
|
|
const f = await fixture();
|
|
const vendor = join(f.server, "dist/vendor/paperclip-runner");
|
|
const daemon = join(vendor, "bin", `${process.platform}-${process.arch}`, "paperclip-runnerd");
|
|
const codex = join(f.root, "node_modules/@openai/codex/bin/codex");
|
|
const observations = join(f.root, "startup-observations.json");
|
|
await mkdir(join(vendor, "bin", `${process.platform}-${process.arch}`), { recursive: true });
|
|
await mkdir(join(f.server, "dist/services/native-runtime"), { recursive: true });
|
|
await mkdir(join(f.root, "node_modules/@openai/codex/bin"), { recursive: true });
|
|
await writeFile(daemon, "fixture-daemon");
|
|
await writeFile(codex, "#!/bin/sh\nprintf 'codex-cli 0.149.5\\n'\n");
|
|
await chmod(codex, 0o755);
|
|
await writeFile(join(f.server, "dist/services/native-runtime/native-codex-runner.js"), `export function resolvePaperclipRunnerBinary() { return ${JSON.stringify(daemon)}; }`);
|
|
await writeFile(join(vendor, "index.js"), `
|
|
import {writeFileSync} from "node:fs";
|
|
const state={calls:[],environmentKeys:[],fileAuthPinned:false};let retired=false;
|
|
const save=()=>writeFileSync(${JSON.stringify(observations)},JSON.stringify(state));
|
|
export function resolveCodexCommand(){return ${JSON.stringify(mode === "ambient-codex" ? process.execPath : codex)};}
|
|
export function createIsolatedCodexAppServerArgs(){return ["app-server"];}
|
|
export function createRunnerdCodexTransport(options){
|
|
state.environmentKeys=Object.keys(options.environment).sort();
|
|
state.fileAuthPinned=options.codexArgs.includes('cli_auth_credentials_store="file"');
|
|
state.privateStateDirectory=options.stateDirectory;
|
|
save();return {transport:{async close(){retired=true;state.calls.push("transport-close");save();${mode === "startup-and-cleanup-failed" ? 'throw new Error("fixture secondary transport cleanup failure");' : ''}}},
|
|
evidence:()=>({runnerPid:111,codexPid:222,providerDriver:"codex_app_server",runnerExited:retired,diagnostics:["fixture provider bootstrap failed"],providerSessionId:"PRIVATE-PROVIDER-ID"})};}
|
|
export class CodexAppServerDriver {
|
|
constructor(options){this.options=options;}
|
|
async openSession(){state.calls.push("open");save();
|
|
${mode === "startup-and-cleanup-failed" ? 'throw new Error("fixture original provider startup failure");' : ''}
|
|
const model=${JSON.stringify(mode === "wrong-model" ? "wrong-model" : "gpt-5.6-sol")};
|
|
return {ids:()=>({driverSessionId:"PRIVATE-DRIVER-ID",providerSessionId:"PRIVATE-PROVIDER-ID"}),
|
|
events:()=>({async *[Symbol.asyncIterator](){yield {eventType:"session.started",payload:{context:{model,sandbox:{permissionProfile:{id:"paperclip-runner-workspace-read-only"}}}}};}}),
|
|
startTurn(){state.calls.push("FORBIDDEN-TURN");save();throw new Error("No provider turn is permitted");},
|
|
async close(){retired=true;state.calls.push("session-close");save();${mode === "cleanup-failed" ? 'throw new Error("fixture session cleanup failure");' : ''}}};}
|
|
}
|
|
`);
|
|
return { ...f, observations, expectedRunnerSha256: hash("fixture-daemon") };
|
|
}
|
|
|
|
it.skipIf(process.platform === "win32")("installed native startup uses closed homes, file-only auth and no turn or version equality gate", async () => {
|
|
const f = await startupFixture();
|
|
const receipt = await probeInstalledCodexStartup({ consumerRoot: f.root, serverRoot: f.server, expectedRunnerSha256: f.expectedRunnerSha256 });
|
|
expect(receipt).toMatchObject({ nativeSessionStarted: true, cleanupConfirmed: true, providerTurns: 0, credentialsUsed: false,
|
|
codexVersion: "codex-cli 0.149.5", defaultRuntimeResolution: true, reasoningEffortExercised: false });
|
|
expect(await readFile(f.observations, "utf8").then(JSON.parse)).toMatchObject({ calls: ["open", "session-close"], fileAuthPinned: true,
|
|
environmentKeys: ["CODEX_HOME", "HOME", "LC_ALL", "PAPERCLIP_RUNNER_NETWORK_ACCESS", "PATH", "TMPDIR", "TZ"] });
|
|
expect(JSON.stringify(receipt)).not.toMatch(/PRIVATE-(?:DRIVER|PROVIDER)-ID/);
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")("installed startup preserves the primary cause, records bounded diagnostics and attempts independent cleanup", async () => {
|
|
const f = await startupFixture("startup-and-cleanup-failed");
|
|
const error = await probeInstalledCodexStartup({ consumerRoot: f.root, serverRoot: f.server, expectedRunnerSha256: f.expectedRunnerSha256 }).catch(error => error);
|
|
expect(error).toBeInstanceOf(AggregateError);
|
|
expect(error.message).toContain("fixture original provider startup failure");
|
|
expect(error.message).toContain("fixture secondary transport cleanup failure");
|
|
expect(error.message).toContain("fixture provider bootstrap failed");
|
|
expect(error.cause.message).toBe("fixture original provider startup failure");
|
|
expect(error.errors.map((error: Error) => error.message)).toEqual(["fixture original provider startup failure", "fixture secondary transport cleanup failure"]);
|
|
expect(error.message).not.toContain("PRIVATE-PROVIDER-ID");
|
|
const observations = JSON.parse(await readFile(f.observations, "utf8"));
|
|
expect(observations.calls).toEqual(["open", "transport-close"]);
|
|
await expect(lstat(observations.privateStateDirectory)).rejects.toThrow();
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")("installed startup cannot qualify when session cleanup fails after successful open", async () => {
|
|
const f = await startupFixture("cleanup-failed");
|
|
await expect(probeInstalledCodexStartup({ consumerRoot: f.root, serverRoot: f.server, expectedRunnerSha256: f.expectedRunnerSha256 })).rejects.toThrow("fixture session cleanup failure");
|
|
expect(JSON.parse(await readFile(f.observations, "utf8")).calls).toEqual(["open", "session-close", "session-close"]);
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")("installed startup rejects stale daemon/ambient Codex and cleans a mismatched native session", async () => {
|
|
const f = await startupFixture();
|
|
await expect(probeInstalledCodexStartup({ consumerRoot: f.root, serverRoot: f.server, expectedRunnerSha256: "0".repeat(64) })).rejects.toThrow("reviewed pin");
|
|
await expect(readFile(f.observations)).rejects.toThrow();
|
|
const ambient = await startupFixture("ambient-codex");
|
|
await expect(probeInstalledCodexStartup({ consumerRoot: ambient.root, serverRoot: ambient.server, expectedRunnerSha256: ambient.expectedRunnerSha256 })).rejects.toThrow("ambient Codex");
|
|
const wrong = await startupFixture("wrong-model");
|
|
await expect(probeInstalledCodexStartup({ consumerRoot: wrong.root, serverRoot: wrong.server, expectedRunnerSha256: wrong.expectedRunnerSha256 })).rejects.toThrow("matching native identity");
|
|
expect(await readFile(wrong.observations, "utf8").then(JSON.parse)).toMatchObject({ calls: ["open", "session-close"] });
|
|
});
|