Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix: keep hosted path inventories outside captured scan output (#2110)

Michael D'Angelo6ce90ee16c3d
diff --git a/plugins/codex-security/.codex-plugin/plugin.json b/plugins/codex-security/.codex-plugin/plugin.json
index ed4eeceb5..f346c86a7 100644
--- a/plugins/codex-security/.codex-plugin/plugin.json
+++ b/plugins/codex-security/.codex-plugin/plugin.json
@@ -20,6 +20,7 @@
"mcpServers": "./.mcp.json",
"codexSecurity": {
"directDeepScanEngine": 1,
+ "hostedScopeInventory": 1,
"workerProviderSnapshot": 4
},
"interface": {
diff --git a/plugins/codex-security/mcp-app/helpers-main.ts b/plugins/codex-security/mcp-app/helpers-main.ts
index b412c3633..5f72d187a 100644
--- a/plugins/codex-security/mcp-app/helpers-main.ts
+++ b/plugins/codex-security/mcp-app/helpers-main.ts
@@ -88,6 +88,7 @@ function runHelper(): void {
if (
command === "generate-in-scope-files" ||
command === "make-repo-scope-input" ||
+ command === "make-hosted-repo-scope-input" ||
command === "make-diff-rank-input"
) {
void inventoryCommand(command, args).then((code) => {
diff --git a/plugins/codex-security/mcp-app/src/helpers/generate-inventory.ts b/plugins/codex-security/mcp-app/src/helpers/generate-inventory.ts
index 45940e7fa..7c199d010 100644
--- a/plugins/codex-security/mcp-app/src/helpers/generate-inventory.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/generate-inventory.ts
@@ -44,14 +44,22 @@ import {
runRipgrep,
} from "./inventory-git";
import { PREVIEW_BYTES, previewForBytes, sampleFile } from "./source-preview";
+import {
+ writeHostedOutput,
+ writeHostedScopeInventory,
+} from "./hosted-scope-inventory";
export type InventoryCommand =
- "generate-in-scope-files" | "make-repo-scope-input" | "make-diff-rank-input";
+ | "generate-in-scope-files"
+ | "make-repo-scope-input"
+ | "make-hosted-repo-scope-input"
+ | "make-diff-rank-input";
export interface InventoryOptions {
repo: string;
out: string;
scope?: string;
scopesFile?: string;
+ stateDir?: string;
area?: string;
previewBytes?: number;
base?: string;
@@ -208,17 +216,14 @@ function inventoryOutput(value: string): string {
return output;
}
-function writeInventory(output: string, rows: Buffer[]): number {
- const unique = [
- ...new Map(rows.map((row) => [row.toString("hex"), row])).values(),
- ].sort(Buffer.compare);
+function replaceInventory(output: string, rows: Buffer[]): void {
mkdir(dirname(output));
const temporary = append(
dirname(output),
`.${randomBytes(12).toString("hex")}.tmp`,
);
try {
- writeFile(temporary, unique, true);
+ writeFile(temporary, rows, true);
if (windows)
windowsFiles().rename(
Buffer.from(temporary, "utf16le"),
@@ -231,14 +236,13 @@ function writeInventory(output: string, rows: Buffer[]): number {
else unlinkSync(fsPath(temporary));
}
}
- return unique.length;
}
export async function generateInventory(
command: InventoryCommand,
options: InventoryOptions,
home = environmentValue("HOME"),
-): Promise<number> {
+): Promise<{ count: number; output: string }> {
const repo = canonical(expandHome(options.repo, home));
if (!directory(repo)) throw new Error(`Repo path not found: ${repo}`);
const outputPath = expandHome(options.out, home),
@@ -418,22 +422,43 @@ export async function generateInventory(
}
}
}
- if (inventory) return writeInventory(output, inventoryRows);
- mkdir(dirname(output));
- writeFile(
- output,
- [...rankRows.values()]
- .sort((left, right) => compare(left.path, right.path))
- .map((row) =>
- Buffer.from(
- stringifyJson(row, 0).replace(
- /[\u007f-\uffff]/g,
- (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
- ) + (windows ? "\r\n" : "\n"),
- ),
+ if (inventory) {
+ const unique = [
+ ...new Map(
+ inventoryRows.map((row) => [row.toString("hex"), row]),
+ ).values(),
+ ].sort(Buffer.compare);
+ replaceInventory(output, unique);
+ return { count: unique.length, output };
+ }
+ const rows = [...rankRows.values()]
+ .sort((left, right) => compare(left.path, right.path))
+ .map((row) =>
+ Buffer.from(
+ stringifyJson(row, 0).replace(
+ /[\u007f-\uffff]/g,
+ (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
+ ) + (windows ? "\r\n" : "\n"),
),
- );
- return rankRows.size;
+ );
+ if (command === "make-hosted-repo-scope-input") {
+ if (options.stateDir !== undefined) {
+ const hosted = writeHostedScopeInventory(
+ expandHome(options.stateDir, home),
+ expandHome(options.scopesFile!, home),
+ repo,
+ output,
+ rows,
+ );
+ if (hosted !== undefined) return { count: rows.length, output: hosted };
+ }
+ if (windows) replaceInventory(output, rows);
+ else writeHostedOutput(output, rows);
+ } else {
+ mkdir(dirname(output));
+ writeFile(output, rows);
+ }
+ return { count: rows.length, output };
}
export async function inventoryCommand(
@@ -443,23 +468,18 @@ export async function inventoryCommand(
): Promise<number> {
const inventory = command === "generate-in-scope-files",
diff = command === "make-diff-rank-input",
- scoped = command === "make-repo-scope-input";
+ scoped = !inventory && !diff;
const required = [
"repo",
"out",
- ...(inventory
- ? ["scope"]
- : diff
- ? ["base"]
- : scoped
- ? ["scopes-file"]
- : []),
+ inventory ? "scope" : diff ? "base" : "scopes-file",
];
const optional = inventory
? ["diff-base", "diff-head", "diff-mode"]
: diff
? ["head", "mode", "area", "preview-bytes"]
: [];
+ if (command === "make-hosted-repo-scope-input") optional.push("state-dir");
const usage = `usage: launch_codex_security_mcp[.cmd] --helper ${command} ${required.map((name) => `--${name} VALUE`).join(" ")}`;
try {
let values: Record<string, string | boolean | undefined>;
@@ -514,13 +534,14 @@ Defaults: scope=., head=HEAD, mode=revisions, preview-bytes=1024; area uses the
error instanceof Error ? error.message : String(error),
);
}
- const count = await generateInventory(
+ const { count, output } = await generateInventory(
command,
{
repo: values.repo as string,
out: values.out as string,
scope: values.scope as string | undefined,
scopesFile: values["scopes-file"] as string | undefined,
+ stateDir: values["state-dir"] as string | undefined,
area: values.area as string | undefined,
previewBytes:
values["preview-bytes"] === undefined
@@ -535,7 +556,7 @@ Defaults: scope=., head=HEAD, mode=revisions, preview-bytes=1024; area uses the
print(
inventory
? `Recorded ${count} in-scope files.`
- : `Wrote ${count} ${scoped ? "scoped paths" : "rows"} to ${expandHome(values.out as string, home)}`,
+ : `Wrote ${count} ${scoped ? "scoped paths" : "rows"} to ${output}`,
);
return 0;
} catch (error) {
diff --git a/plugins/codex-security/mcp-app/src/helpers/hosted-scope-inventory.ts b/plugins/codex-security/mcp-app/src/helpers/hosted-scope-inventory.ts
new file mode 100644
index 000000000..81a09d230
--- /dev/null
+++ b/plugins/codex-security/mcp-app/src/helpers/hosted-scope-inventory.ts
@@ -0,0 +1,158 @@
+import { randomBytes } from "node:crypto";
+import fs from "node:fs";
+import { basename, dirname, isAbsolute, join } from "node:path";
+import { ancestors, append, sameFile } from "./inventory-paths";
+import { mkdir, normalizePath, resolvedPathText } from "./helper-files";
+import { decodePosixBytes, encodePosixPath } from "./posix-path";
+
+const readWithoutFollowingLinks =
+ fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK;
+
+// A shared binding may use one protected alias. Use ordinary scan output
+// for more complex path layouts instead of resolving them on the executor.
+function trustedStatePath(
+ path: string,
+ uid: number,
+ repo: string,
+ scan: string,
+ allowAlias = true,
+): boolean {
+ const spelling = normalizePath(path);
+ if (spelling.split("/").includes("..")) return false;
+ for (const directory of [...ancestors(spelling)].reverse()) {
+ const encoded = encodePosixPath(directory);
+ const info = fs.lstatSync(encoded);
+ if (info.uid !== 0 && info.uid !== uid) return false;
+ if (sameFile(directory, repo) || sameFile(directory, scan)) return false;
+ if (info.isSymbolicLink()) {
+ if (!allowAlias) return false;
+ allowAlias = false;
+ const link = decodePosixBytes(
+ fs.readlinkSync(encoded, { encoding: "buffer" }),
+ );
+ const target = isAbsolute(link) ? link : append(dirname(directory), link);
+ if (!trustedStatePath(target, uid, repo, scan, false)) return false;
+ } else if (
+ !info.isDirectory() ||
+ ((info.mode & 0o022) !== 0 && (info.mode & 0o1000) === 0)
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/** Write to the hosted executor's bound state directory when it can protect the inventory. */
+export function writeHostedScopeInventory(
+ stateDirectory: string,
+ scopesFile: string,
+ repo: string,
+ output: string,
+ rows: Buffer[],
+): string | undefined {
+ if (process.platform !== "linux" || !isAbsolute(stateDirectory)) return;
+ try {
+ const uid = process.geteuid!();
+ const scan = resolvedPathText(dirname(output), false);
+ if (!trustedStatePath(stateDirectory, uid, repo, scan)) return;
+ const parent = resolvedPathText(stateDirectory);
+ const name = `${basename(scopesFile)}.scoped-${randomBytes(12).toString("hex")}.jsonl`;
+ const encoded = encodePosixPath(join(parent, name));
+ const fd = fs.openSync(encoded, "wx", 0o600);
+ let reader: number | undefined;
+ let cleanupFd = fd;
+ try {
+ let file = fs.fstatSync(fd);
+ // A reader could already hold a descriptor if the mount created this
+ // entry with group or other access. Only repair missing owner access.
+ if (
+ file.uid === uid &&
+ (file.mode & 0o077) === 0 &&
+ (file.mode & 0o777) !== 0o600
+ ) {
+ fs.fchmodSync(fd, 0o600);
+ // Some mounted filesystems accept chmod without enforcing the requested mode.
+ file = fs.fstatSync(fd);
+ }
+ if (file.uid !== uid || (file.mode & 0o777) !== 0o600)
+ throw new Error(
+ "The state directory does not support private inventory files.",
+ );
+ // Keep the inode pinned if closing the writer reports a delayed error.
+ reader = fs.openSync(encoded, readWithoutFollowingLinks);
+ const original = fs.fstatSync(fd, { bigint: true });
+ const pinned = fs.fstatSync(reader, { bigint: true });
+ if (pinned.dev !== original.dev || pinned.ino !== original.ino)
+ throw new Error("The state inventory changed before writing.");
+ for (const row of rows) fs.writeFileSync(fd, row);
+ cleanupFd = reader;
+ fs.closeSync(fd);
+ } catch {
+ if (cleanupFd === fd) {
+ try {
+ fs.ftruncateSync(fd, 0);
+ } catch {
+ // A storage failure can still leave the directory entry removable.
+ }
+ }
+ const held = fs.fstatSync(cleanupFd, { bigint: true });
+ const named = fs.lstatSync(encoded, {
+ bigint: true,
+ throwIfNoEntry: false,
+ });
+ if (named?.dev === held.dev && named.ino === held.ino)
+ fs.unlinkSync(encoded);
+ return undefined;
+ } finally {
+ for (const descriptor of [cleanupFd === fd ? fd : undefined, reader]) {
+ if (descriptor === undefined) continue;
+ try {
+ fs.closeSync(descriptor);
+ } catch {
+ // These cleanup closes cannot change the write result.
+ }
+ }
+ }
+ return append(stateDirectory, name);
+ } catch {
+ return undefined;
+ }
+}
+
+// Scan output can be on a mount that does not support rename.
+export function writeHostedOutput(output: string, rows: Buffer[]): void {
+ mkdir(dirname(output));
+ const path = encodePosixPath(output);
+ let writer: number;
+ try {
+ writer = fs.openSync(path, "wx");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ const entry = fs.lstatSync(path);
+ if (!entry.isFile() && !entry.isSymbolicLink()) throw error;
+ // Replace only this disposable scan entry, without writing through a link.
+ fs.unlinkSync(path);
+ writer = fs.openSync(path, "wx");
+ }
+ try {
+ const file = fs.fstatSync(writer);
+ if (file.uid === process.geteuid!() && !(file.mode & 0o400)) {
+ try {
+ fs.fchmodSync(writer, (file.mode & 0o777) | 0o600);
+ } catch {
+ // Some fixed-mode mounts permit reading even when chmod is unavailable.
+ }
+ }
+ for (const row of rows) fs.writeFileSync(writer, row);
+ } finally {
+ fs.closeSync(writer);
+ }
+ // Some filesystems expose a newly written file only after the writer closes.
+ const reader = fs.openSync(path, readWithoutFollowingLinks);
+ try {
+ if (!fs.fstatSync(reader).isFile())
+ throw new Error(`--out: expected a regular file path: ${output}`);
+ } finally {
+ fs.closeSync(reader);
+ }
+}
diff --git a/plugins/codex-security/mcp-app/tests/test_hosted_scope_inventory.ts b/plugins/codex-security/mcp-app/tests/test_hosted_scope_inventory.ts
new file mode 100644
index 000000000..acd95627f
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_hosted_scope_inventory.ts
@@ -0,0 +1,293 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, dirname, join } from "node:path";
+import { test, type TestContext } from "node:test";
+import { importSource } from "./import-module.ts";
+
+const { writeHostedScopeInventory } = (await importSource(
+ join(import.meta.dirname, "../src/helpers/hosted-scope-inventory.ts"),
+)) as typeof import("../src/helpers/hosted-scope-inventory.ts");
+
+function fixture(t: TestContext) {
+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "hosted-scope-")));
+ t.after(() => fs.rmSync(base, { force: true, recursive: true }));
+ // Exercise the fixture's real permissions independently of the runner's
+ // temp mount and unmapped UIDs in a user namespace.
+ const lstat = fs.lstatSync;
+ t.mock.method(fs, "lstatSync", (...args: Parameters<typeof fs.lstatSync>) => {
+ const info = lstat(...args);
+ const path = String(args[0]);
+ if (
+ info?.isDirectory() &&
+ typeof info.mode === "number" &&
+ (path === "/" || base.startsWith(path + "/"))
+ ) {
+ info.uid = 0;
+ info.mode &= ~0o022;
+ }
+ return info;
+ });
+ const parent = join(base, "state");
+ fs.mkdirSync(parent, { mode: 0o700 });
+ const alias = join(base, "state-alias");
+ fs.symlinkSync(parent, alias);
+ const scopes = join(base, "scopes.json");
+ const repo = join(base, "repo");
+ const output = join(base, "scan", "input.jsonl");
+ function write(
+ directory = parent,
+ { text = "inventory row\n", checkout = repo, scanOutput = output } = {},
+ ) {
+ return writeHostedScopeInventory(directory, scopes, checkout, scanOutput, [
+ Buffer.from(text),
+ ]);
+ }
+ return { base, parent, alias, repo, write };
+}
+
+test(
+ "private inventories remain readable through the executor's state directory name",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { base, parent, alias, write } = fixture(t);
+ const mask = process.umask(0o777);
+ try {
+ const first = write(parent, { text: "one\n" });
+ const second = write(alias, { text: "two\n" });
+ assert.ok(first && second && first !== second);
+ for (const [path, state, expected] of [
+ [first, parent, "one\n"],
+ [second, alias, "two\n"],
+ ]) {
+ assert.equal(dirname(path), state);
+ assert.match(
+ basename(path),
+ /^scopes\.json\.scoped-[0-9a-f]{24}\.jsonl$/,
+ );
+ assert.equal(fs.statSync(path).mode & 0o777, 0o600);
+ assert.equal(fs.readFileSync(path, "utf8"), expected);
+ }
+ const transferred = join(base, "transferred-state");
+ fs.renameSync(parent, transferred);
+ fs.unlinkSync(alias);
+ fs.symlinkSync(transferred, alias);
+ assert.equal(fs.readFileSync(second, "utf8"), "two\n");
+ } finally {
+ process.umask(mask);
+ }
+ },
+);
+
+test(
+ "hosted scratch skips a private directory beneath a replaceable ancestor",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { base, parent, write } = fixture(t);
+ fs.chmodSync(base, 0o770);
+ assert.equal(write(), undefined);
+ assert.deepEqual(fs.readdirSync(parent), []);
+ },
+);
+
+test(
+ "an alternate name for the checkout or output still excludes scratch",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { base, repo, parent, alias, write } = fixture(t);
+ assert.equal(write(parent, { checkout: alias }), undefined);
+ assert.equal(
+ write(parent, { scanOutput: join(alias, "inventory") }),
+ undefined,
+ );
+ fs.mkdirSync(repo, { mode: 0o700 });
+ const checkoutLink = join(repo, "link-to-state");
+ fs.symlinkSync(parent, checkoutLink);
+ const offered = join(base, "offered-state");
+ fs.symlinkSync(checkoutLink, offered);
+ assert.equal(write(offered), undefined);
+ assert.deepEqual(fs.readdirSync(parent), []);
+ },
+);
+
+test(
+ "a state alias cannot pass through a replaceable directory",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { base, parent, write } = fixture(t);
+ const shared = join(base, "shared");
+ fs.mkdirSync(shared);
+ fs.chmodSync(shared, 0o770);
+ const hop = join(shared, "state-link");
+ fs.symlinkSync(parent, hop);
+ const nested = join(base, "outer-link");
+ fs.symlinkSync("shared/state-link", nested);
+ const trailing = join(base, "trailing-link");
+ fs.symlinkSync("outer-link/", trailing);
+ for (const alias of [hop, nested, trailing]) {
+ assert.equal(write(alias), undefined);
+ assert.deepEqual(fs.readdirSync(parent), []);
+ }
+ },
+);
+
+test(
+ "state containing a symlink followed by .. falls back",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { base, parent, write } = fixture(t);
+ const sub = join(parent, "sub");
+ fs.mkdirSync(sub, { mode: 0o700 });
+ const link = join(base, "link-to-sub");
+ fs.symlinkSync(sub, link);
+ assert.equal(write(`${link}/..`), undefined);
+ assert.deepEqual(fs.readdirSync(parent), ["sub"]);
+ },
+);
+
+test(
+ "an already-private state file works when the mount refuses chmod",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { parent, write } = fixture(t);
+ const mask = process.umask(0o077);
+ t.after(() => process.umask(mask));
+ t.mock.method(fs, "fchmodSync", () => {
+ throw Object.assign(new Error("chmod denied"), { code: "EPERM" });
+ });
+ const path = write(parent, { text: "private" });
+ assert.ok(path);
+ assert.equal(fs.statSync(path).mode & 0o777, 0o600);
+ assert.equal(fs.readFileSync(path, "utf8"), "private");
+ },
+);
+
+for (const unsupported of ["mode", "owner"] as const) {
+ test(
+ `a filesystem reporting the wrong ${unsupported} never receives inventory bytes`,
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { parent, write } = fixture(t);
+ const fstat = fs.fstatSync;
+ t.mock.method(
+ fs,
+ "fstatSync",
+ (...args: Parameters<typeof fs.fstatSync>) => {
+ const file = fstat(...args);
+ if (unsupported === "mode" && typeof file.mode === "number")
+ file.mode |= 0o044;
+ if (unsupported === "owner" && typeof file.uid === "number")
+ file.uid = process.geteuid!() + 1;
+ return file;
+ },
+ );
+ const chmod = t.mock.method(fs, "fchmodSync");
+ const written = t.mock.method(fs, "writeFileSync");
+ assert.equal(write(parent, { text: "private" }), undefined);
+ assert.equal(chmod.mock.callCount(), 0);
+ assert.equal(written.mock.callCount(), 0);
+ assert.deepEqual(fs.readdirSync(parent), []);
+ },
+ );
+}
+
+test(
+ "a partial scratch write leaves no inventory and preserves a replaced pathname",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { parent, write } = fixture(t);
+ let replacement: string | undefined;
+ const actual = fs.writeFileSync;
+ const close = fs.closeSync;
+ let scratch = "";
+ let failedFd: number | undefined;
+ let replaceAfterClose = false;
+ let linkedAtClose: boolean | undefined;
+ t.mock.method(fs, "closeSync", (fd: number) => {
+ close(fd);
+ if (fd !== failedFd || !replaceAfterClose) return;
+ // An unlinked inode can be reused as soon as its last descriptor closes.
+ linkedAtClose = fs.existsSync(scratch);
+ if (linkedAtClose) fs.unlinkSync(scratch);
+ actual(scratch, "new owner");
+ });
+ const writeRow = t.mock.method(
+ fs,
+ "writeFileSync",
+ (fd: number, bytes: Buffer) => {
+ actual(fd, bytes.subarray(0, 3));
+ scratch = join(
+ parent,
+ fs.readdirSync(parent).find((name) => name.endsWith(".jsonl"))!,
+ );
+ failedFd = fd;
+ if (replacement !== undefined) {
+ fs.renameSync(scratch, replacement);
+ actual(scratch, "other file");
+ }
+ throw Object.assign(new Error("scratch full"), { code: "ENOSPC" });
+ },
+ );
+ assert.equal(write(), undefined);
+ assert.deepEqual(fs.readdirSync(parent), []);
+ replacement = join(parent, "moved");
+ assert.equal(write(), undefined);
+ assert.equal(writeRow.mock.callCount(), 2);
+ assert.equal(fs.statSync(replacement).size, 0);
+ const remaining = fs
+ .readdirSync(parent)
+ .find((name) => name.endsWith(".jsonl"))!;
+ assert.equal(
+ fs.readFileSync(join(parent, remaining), "utf8"),
+ "other file",
+ );
+ fs.unlinkSync(join(parent, remaining));
+ t.mock.method(fs, "ftruncateSync", () => {
+ throw Object.assign(new Error("truncate denied"), { code: "EPERM" });
+ });
+ assert.equal(write(), undefined);
+ assert.equal(fs.readFileSync(scratch, "utf8"), "other file");
+ fs.unlinkSync(scratch);
+ replacement = undefined;
+ replaceAfterClose = true;
+ assert.equal(write(), undefined);
+ assert.equal(linkedAtClose, false);
+ assert.equal(fs.readFileSync(scratch, "utf8"), "new owner");
+ },
+);
+
+for (const replace of [false, true]) {
+ test(
+ `a delayed write error removes only the failed inventory (replaced=${replace})`,
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const { parent, write } = fixture(t);
+ const close = fs.closeSync;
+ const writeRow = t.mock.method(fs, "writeFileSync");
+ let writerCloses = 0;
+ t.mock.method(fs, "closeSync", (fd: number) => {
+ if (fd !== writeRow.mock.calls[0]?.arguments[0]) return close(fd);
+ writerCloses++;
+ close(fd);
+ if (replace) {
+ const scratch = join(parent, fs.readdirSync(parent)[0]!);
+ fs.unlinkSync(scratch);
+ fs.writeFileSync(scratch, "replacement");
+ }
+ throw Object.assign(new Error("quota exceeded on close"), {
+ code: "EDQUOT",
+ });
+ });
+ assert.equal(write(), undefined);
+ assert.equal(writerCloses, 1);
+ const remaining = fs.readdirSync(parent);
+ if (replace) {
+ assert.equal(remaining.length, 1);
+ assert.equal(
+ fs.readFileSync(join(parent, remaining[0]!), "utf8"),
+ "replacement",
+ );
+ } else assert.deepEqual(remaining, []);
+ },
+ );
+}
diff --git a/plugins/codex-security/mcp-app/tests/test_hosted_scope_recovery.ts b/plugins/codex-security/mcp-app/tests/test_hosted_scope_recovery.ts
new file mode 100644
index 000000000..e1b8627b7
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_hosted_scope_recovery.ts
@@ -0,0 +1,146 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import { test } from "node:test";
+
+test(
+ "hosted scope recovery creates fresh files and replaces links without altering their target",
+ { skip: process.platform !== "linux" },
+ (t) => {
+ const root = fs.mkdtempSync(join(tmpdir(), "hosted-scope-recovery-"));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const repo = join(root, "repo");
+ fs.mkdirSync(repo);
+ const scan = join(root, "scan");
+ fs.mkdirSync(scan);
+ const output = join(scan, "scoped-source-input.jsonl");
+ const sentinel = join(root, "sentinel");
+ fs.writeFileSync(sentinel, "original");
+ const scopes = join(root, "scopes.json");
+ const helper = join(
+ import.meta.dirname,
+ "../../../../sdk/typescript/_bundled_plugin/mcp/helpers.mjs",
+ );
+ const mount = join(root, "fixed-permissions.cjs");
+ fs.writeFileSync(
+ mount,
+ `
+ const fs = require("node:fs");
+ const open = fs.openSync, chmod = fs.fchmodSync;
+ const initialMode = process.umask() === 0o777 ? 0 : 0o644;
+ fs.openSync = (path, flags, mode) => {
+ const fd = open(path, flags, mode);
+ if (flags === "wx" && String(path) === ${JSON.stringify(output)}) chmod(fd, initialMode);
+ return fd;
+ };
+ if (initialMode !== 0)
+ fs.fchmodSync = () => { throw Object.assign(new Error("chmod unsupported"), { code: "ENOTSUP" }); };
+ `,
+ );
+ const noRename = join(root, "no-rename.cjs");
+ const fault = join(root, "storage-fault");
+ fs.writeFileSync(
+ noRename,
+ `
+ const fs = require("node:fs");
+ const publish = fs.renameSync;
+ fs.renameSync = () => { throw Object.assign(new Error("rename unsupported"), { code: "ENOTSUP" }); };
+ const fault = ${JSON.stringify(fault)};
+ const failure = fs.existsSync(fault) ? fs.readFileSync(fault, "utf8") : "";
+ if (failure === "write") {
+ const write = fs.writeFileSync;
+ fs.writeFileSync = (fd, data, ...args) => {
+ if (typeof fd !== "number") return write(fd, data, ...args);
+ write(fd, data.subarray(0, 1));
+ throw Object.assign(new Error("disk full"), { code: "ENOSPC" });
+ };
+ } else {
+ const open = fs.openSync, close = fs.closeSync;
+ let writer;
+ fs.openSync = (path, flags, ...args) => {
+ if (writer?.path === String(path))
+ throw Object.assign(new Error("writer still open"), { code: "EBUSY" });
+ const fd = open(path, flags, ...args);
+ if (flags === "wx") writer = { fd, path: String(path) };
+ return fd;
+ };
+ fs.closeSync = fd => {
+ close(fd);
+ if (writer?.fd !== fd) return;
+ const path = writer.path;
+ writer = undefined;
+ if (failure === "close")
+ throw Object.assign(new Error("close quota exceeded"), { code: "EDQUOT" });
+ // This mount publishes completed bytes as a new inode when the writer closes.
+ fs.copyFileSync(path, path + ".published");
+ publish(path + ".published", path);
+ };
+ }
+ `,
+ );
+ const args = ["--repo", repo, "--scopes-file", scopes, "--out", output];
+ for (const [name, link, mask, preload] of [
+ ["one.ts", fs.symlinkSync, 0o777, mount],
+ ["two.ts", fs.linkSync, 0o022, mount],
+ ["fresh.ts", undefined, 0o022, noRename],
+ ["occupied.ts", fs.linkSync, 0o022, noRename],
+ ] as const) {
+ fs.writeFileSync(join(repo, name), "source");
+ fs.writeFileSync(scopes, JSON.stringify([name]));
+ link?.(sentinel, output);
+ const run = (command: string) => {
+ const stdout = execFileSync(
+ process.execPath,
+ ["--require", preload, helper, command, ...args],
+ { encoding: "utf8", stdio: "pipe" },
+ );
+ const reported = stdout.match(/^Wrote 1 scoped paths to (.+)$/mu)?.[1];
+ assert.ok(reported, stdout);
+ return reported;
+ };
+ const previous = process.umask(mask);
+ let reported: string;
+ let ordinaryMode: number | undefined;
+ try {
+ if (!link) {
+ assert.equal(run("make-repo-scope-input"), output);
+ ordinaryMode = fs.statSync(output).mode & 0o777;
+ fs.unlinkSync(output);
+ fs.writeFileSync(fault, "write");
+ assert.throws(() => run("make-hosted-repo-scope-input"), /disk full/);
+ for (const entry of fs.readdirSync(scan))
+ assert.equal(entry, basename(output));
+ fs.writeFileSync(fault, "close");
+ for (let attempt = 0; attempt < 2; attempt++)
+ assert.throws(
+ () => run("make-hosted-repo-scope-input"),
+ /close quota exceeded/,
+ );
+ fs.unlinkSync(fault);
+ }
+ reported = run("make-hosted-repo-scope-input");
+ } finally {
+ process.umask(previous);
+ }
+ assert.deepEqual(fs.readdirSync(scan), [basename(output)]);
+ assert.equal(reported, output);
+ const mode = fs.statSync(reported).mode & 0o777;
+ assert.ok(mode & 0o400);
+ if (ordinaryMode !== undefined) assert.equal(mode, ordinaryMode);
+ assert.equal(fs.readFileSync(sentinel, "utf8"), "original");
+ assert.equal(
+ fs.readFileSync(reported, "utf8"),
+ JSON.stringify({ path: name }) + "\n",
+ );
+ fs.unlinkSync(reported);
+ if (link === fs.symlinkSync) {
+ fs.mkdirSync(output);
+ assert.throws(() => run("make-hosted-repo-scope-input"), { status: 1 });
+ assert.deepEqual(fs.readdirSync(scan), [basename(output)]);
+ fs.rmdirSync(output);
+ }
+ }
+ },
+);
diff --git a/plugins/codex-security/references/scan-artifacts.md b/plugins/codex-security/references/scan-artifacts.md
index 0d5abe6b8..65f6d28eb 100644
--- a/plugins/codex-security/references/scan-artifacts.md
+++ b/plugins/codex-security/references/scan-artifacts.md
@@ -11,7 +11,7 @@ Follow `artifact-storage.md` for storage selection, file authoring and shared th
- `scan_id=<scanId returned by the MCP scan context, or CODEX_SECURITY_SCAN_ID when provided>`
- `scan_dir=<scanDir returned by the MCP scan context>`; when `CODEX_SECURITY_SCAN_DIR` is provided, use that existing SDK-owned directory. Never derive a scan directory from a repository name, revision, timestamp or temporary-directory formula.
- For a standalone phase, use the `directory` returned by `save_codex_security_artifact` for the selected `targetPath` and `storage`, as described in `artifact-storage.md`.
-- `target_paths_file=<CODEX_SECURITY_TARGET_PATHS_FILE>` for SDK scoped-path scans; reference it as `"$CODEX_SECURITY_TARGET_PATHS_FILE"` in POSIX shells or `"$env:CODEX_SECURITY_TARGET_PATHS_FILE"` in PowerShell. This read-only scope input lives in the isolated Codex home outside the model-writable scan directory. Pass it directly to `make-repo-scope-input --scopes-file` and `bind-repo-scopes --scopes-file` before finalization, and do not print, evaluate, modify, or treat its contents as shell syntax.
+- `target_paths_file=<CODEX_SECURITY_TARGET_PATHS_FILE>` for SDK scoped-path scans; reference it as `"$CODEX_SECURITY_TARGET_PATHS_FILE"` in POSIX shells or `"$env:CODEX_SECURITY_TARGET_PATHS_FILE"` in PowerShell. This read-only scope file lives outside the scan directory. Pass it unchanged as `--scopes-file` to the SDK's primary inventory command and to `bind-repo-scopes` before finalization. For `make-hosted-repo-scope-input`, review the inventory at the path it reports. Use the supplied scan-directory recovery command only if a later shell cannot read that file. Do not print, evaluate, modify, or treat the scope file as shell syntax.
- `artifacts_dir=<scan_dir>/artifacts`
- `context_dir=<artifacts_dir>/01_context`
- `discovery_dir=<artifacts_dir>/02_discovery`
diff --git a/plugins/codex-security/skills/security-scan/SKILL.md b/plugins/codex-security/skills/security-scan/SKILL.md
index e3e846f17..79bbd9839 100644
--- a/plugins/codex-security/skills/security-scan/SKILL.md
+++ b/plugins/codex-security/skills/security-scan/SKILL.md
@@ -19,7 +19,7 @@ SDK hosts supply their own progress instructions. Use actual deduplicated review
## Workflow
-1. Resolve the authorized target, scope, scan directory, and source context. Preserve the supplied threat model, applicable inherited `SECURITY.md` guidance, and optional `CODEX_SECURITY_KNOWLEDGE_BASE`. When `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied, use the SDK's exact `make-repo-scope-input` command to resolve every requested file and non-ignored directory descendant before review. If the host does not supply the command, run `<plugin_dir>/scripts/launch_codex_security_mcp --helper make-repo-scope-input --repo <repo_root> --scopes-file "$CODEX_SECURITY_TARGET_PATHS_FILE" --out <scan_dir>/scoped-source-input.jsonl` or use the [PowerShell command](#windows-scoped-input) on Windows. Pass the resulting inventory to the core audit without widening scope; do not print, modify, or evaluate the scope file.
+1. Resolve the authorized target, scope, scan directory, and source context. Preserve the supplied threat model, applicable inherited `SECURITY.md` guidance, and optional `CODEX_SECURITY_KNOWLEDGE_BASE`. When `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied, run the SDK's primary inventory command exactly as supplied to resolve every requested file and non-ignored directory descendant before review. For `make-hosted-repo-scope-input`, use the path it reports. Run the supplied recovery command only if that inventory is missing or unreadable in a later shell. If the host does not supply an inventory command, run `<plugin_dir>/scripts/launch_codex_security_mcp --helper make-repo-scope-input --repo <repo_root> --scopes-file "$CODEX_SECURITY_TARGET_PATHS_FILE" --out <scan_dir>/scoped-source-input.jsonl` or use the [PowerShell command](#windows-scoped-input) on Windows. Pass the resulting inventory to the core audit without widening scope; do not print, modify, or evaluate the scope file.
2. Read `../../references/core-scan.md` and perform the audit within the resolved scope and configured limits. Retain its semantic `scope`, `threatModel`, `findings`, and `reviewState`, including source evidence, validation, attack paths, calibrated severity/confidence, and unresolved work.
3. Save semantic checkpoints throughout the audit as described below. For an SDK-owned scan with a bound semantic draft tool, save the first `complete: false` checkpoint as soon as the threat model is available, then checkpoint new findings and decisions and submit `complete: true` when review finishes. Without that tool, retain the model in an early unsealed canonical draft and update `scan-manifest.json` and `findings.json` using `../../references/scan-contract.md` and the SDK's exact identity and directory. Omit `scan.sealedAt` and `scan.artifacts`. Put review bookkeeping in `scan.reviewState` and set `scan.mode` to `scoped_path` for requested scopes or `repository` otherwise. On SDK file-authored paths, run the supplied scope-binding command when a target-paths file is present.
4. Verify both canonical JSON files exist. Return control for an SDK-owned scan; the SDK owns finalization and report generation. For other host-backed scans, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` once and return after it succeeds and `report.md` exists. If completion fails, surface its exact error and preserve the scan for continuation. Do not hand-author reports or reread complete canonical findings unless requested. Report complete measured token usage only; leave pending usage to the host and identify unavailable counts.
diff --git a/sdk/typescript/docs/hosted-scans.md b/sdk/typescript/docs/hosted-scans.md
index c89ee00a3..dc49252bf 100644
--- a/sdk/typescript/docs/hosted-scans.md
+++ b/sdk/typescript/docs/hosted-scans.md
@@ -208,6 +208,20 @@ needs before returning that outcome. Use shared mounts or a coordinated transfer
that preserves the supplied path bindings, not independent copies of mutable
workbench state.
+For path scans with the Linux CLI and a current plugin, use the inventory
+path the scope helper reports. A Linux executor can keep the inventory in
+`stateDirectory` outside the checkout and captured output. The state binding
+may include one protected symlink and must exclude `..` from the path and
+link target. Its protected directory must support executor-owned mode-`0600`
+files and keep a reader open across writer close.
+
+Other layouts use `scoped-source-input.jsonl` in scan output. If a later
+shell loses the inventory, run the recovery command in the prompt. It may
+replace an earlier output file, so the executor needs permission to remove it.
+State transfers include private inventories named
+`<scope-input-filename>.scoped-<24 lowercase hex digits>.jsonl`. Hosts can
+remove the request's private inventories after execution finishes.
+
Run the plugin stdio server from
`pluginRoot/scripts/launch_codex_security_mcp --stdio` with the supplied
environment. The executor needs the target files, plugin skills and registered
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index d40967783..cb9e76c30 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -2733,7 +2733,11 @@ export class CodexSecurity {
}
checkOpen();
const basePrompt = scanPrompt(
- await targetInstruction(normalized, shellPluginRoot),
+ await targetInstruction(
+ normalized,
+ shellPluginRoot,
+ this.#dependencies.hostedScan !== undefined,
+ ),
mode,
skillName,
scanId,
@@ -5318,6 +5322,7 @@ function skillNameFor(target: NormalizedTarget, mode: ScanMode): string {
async function targetInstruction(
target: NormalizedTarget,
pluginRoot: string,
+ hosted: boolean,
): Promise<string> {
if (target.kind === "repository")
return "Scan target: the entire repository.";
@@ -5338,17 +5343,40 @@ async function targetInstruction(
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
}
- const makeScope = legacyGenerator
- ? `${pluginPythonCommand()} ${shellEnvironmentReference("CODEX_SECURITY_PLUGIN_ROOT", "/scripts/generate_rank_input.py")} make-repo-scope-input --repo ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")} --scopes-file ${scopes} --out ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/scoped-source-input.jsonl")}`
- : process.platform === "win32"
- ? String.raw`cmd.exe /d /v:off /s /c '""%CODEX_SECURITY_PLUGIN_ROOT%\scripts\launch_codex_security_mcp.cmd" --helper make-repo-scope-input --repo "%CODEX_SECURITY_REPOSITORY%\." --scopes-file "%CODEX_SECURITY_TARGET_PATHS_FILE%" --out "%CODEX_SECURITY_SCAN_DIR%\scoped-source-input.jsonl""'`
- : `${helper} --helper make-repo-scope-input --repo ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")} --scopes-file ${scopes} --out ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/scoped-source-input.jsonl")}`;
+ const inventory = shellEnvironmentReference(
+ "CODEX_SECURITY_SCAN_DIR",
+ "/scoped-source-input.jsonl",
+ );
+ const scopeArgs = `--repo ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")} --scopes-file ${scopes} --out ${inventory}`;
// CMD expands the environment references once, preserving percent signs in path values.
const bindScopes =
process.platform === "win32"
? String.raw`cmd.exe /d /v:off /s /c '""%CODEX_SECURITY_PLUGIN_ROOT%\scripts\launch_codex_security_mcp.cmd" --helper bind-repo-scopes --scopes-file "%CODEX_SECURITY_TARGET_PATHS_FILE%" --manifest "%CODEX_SECURITY_SCAN_DIR%\scan-manifest.json""'`
- : `${shellEnvironmentReference("CODEX_SECURITY_PLUGIN_ROOT", "/scripts/launch_codex_security_mcp")} --helper bind-repo-scopes --scopes-file ${scopes} --manifest ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/scan-manifest.json")}`;
- return `Scan target paths: resolve every requested file and all non-ignored descendants of requested directories using ${makeScope}. Before finalization, preserve every requested scope with ${bindScopes}. Do not print, evaluate, or modify the target-paths file.`;
+ : `${helper} --helper bind-repo-scopes --scopes-file ${scopes} --manifest ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/scan-manifest.json")}`;
+ const scanTarget =
+ "Scan target paths: resolve every requested file and all non-ignored descendants of requested directories";
+ const finalize = `Before finalization, preserve every requested scope with:\n${bindScopes}\nDo not print, evaluate, or modify the target-paths file.`;
+ if (hosted && process.platform === "linux" && !legacyGenerator) {
+ const capabilities = await pluginCapabilities(pluginRoot).catch(
+ () => undefined,
+ );
+ if (capabilities?.["hostedScopeInventory"] === 1) {
+ const hostedHelper = `${helper} --helper make-hosted-repo-scope-input ${scopeArgs}`;
+ return [
+ `${scanTarget} using the hosted scope helper:`,
+ `${hostedHelper} --state-dir ${shellEnvironmentReference("CODEX_SECURITY_STATE_DIR")}`,
+ "Use the reported path. If a later shell cannot read it, use the path reported by this recovery command:",
+ hostedHelper,
+ finalize,
+ ].join("\n");
+ }
+ }
+ const makeScope = legacyGenerator
+ ? `${pluginPythonCommand()} ${shellEnvironmentReference("CODEX_SECURITY_PLUGIN_ROOT", "/scripts/generate_rank_input.py")} make-repo-scope-input ${scopeArgs}`
+ : process.platform === "win32"
+ ? String.raw`cmd.exe /d /v:off /s /c '""%CODEX_SECURITY_PLUGIN_ROOT%\scripts\launch_codex_security_mcp.cmd" --helper make-repo-scope-input --repo "%CODEX_SECURITY_REPOSITORY%\." --scopes-file "%CODEX_SECURITY_TARGET_PATHS_FILE%" --out "%CODEX_SECURITY_SCAN_DIR%\scoped-source-input.jsonl""'`
+ : `${helper} --helper make-repo-scope-input ${scopeArgs}`;
+ return `${scanTarget} using ${makeScope}. ${finalize}`;
}
if (target.kind === "refs") {
return `Scan target: Git diff from ${target.base} to ${target.head}.`;
@@ -6157,21 +6185,23 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {
return result;
}
-async function requireCurrentDeepScanPlugin(
- runtime: PreparedRuntime,
-): Promise<void> {
+async function pluginCapabilities(pluginRoot: string) {
const manifest: unknown = JSON.parse(
- await readFile(
- join(runtime.plugin.pluginRoot, ".codex-plugin", "plugin.json"),
- "utf8",
- ),
+ await readFile(join(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"),
);
const capabilities = isRecord(manifest)
? manifest["codexSecurity"]
: undefined;
+ return isRecord(capabilities) ? capabilities : undefined;
+}
+
+async function requireCurrentDeepScanPlugin(
+ runtime: PreparedRuntime,
+): Promise<void> {
+ const capabilities = await pluginCapabilities(runtime.plugin.pluginRoot);
if (
runtime.deepScanConfigPath === undefined ||
- !isRecord(capabilities) ||
+ capabilities === undefined ||
capabilities["directDeepScanEngine"] !== 1 ||
capabilities["workerProviderSnapshot"] !== 4
) {
diff --git a/sdk/typescript/src/custom-validation-prompt.ts b/sdk/typescript/src/custom-validation-prompt.ts
index 293c6839f..6d284a394 100644
--- a/sdk/typescript/src/custom-validation-prompt.ts
+++ b/sdk/typescript/src/custom-validation-prompt.ts
@@ -8,13 +8,17 @@ import { PLUGIN_NAME } from "./runtime.js";
// Review this adapter when the bundled workflows change. Never silently run
// the ordinary validation sequence with a custom-validation request.
const SOURCES = {
- "references/core-scan.md":
+ "references/core-scan.md": [
"7690b6c854de07ff15984f6d2c25ddfa1f6ae65f65876cadf2f904054b4f0679",
- "skills/security-scan/SKILL.md":
+ ],
+ "skills/security-scan/SKILL.md": [
"b6a69658d48fff6979d6690e95d2096da236bb7e51b96ebb4f92102a9863d66c",
- "skills/security-diff-scan/SKILL.md":
+ "99cfcbbaa9d5b0450881ec752a116888b05b7fe21ea7af28fd22d088882dcd46",
+ ],
+ "skills/security-diff-scan/SKILL.md": [
"09232fd5d96cfed2a5bdccd176c09b7e9ca53ebd7ac136d283bec884fde94b0d",
-} as const;
+ ],
+};
const DISABLED_TOOLS = [
"start_codex_security_standard_scan",
@@ -33,7 +37,8 @@ async function source(pluginRoot: string, name: keyof typeof SOURCES) {
"\r\n",
"\n",
);
- if (createHash("sha256").update(text).digest("hex") !== SOURCES[name]) {
+ const digest = createHash("sha256").update(text).digest("hex");
+ if (!SOURCES[name].includes(digest)) {
throw new IncompleteScanError(
`Custom validation is incompatible with the installed plugin workflow (${name}). Update the SDK and plugin together. Default validation was not started.`,
);
diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.ts
index d9633ae9f..df1a3873c 100644
--- a/sdk/typescript/tests-ts/custom-validation.test.ts
+++ b/sdk/typescript/tests-ts/custom-validation.test.ts
@@ -1237,6 +1237,9 @@ describe("custom validation", () => {
test("renders only the discovery portion of the shipped workflows", async () => {
const standard = await customDiscoveryPrompt(PLUGIN_ROOT, "security-scan");
const diff = await customDiscoveryPrompt(PLUGIN_ROOT, "security-diff-scan");
+ expect(standard.match(/^1\. .+$/mu)?.[0]).toContain(
+ "make-hosted-repo-scope-input",
+ );
expect(standard).toContain("## Baseline Auditor Prompt");
expect(standard).toContain("## Focused Investigator Prompt");
expect(standard).toContain("<plugin_dir>/references/scan-prologue.md");
diff --git a/sdk/typescript/tests-ts/hosted-scan.test.ts b/sdk/typescript/tests-ts/hosted-scan.test.ts
index 5fe37f98c..4c6746975 100644
--- a/sdk/typescript/tests-ts/hosted-scan.test.ts
+++ b/sdk/typescript/tests-ts/hosted-scan.test.ts
@@ -1,8 +1,8 @@
-import { spawn } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import { createInterface } from "node:readline";
import { createHash } from "node:crypto";
import { PassThrough, Writable } from "node:stream";
-import { readFile, realpath, stat, symlink } from "node:fs/promises";
+import { readFile, realpath, stat, symlink, unlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import { delimiter, dirname, isAbsolute, join } from "node:path";
import { afterEach, expect, mock, spyOn, test } from "bun:test";
@@ -392,6 +392,65 @@ test.each(sealedScopes)(
},
);
+test.skipIf(process.platform !== "linux").each([
+ ["private", "completed"],
+ ["private", "acceptance_unknown"],
+ ["output", "completed"],
+ ["lost", "completed"],
+] as const)(
+ "hosted scope generation with %s scratch preserves the %s receipt",
+ async (storage, status) => {
+ const input = await fixture(["service-a/nested/route [x].ts"]);
+ const outputCopy = join(input.outputDirectory, "scoped-source-input.jsonl");
+ let inventory = "";
+ const run: ScanExecutor["run"] = async (request) => {
+ const commands = request.prompt.split("\n");
+ const [primary, recovery] = commands.filter((line) =>
+ line.includes("--helper make-hosted-repo-scope-input "),
+ );
+ const environment = { ...request.runtime.environment };
+ if (storage === "output")
+ environment["CODEX_SECURITY_STATE_DIR"] =
+ request.runtime.outputDirectory;
+ const shell = (command: string) =>
+ execFileSync("/bin/sh", ["-c", command], {
+ cwd: request.runtime.outputDirectory,
+ env: environment,
+ encoding: "utf8",
+ });
+ const generate = (command: string) =>
+ shell(command).match(/^Wrote 2 scoped paths to (.+)$/mu)![1]!;
+ inventory = generate(primary!);
+ if (storage !== "output") {
+ expect(await realpath(dirname(inventory))).toBe(
+ await realpath(request.runtime.stateDirectory),
+ );
+ }
+ if (storage === "lost") {
+ await unlink(inventory);
+ inventory = generate(recovery!);
+ }
+ if (storage !== "private") expect(inventory).toBe(outputCopy);
+ if (status === "completed") {
+ await writeDraft(request);
+ shell(
+ commands.find((line) => line.includes("--helper bind-repo-scopes "))!,
+ );
+ }
+ return receipt(request, { status });
+ };
+ const result = await runHostedScan(input, { executor: { run } });
+ expect(result.status, JSON.stringify(result)).toBe(status);
+ expect(result.execution?.sessionId).toBe("host-session");
+ expect(parseJsonLines(await readFile(inventory, "utf8"))).toEqual([
+ { path: "service-a/index.ts" },
+ { path: "service-a/nested/route [x].ts" },
+ ]);
+ if (storage === "private")
+ await expect(stat(outputCopy)).rejects.toMatchObject({ code: "ENOENT" });
+ },
+);
+
test("hosted execution preserves inspected runtime tool paths", async () => {
const input = await fixture(["tools/placeholder.ts"]);
const repositoryTools = await realpath(join(input.repository, "tools"));