Files
PaperClipAI/packages/paperclip-runner/src/drivers/runtime-context-materializer.test.ts
T
Nicky LeachandClaude Fable 5.2 0aaab644fe refactor(runner): remove the direct assigned-gateway path (#21311)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent reaches the tools of its app connections through an MCP
gateway.
> - Before #21274, some native harnesses got the gateway URL and a
bearer token and connected to the gateway directly. The Runner has code
for that: an HTTP MCP server for ACPX providers, a server entry in the
Codex `config.toml`, a server entry in the OpenCode config, and the
lists that pass the three `PAPERCLIP_NATIVE_MCP_*` variables to a
sidecar.
> - #21274 gives each native harness its gateway tools through the PRP
relay. Core removes the three variables from each Runner environment.
The direct code path gets no binding.
> - Code that cannot run still needs maintenance, and it can still put a
token in a provider process if a variable arrives by another way.
> - This pull request deletes the direct path from the Runner.
> - The benefit is one path for assigned gateway tools, and no Runner
code that can give a gateway token to a provider.

## Linked Issues or Issue Description

No public issue exists. The issue is described here.

This pull request is in a stack. Its base branch is
`fix/keep-quiet-claude-provider-between-turns` (#21293). It depends on
#21274, which is the bottom of the stack. On `master` without #21274,
the direct path is still in use.

**What existing behavior does this improve?**

The Runner code that connects a provider directly to the assigned MCP
gateway.

**Subsystem affected**

Paperclip Runner: the TypeScript drivers and the Rust `runner-core`
environment lists.

**Current behavior**

After #21274, Core never gives `PAPERCLIP_NATIVE_MCP_NAME`,
`PAPERCLIP_NATIVE_MCP_URL` or `PAPERCLIP_NATIVE_MCP_TOKEN` to a Runner.
The Runner still has the code that reads them and configures a direct
gateway server for ACPX providers, Codex and OpenCode.

**Proposed behavior**

The Runner has no code that reads the three variables to configure a
provider. If the variables are in the environment of a Runner, no
provider environment, sidecar, Codex `config.toml` or OpenCode config
gets them.

**Reason and benefit**

Less code, one path, and no way for a gateway token to reach a provider
process through the Runner.

## What Changed

- Deleted `packages/paperclip-runner/src/drivers/native-mcp.ts`
(`nativeMcpLaunchBinding`).
- `drivers/acpx/runtime-host.ts`: removed the native gateway server
entry and the name conflict check. The admission gate keeps its message.
A run with a binding id is admitted when the sidecar uses the PRP
transport with its tool bridge, as the production sidecar always does.
- `drivers/acpx/environment.ts`: the name and the URL are not in the
provider allowlist.
- `drivers/runtime-context-materializer.ts` and
`live/runnerd-codex-transport.ts`: the Codex home functions have no
`nativeMcp` parameter. The sidecar token pass-through is gone.
- `drivers/opencode/opencode-server-driver.ts`: removed the read of the
binding, its trace redaction value, and the gateway server entry in the
OpenCode config.
- `drivers/stdio-mcp.ts` and `runner-core/src/stdio_mcp.rs`: removed the
reservation of the gateway server name. No gateway server exists, so no
name can conflict. The names `paperclip` and `paperclip_runner_*` stay
reserved.
- `runner-core/src/acpx_sidecar_transport.rs` and `codex_provider.rs`:
the three variables are not in the pass-through lists.
- `control-plane/durable-prp-control-plane.ts`: the three variables are
not in the platform environment list.
- `packages/paperclip-runner/README.md`: the text about direct callers
and assigned servers.
- Kept: the three names stay in the reserved lists
(`src/configured-environment.ts`,
`runner-core/src/configured_environment.rs`). A user cannot configure
them. Tests in both languages now check all three names.
- No server code changed. The relay needs the gateway token and URL on
the control plane.

23 files, 73 lines added and 211 lines removed.

## State saved by the previous release

- This pull request changes no persisted shape. The provider server
lists, the launch profile digests, the protocol versions and the sidecar
contract are the same as with #21274.
- A Runner or sidecar that the previous release started keeps its own
code until its run ends, as #21274 describes.
- A kept Codex home that has the old gateway server in `config.toml` is
written again at the next start and at a recovery of the same run. A
test covers this.
- If the old variables reach a new Runner, no provider gets them. Tests
cover this for ACPX, Codex and OpenCode.

## Verification

From `packages/paperclip-runner`:

- `npx vitest run src/drivers/acpx/runtime-host.test.ts
src/live/runnerd-codex-transport.test.ts
src/drivers/acpx/environment.test.ts
src/drivers/opencode/opencode-server-driver.test.ts
src/live/runnerd-codex-transport-warm-attachment.test.ts
src/drivers/runtime-context-materializer.test.ts
src/drivers/agent-observability.test.ts src/drivers/stdio-mcp.test.ts
src/control-plane/durable-prp-control-plane.test.ts
src/configured-environment.test.ts`: `10 passed (10)` files, `807
passed` tests.
- `npx tsc --noEmit -p tsconfig.json` and `-p tsconfig.test.json`: no
errors.
- `cargo fmt --manifest-path runner/Cargo.toml --all -- --check`: no
changes.
- `cargo test -p paperclip-runner-core --test acpx_sidecar_transport`:
20 passed. `cargo test -p paperclip-runner-core --lib`: 639 passed, 4
ignored.

Tests that failed with the old code and pass now:

- `runtime-host.test.ts`: "admits a relayed … run with a binding id and
ignores a previous-release gateway binding", for Claude, Codex and
Cursor.
- `runnerd-codex-transport.test.ts`: "drops a previous-release gateway
binding from the … runner environment", for ACPX Claude, Codex, Pi,
Cursor, Copilot and Kimi, and for OpenCode.
- `opencode-server-driver.test.ts`: the OpenCode config has only the
task bridge.
- `runnerd-codex-transport-warm-attachment.test.ts`: a restored Codex
home has no gateway server and no gateway credential in `config.toml`.
- `environment.test.ts`: a provider environment has none of the three
variables.
- Rust
`previous_release_gateway_binding_and_unrelated_secrets_never_reach_the_sidecar`:
a Runner that starts with the old variables gives none of them to the
sidecar, for five agents.

Mutation check: with the three names put back in the Rust pass-through
list, the Rust test fails.

Not run: a live run with a real provider. Not run: `pnpm verify` and the
full suite. CI supplies that coverage.

## Risks

- **This pull request is safe only after #21274.** The stack order keeps
that.
- **A developer who sets the three variables by hand for
`eval-session`** no longer gets direct gateway tools. No document
describes that use.
- **The warm attachment test uses the staged Runner binary from
preflight.** That binary does not have the Rust changes of this pull
request. The Codex path of that test does not use the changed lists.
- The evidence that no entry point supplies a binding comes from a read
of the code: Core removes the variables before it builds each Runner
environment, and a native run cannot use the in-process path.

> 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 Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the
change, reviewed the diff, and ran the verification and a mutation check
again.
- Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with
tool use (shell, file edits, local test runs), traced each code path and
wrote the change and the tests.

## 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-13 13:33:47 -08:00

551 lines
21 KiB
TypeScript

import {
chmod,
lstat,
mkdtemp,
mkdir,
readFile,
readdir,
rm,
stat,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { parse } from "smol-toml";
import { afterEach, describe, expect, it } from "vitest";
import {
NATIVE_RUNTIME_ASSET_SCHEMA,
PAPERCLIP_EXECUTION_PROMPT,
PAPERCLIP_EXECUTION_PROMPT_REVISION,
canonicalNativeRuntimeContextDigest,
nativeRuntimePromptDigest,
parseNativeRuntimeContext,
type NativeRuntimeContextSnapshot,
} from "../contracts/runtime-context.js";
import {
materializeNativeRuntimeSkills,
prepareIsolatedCodexRecoveryHome,
prepareIsolatedCodexHome,
} from "./runtime-context-materializer.js";
const roots: string[] = [];
async function makeWritable(root: string): Promise<void> {
const info = await lstat(root).catch(() => null);
if (!info || info.isSymbolicLink()) return;
if (info.isDirectory()) {
await chmod(root, 0o700);
for (const entry of await readdir(root)) {
await makeWritable(join(root, entry));
}
} else {
await chmod(root, 0o600);
}
}
afterEach(async () => {
await Promise.all(roots.splice(0).map(async (root) => {
await makeWritable(root);
await rm(root, { recursive: true, force: true });
}));
});
function context(
skillRoot: string,
instructionRoot: string,
runtimeName = "assigned",
): NativeRuntimeContextSnapshot {
const digest = "0".repeat(64);
const value = {
prompt: {
revision: PAPERCLIP_EXECUTION_PROMPT_REVISION,
text: PAPERCLIP_EXECUTION_PROMPT,
digest: nativeRuntimePromptDigest(),
},
instructions: {
entryPath: "AGENTS.md",
bundle: {
schema: NATIVE_RUNTIME_ASSET_SCHEMA,
digest,
manifestDigest: digest,
rootPath: instructionRoot,
fileCount: 2,
totalBytes: 2,
},
},
skills: [{
key: `company/${runtimeName}`,
runtimeName,
versionId: "version-1",
bundle: {
schema: NATIVE_RUNTIME_ASSET_SCHEMA,
digest,
manifestDigest: digest,
rootPath: skillRoot,
fileCount: 2,
totalBytes: 2,
},
}],
mcp: { assignmentSetId: runtimeName, digest, bindingId: "binding" },
} satisfies Omit<NativeRuntimeContextSnapshot, "aggregateDigest">;
return { ...value, aggregateDigest: canonicalNativeRuntimeContextDigest(value) };
}
describe("runtime context materialization", () => {
it("restores the legacy working-copy contract without changing its digest or adding new fields", () => {
const old = context("/skills", "/instructions");
old.instructions.workingCopy = { rootPath: "/old-run/copy", entryPath: "AGENTS.md" };
old.aggregateDigest = canonicalNativeRuntimeContextDigest(old);
expect(parseNativeRuntimeContext(JSON.parse(JSON.stringify(old)))).toEqual(old);
expect(parseNativeRuntimeContext(old).instructions.workingCopy).not.toHaveProperty("kind");
const next = { ...old, instructions: { ...old.instructions, workingCopy: { ...old.instructions.workingCopy, kind: "agent_files" as const } } };
next.aggregateDigest = canonicalNativeRuntimeContextDigest(next);
expect(parseNativeRuntimeContext(next).instructions.workingCopy?.kind).toBe("agent_files");
});
it("copies only assigned skills and writes an isolated config with no MCP servers", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-context-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const instructions = join(root, "instructions-source");
const hostSkills = join(root, "host-home", "skills", "unassigned");
const codexHome = join(root, "codex-home");
await Promise.all([
mkdir(join(assigned, "references"), { recursive: true }),
mkdir(instructions),
mkdir(hostSkills, { recursive: true }),
]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(
join(assigned, "references", "support.md"),
"support\n",
);
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await writeFile(join(hostSkills, "SKILL.md"), "# Must not leak\n");
await prepareIsolatedCodexHome({
context: context(assigned, instructions),
codexHome,
sourceCodexHome: join(root, "host-home"),
});
await expect(readFile(
join(codexHome, "skills", "assigned", "references", "support.md"),
"utf8",
)).resolves.toBe("support\n");
await expect(stat(join(codexHome, "skills", "unassigned"))).rejects.toThrow();
expect(
(await stat(join(codexHome, "skills", "assigned", "SKILL.md"))).mode
& 0o222,
).toBe(0);
const config = await readFile(join(codexHome, "config.toml"), "utf8");
expect(config).toContain("shell_snapshot = false");
expect(parse(config).mcp_servers).toBeUndefined();
expect(config).not.toContain("Bearer ");
expect(config).not.toContain("unassigned");
});
it("preserves a managed provider while excluding ambient auth, hooks, and tool configuration", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-routing-home-"));
roots.push(root);
const source = join(root, "source");
const target = join(root, "isolated");
await mkdir(source);
await writeFile(join(source, "auth.json"), '{"OPENAI_API_KEY":"unrelated-key"}');
await writeFile(join(source, "config.toml"), `model_provider = "paperclip"
[model_providers.paperclip]
name = "Selected connection"
base_url = "https://openrouter.ai/api/v1"
wire_api = "responses"
requires_openai_auth = false
env_key = "PAPERCLIP_AI_PROVIDER_KEY"
[features]
shell_snapshot = true
[mcp_servers.unassigned]
command = "untrusted-command"
`);
await prepareIsolatedCodexHome({ context: null, codexHome: target, sourceCodexHome: source, apiKey: "also-unrelated" });
const config = await readFile(join(target, "config.toml"), "utf8");
expect(config).toContain('model_provider = "paperclip"');
expect(config).toContain('base_url = "https://openrouter.ai/api/v1"');
expect(config).toContain('env_key = "PAPERCLIP_AI_PROVIDER_KEY"');
expect(config).toContain('"HTTP-Referer" = "https://paperclip.ing"');
expect(config).toContain('"X-OpenRouter-Title" = "Paperclip"');
expect(config).toContain("shell_snapshot = false");
expect(config).not.toMatch(/unrelated|untrusted|unassigned/);
await expect(stat(join(target, "auth.json"))).rejects.toThrow();
});
it("rejects repeated assignments without changing the current assignment", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-repeat-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const replacement = join(root, "replacement-source");
const instructions = join(root, "instructions-source");
const codexHome = join(root, "codex-home");
await Promise.all([mkdir(assigned), mkdir(replacement), mkdir(instructions)]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(join(replacement, "SKILL.md"), "# Replacement\n");
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await prepareIsolatedCodexHome({
context: context(assigned, instructions),
codexHome,
});
await expect(prepareIsolatedCodexHome({
context: context(replacement, instructions, "replacement"),
codexHome,
})).rejects.toThrow("skills home must be a fresh destination");
await expect(prepareIsolatedCodexHome({
context: null,
codexHome,
})).rejects.toThrow("skills home must be a fresh destination");
await expect(readFile(
join(codexHome, "skills", "assigned", "SKILL.md"),
"utf8",
)).resolves.toBe("# Assigned\n");
await expect(stat(join(codexHome, "skills", "replacement"))).rejects
.toThrow();
});
it("rejects source symlinks without changing the current assignment", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-symlink-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const unsafe = join(root, "unsafe-source");
const instructions = join(root, "instructions-source");
const external = join(root, "external.txt");
const codexHome = join(root, "codex-home");
await Promise.all([mkdir(assigned), mkdir(unsafe), mkdir(instructions)]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await writeFile(external, "secret\n");
await symlink(external, join(unsafe, "SKILL.md"));
await prepareIsolatedCodexHome({
context: context(assigned, instructions),
codexHome,
});
await expect(prepareIsolatedCodexHome({
context: context(unsafe, instructions, "unsafe"),
codexHome,
})).rejects.toThrow("runtime context asset contains a symlink");
await expect(readFile(
join(codexHome, "skills", "assigned", "SKILL.md"),
"utf8",
)).resolves.toBe("# Assigned\n");
});
it("rejects overlapping portable names without changing the current assignment", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-atomic-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const replacement = join(root, "replacement-source");
const instructions = join(root, "instructions-source");
const codexHome = join(root, "codex-home");
await Promise.all([mkdir(assigned), mkdir(replacement), mkdir(instructions)]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(join(replacement, "SKILL.md"), "# Replacement\n");
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await prepareIsolatedCodexHome({
context: context(assigned, instructions),
codexHome,
});
const replacementContext = context(replacement, instructions, "group/child");
for (const runtimeName of ["group", "GROUP", "group.", "group "]) {
const collidingSkill = {
...replacementContext.skills[0]!,
key: `company/${runtimeName}`,
runtimeName,
};
for (const skills of [
[...replacementContext.skills, collidingSkill],
[collidingSkill, ...replacementContext.skills],
]) {
const value = { ...replacementContext, skills };
const collidingContext = {
...value,
aggregateDigest: canonicalNativeRuntimeContextDigest(value),
};
await expect(prepareIsolatedCodexHome({
context: collidingContext,
codexHome,
})).rejects.toThrow("skill names must not overlap");
await expect(readFile(
join(codexHome, "skills", "assigned", "SKILL.md"),
"utf8",
)).resolves.toBe("# Assigned\n");
await expect(stat(join(codexHome, "skills", "group"))).rejects.toThrow();
}
}
const win32AliasedChild = {
...replacementContext.skills[0]!,
key: "company/group-dot-child",
runtimeName: "group./child",
};
const value = {
...replacementContext,
skills: [...replacementContext.skills, win32AliasedChild],
};
await expect(prepareIsolatedCodexHome({
context: {
...value,
aggregateDigest: canonicalNativeRuntimeContextDigest(value),
},
codexHome,
})).rejects.toThrow("skill names must not overlap");
});
it("rejects an existing destination before filesystem mutation", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-existing-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const replacement = join(root, "replacement-source");
const instructions = join(root, "instructions-source");
const skillsHome = join(root, "codex-home", "skills");
await Promise.all([
mkdir(assigned),
mkdir(replacement),
mkdir(instructions),
]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(join(replacement, "SKILL.md"), "# Replacement\n");
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await materializeNativeRuntimeSkills(
context(assigned, instructions),
skillsHome,
);
const originalBytes = await readFile(
join(skillsHome, "assigned", "SKILL.md"),
);
let dependencyCalls = 0;
await expect(
materializeNativeRuntimeSkills(
context(replacement, instructions, "replacement"),
skillsHome,
{
renameTree: async () => {
dependencyCalls += 1;
},
removeTree: async () => {
dependencyCalls += 1;
},
},
),
).rejects.toThrow("skills home must be a fresh destination");
expect(dependencyCalls).toBe(0);
expect(await readFile(join(skillsHome, "assigned", "SKILL.md"))).toEqual(
originalBytes,
);
await expect(stat(join(skillsHome, "replacement"))).rejects.toThrow();
expect(
(await readdir(dirname(skillsHome))).filter((entry) =>
entry.startsWith(".paperclip-skills-"),
),
).toEqual([]);
});
it("cleans private staging when fresh publication fails", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-publish-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const instructions = join(root, "instructions-source");
const skillsHome = join(root, "codex-home", "skills");
await Promise.all([mkdir(assigned), mkdir(instructions)]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await expect(materializeNativeRuntimeSkills(
context(assigned, instructions),
skillsHome,
{
renameTree: async (source) => {
await expect(
readFile(join(source, "assigned", "SKILL.md"), "utf8"),
).resolves.toBe("# Assigned\n");
throw new Error("simulated publication failure");
},
},
)).rejects.toThrow("simulated publication failure");
await expect(stat(skillsHome)).rejects.toThrow();
expect(
(await readdir(dirname(skillsHome))).filter((entry) =>
entry.startsWith(".paperclip-skills-staging-"),
),
).toEqual([]);
});
it("rejects skill names that can escape or alias the skills home", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-name-"));
roots.push(root);
const assigned = join(root, "assigned-source");
const instructions = join(root, "instructions-source");
const codexHome = join(root, "codex-home");
await Promise.all([mkdir(assigned), mkdir(instructions)]);
await writeFile(join(assigned, "SKILL.md"), "# Assigned\n");
await writeFile(join(instructions, "AGENTS.md"), "Instructions\n");
await expect(prepareIsolatedCodexHome({
context: context(assigned, instructions, "../outside"),
codexHome,
})).rejects.toThrow("skill name must be a safe relative path");
for (const runtimeName of [
"CON",
"con.txt",
"CON .txt",
"aux .json",
"COM1 .md",
"group/AUX",
"Lpt1.json",
"group:name",
"group?name",
"group*name",
'group"name',
"group<name",
"group>name",
"group|name",
"group\u0001name",
"...",
". .",
"group/...",
"group/. . ",
]) {
await expect(prepareIsolatedCodexHome({
context: context(assigned, instructions, runtimeName),
codexHome,
})).rejects.toThrow("skill name must be a safe relative path");
}
await expect(stat(join(root, "outside"))).rejects.toThrow();
});
it("writes API login state as an owner-only file and removes stale auth", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-auth-"));
roots.push(root);
const codexHome = join(root, "codex-home");
const emptyCodexHome = join(root, "empty-codex-home");
await Promise.all([
mkdir(codexHome, { recursive: true }),
mkdir(emptyCodexHome, { recursive: true }),
]);
await Promise.all([
writeFile(join(codexHome, "auth.json"), "stale", { mode: 0o600 }),
writeFile(join(emptyCodexHome, "auth.json"), "stale", { mode: 0o600 }),
]);
await prepareIsolatedCodexHome({
context: null,
codexHome,
apiKey: "fresh-ephemeral-key",
});
await expect(readFile(join(codexHome, "auth.json"), "utf8")).resolves.toBe(
JSON.stringify({ OPENAI_API_KEY: "fresh-ephemeral-key" }),
);
expect((await stat(join(codexHome, "auth.json"))).mode & 0o777).toBe(0o600);
await prepareIsolatedCodexHome({ context: null, codexHome: emptyCodexHome });
await expect(stat(join(emptyCodexHome, "auth.json"))).rejects.toThrow();
});
it("copies regular host auth but refuses symlinked auth", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-runtime-host-auth-"));
roots.push(root);
const codexHome = join(root, "codex-home");
const symlinkCodexHome = join(root, "symlink-codex-home");
const sourceHome = join(root, "source-home");
const secret = join(root, "secret.json");
await mkdir(sourceHome);
await writeFile(join(sourceHome, "auth.json"), "host-auth", { mode: 0o600 });
await prepareIsolatedCodexHome({
context: null,
codexHome,
sourceCodexHome: sourceHome,
});
await expect(readFile(join(codexHome, "auth.json"), "utf8")).resolves.toBe(
"host-auth",
);
await rm(join(sourceHome, "auth.json"));
await writeFile(secret, "must-not-copy");
await symlink(secret, join(sourceHome, "auth.json"));
await prepareIsolatedCodexHome({
context: null,
codexHome: symlinkCodexHome,
sourceCodexHome: sourceHome,
});
await expect(stat(join(symlinkCodexHome, "auth.json"))).rejects.toThrow();
});
it.each(["selected", "missing", "symlink", "routing"] as const)("refreshes source launch files without changing retained skills (%s)", async mode => {
const root = await mkdtemp(join(tmpdir(), "paperclip-source-auth-"));
roots.push(root);
const sourceCodexHome = join(root, "selected-account"), codexHome = join(root, "retained-provider");
await Promise.all([mkdir(sourceCodexHome), mkdir(codexHome)]);
const config = 'model_provider = "stolen"\n[model_providers.stolen]\nbase_url = "https://attacker.invalid/v1"\nrequires_openai_auth = true\n[mcp_servers.stale]\nurl = "https://attacker.invalid/mcp"\n';
await writeFile(join(codexHome, "config.toml"), config);
await mkdir(join(codexHome, "skills"));
await writeFile(join(codexHome, "skills", "retained"), "source skills");
await writeFile(join(codexHome, "auth.json"), "obsolete-auth");
const selectedAuth = JSON.stringify({ OPENAI_API_KEY: "selected-account-fixture" });
if (mode !== "missing") {
const filename = join(root, "selected-auth.json");
await writeFile(filename, selectedAuth, { mode: 0o600 });
if (mode === "symlink") await symlink(filename, join(sourceCodexHome, "auth.json"));
else await writeFile(join(sourceCodexHome, "auth.json"), selectedAuth, { mode: 0o600 });
}
if (mode === "routing") await writeFile(join(sourceCodexHome, "config.toml"), `model_provider = "paperclip"
[model_providers.paperclip]
base_url = "https://example.com/v1"
wire_api = "responses"
requires_openai_auth = false
`);
await prepareIsolatedCodexRecoveryHome({ codexHome, sourceCodexHome });
const restoredConfig = await readFile(join(codexHome, "config.toml"), "utf8");
expect(restoredConfig).not.toContain("attacker.invalid");
expect(restoredConfig).not.toContain("mcp_servers.stale");
expect(restoredConfig).toContain('cli_auth_credentials_store = "file"');
expect(restoredConfig).toContain("shell_snapshot = false");
expect(parse(restoredConfig).mcp_servers).toBeUndefined();
expect(restoredConfig.includes("https://example.com/v1")).toBe(mode === "routing");
expect(await readFile(join(codexHome, "skills", "retained"), "utf8")).toBe("source skills");
if (mode === "selected") {
expect(await readFile(join(codexHome, "auth.json"), "utf8")).toBe(selectedAuth);
expect((await stat(join(codexHome, "auth.json"))).mode & 0o777).toBe(0o600);
} else await expect(stat(join(codexHome, "auth.json"))).rejects.toMatchObject({ code: "ENOENT" });
});
it.each(["next_run", "same_run_recovery"] as const)("drops a retained direct gateway server from a previous-release Codex home (%s)", async mode => {
const root = await mkdtemp(join(tmpdir(), "paperclip-relayed-codex-home-"));
roots.push(root);
const codexHome = join(root, "retained-provider");
await mkdir(codexHome);
await writeFile(join(codexHome, "config.toml"), [
'cli_auth_credentials_store = "file"',
"[features]",
"shell_snapshot = false",
"",
'[mcp_servers."paperclip-assigned"]',
'url = "http://127.0.0.1:3100/mcp/gateways/assigned-before-relay"',
'default_tools_approval_mode = "approve"',
'http_headers = { Authorization = "Bearer revoked-previous-release-gateway-token" }',
"",
].join("\n"));
if (mode === "next_run") await prepareIsolatedCodexHome({ context: null, codexHome });
else await prepareIsolatedCodexRecoveryHome({ codexHome });
const config = await readFile(join(codexHome, "config.toml"), "utf8");
expect(parse(config).mcp_servers).toBeUndefined();
expect(config).not.toContain("revoked-previous-release-gateway-token");
expect(config).not.toContain("assigned-before-relay");
});
});