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

test(ci): reduce repeated release and package checks (#1981)

Michael D'Angeload9cf632a82c
diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml
index 9b2f67918..a19ecbb83 100644
--- a/.github/workflows/node-ci.yml
+++ b/.github/workflows/node-ci.yml
@@ -259,8 +259,8 @@ jobs:
- name: Inspect installed package
working-directory: sdk/typescript
env: &package-deep-retry
- # On PRs, exercise the real retry delay on each OS's floor or only runtime.
- PACKAGE_DEEP_RETRY: ${{ github.event_name != 'pull_request' || matrix.node == '22.13.0' || strategy.job-total == 1 }}
+ # Qualify retries on each OS's floor or only runtime, and on every scheduled/manual lane.
+ PACKAGE_DEEP_RETRY: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || matrix.node == '22.13.0' || strategy.job-total == 1 }}
run: node scripts/check-package.mjs ../../dist/*.tgz
- name: Check Action against the release candidate
diff --git a/sdk/typescript/TESTING.md b/sdk/typescript/TESTING.md
index 71caaee73..9a392a6bf 100644
--- a/sdk/typescript/TESTING.md
+++ b/sdk/typescript/TESTING.md
@@ -147,7 +147,12 @@ For source qualification, CI builds and inspects one package archive, then passe
that archive to jobs in the same workflow run, using the commit SHA in the
artifact name. Selected Node runtimes install and inspect the package, including
a strict NodeNext TypeScript consumer, the actual CLI, credential locking, and a
-nested Codex worker. Native plugin-build tests remain in the shared Bun suite.
+nested Codex worker. The installed Deep Scan smoke exercises a real retry on
+one runtime per OS for PRs and main pushes, and on every scheduled or manual
+qualification lane. All selected runtimes still complete direct and detached scans.
+Native plugin-build tests remain in the shared Bun suite. Each supported OS
+exercises the maintainer release preview, Git branch and commit updates,
+concurrent ref conflicts, and preservation of maintainer edits.
Typechecking and formatting run once in an independent required job, so package
consumers do not wait for those checks. Package compilation and archive
validation still finish before the test jobs start.
diff --git a/sdk/typescript/scripts/bun-test-timeout.mts b/sdk/typescript/scripts/bun-test-timeout.mts
new file mode 100644
index 000000000..608939742
--- /dev/null
+++ b/sdk/typescript/scripts/bun-test-timeout.mts
@@ -0,0 +1,93 @@
+import { parseArgs } from "node:util";
+
+// Keep arities aligned with the pinned Bun's test_params:
+// https://github.com/oven-sh/bun/blob/bun-v1.3.14/src/cli/Arguments.zig
+const optionalBunOptions = {
+ bail: { type: "string" },
+ changed: { type: "string" },
+ parallel: { type: "string" },
+ inspect: { type: "string" },
+ "inspect-wait": { type: "string" },
+ "inspect-brk": { type: "string" },
+ config: { type: "string", short: "c" },
+} as const;
+
+export function bunTestTimeout(testArguments: readonly string[]) {
+ const parsingArguments = [...testArguments];
+ let parsed;
+ let bareOptional;
+ do {
+ parsed = parseArgs({
+ args: parsingArguments,
+ allowPositionals: true,
+ strict: false,
+ tokens: true,
+ // Bun options that consume values must not turn those values into timeouts.
+ options: {
+ ...optionalBunOptions,
+ timeout: { type: "string" },
+ "test-name-pattern": { type: "string", short: "t" },
+ grep: { type: "string" },
+ "rerun-each": { type: "string" },
+ retry: { type: "string" },
+ seed: { type: "string" },
+ "coverage-reporter": { type: "string" },
+ "coverage-dir": { type: "string" },
+ reporter: { type: "string" },
+ "reporter-outfile": { type: "string" },
+ "max-concurrency": { type: "string" },
+ "path-ignore-patterns": { type: "string" },
+ "parallel-delay": { type: "string" },
+ shard: { type: "string" },
+ preload: { type: "string", short: "r" },
+ require: { type: "string" },
+ import: { type: "string" },
+ "cpu-prof-name": { type: "string" },
+ "cpu-prof-dir": { type: "string" },
+ "cpu-prof-interval": { type: "string" },
+ "heap-prof-name": { type: "string" },
+ "heap-prof-dir": { type: "string" },
+ install: { type: "string" },
+ eval: { type: "string", short: "e" },
+ print: { type: "string", short: "p" },
+ port: { type: "string" },
+ origin: { type: "string" },
+ conditions: { type: "string" },
+ "fetch-preconnect": { type: "string" },
+ "max-http-header-size": { type: "string" },
+ "dns-result-order": { type: "string" },
+ title: { type: "string" },
+ "unhandled-rejections": { type: "string" },
+ "console-depth": { type: "string" },
+ "user-agent": { type: "string" },
+ "cron-title": { type: "string" },
+ "cron-period": { type: "string" },
+ "main-fields": { type: "string" },
+ "extension-order": { type: "string" },
+ "tsconfig-override": { type: "string" },
+ define: { type: "string", short: "d" },
+ drop: { type: "string" },
+ feature: { type: "string" },
+ loader: { type: "string", short: "l" },
+ "jsx-factory": { type: "string" },
+ "jsx-fragment": { type: "string" },
+ "jsx-import-source": { type: "string" },
+ "jsx-runtime": { type: "string" },
+ "env-file": { type: "string" },
+ cwd: { type: "string" },
+ },
+ });
+ // Bun leaves a following flag outside an optional value; parseArgs does not.
+ bareOptional = parsed.tokens.find(
+ (token): token is Extract<typeof token, { kind: "option" }> =>
+ token.kind === "option" &&
+ Object.hasOwn(optionalBunOptions, token.name) &&
+ !token.inlineValue &&
+ token.value?.startsWith("-")!,
+ );
+ if (bareOptional) {
+ parsingArguments[bareOptional.index] = `--${bareOptional.name}=`;
+ }
+ } while (bareOptional);
+ return parsed.values.timeout as string | undefined;
+}
diff --git a/sdk/typescript/scripts/release-pr.mjs b/sdk/typescript/scripts/release-pr.mjs
index cd1ff51ac..14dc7d38a 100644
--- a/sdk/typescript/scripts/release-pr.mjs
+++ b/sdk/typescript/scripts/release-pr.mjs
@@ -267,9 +267,9 @@ export function createReleasePlan(history, previous = null) {
};
}
-export function createGitRepository(directory) {
+export function createGitRepository(directory, env = process.env) {
const git = (...args) =>
- gitText(args, { cwd: directory, stdio: ["pipe", "pipe", "pipe"] });
+ gitText(args, { cwd: directory, env, stdio: ["pipe", "pipe", "pipe"] });
return {
git,
ensureCommit(sha) {
diff --git a/sdk/typescript/scripts/run-ci-tests.mts b/sdk/typescript/scripts/run-ci-tests.mts
index dba9b5bbb..c60d44596 100644
--- a/sdk/typescript/scripts/run-ci-tests.mts
+++ b/sdk/typescript/scripts/run-ci-tests.mts
@@ -1,6 +1,6 @@
import { spawn } from "node:child_process";
import { mkdir, readFile, readdir } from "node:fs/promises";
-import { parseArgs } from "node:util";
+import { bunTestTimeout } from "./bun-test-timeout.mts";
import { partitionTests, type TestTimings } from "./test-shards.mts";
const selection = /^([1-9]\d*)\/([1-9]\d*)$/.exec(process.argv[2] ?? "");
@@ -45,98 +45,11 @@ const testArguments = [
...process.argv.slice(3),
...selected.map((file) => `./tests-ts/${file}`),
];
-// Keep arities aligned with the pinned Bun's test_params:
-// https://github.com/oven-sh/bun/blob/bun-v1.3.14/src/cli/Arguments.zig
-const optionalBunOptions = {
- bail: { type: "string" },
- changed: { type: "string" },
- parallel: { type: "string" },
- inspect: { type: "string" },
- "inspect-wait": { type: "string" },
- "inspect-brk": { type: "string" },
- config: { type: "string", short: "c" },
-} as const;
-const parsingArguments = [...testArguments];
-let parsed;
-let bareOptional;
-do {
- parsed = parseArgs({
- args: parsingArguments,
- allowPositionals: true,
- strict: false,
- tokens: true,
- // Bun options that consume values must not turn those values into timeouts.
- options: {
- ...optionalBunOptions,
- timeout: { type: "string" },
- "test-name-pattern": { type: "string", short: "t" },
- grep: { type: "string" },
- "rerun-each": { type: "string" },
- retry: { type: "string" },
- seed: { type: "string" },
- "coverage-reporter": { type: "string" },
- "coverage-dir": { type: "string" },
- reporter: { type: "string" },
- "reporter-outfile": { type: "string" },
- "max-concurrency": { type: "string" },
- "path-ignore-patterns": { type: "string" },
- "parallel-delay": { type: "string" },
- shard: { type: "string" },
- preload: { type: "string", short: "r" },
- require: { type: "string" },
- import: { type: "string" },
- "cpu-prof-name": { type: "string" },
- "cpu-prof-dir": { type: "string" },
- "cpu-prof-interval": { type: "string" },
- "heap-prof-name": { type: "string" },
- "heap-prof-dir": { type: "string" },
- install: { type: "string" },
- eval: { type: "string", short: "e" },
- print: { type: "string", short: "p" },
- port: { type: "string" },
- origin: { type: "string" },
- conditions: { type: "string" },
- "fetch-preconnect": { type: "string" },
- "max-http-header-size": { type: "string" },
- "dns-result-order": { type: "string" },
- title: { type: "string" },
- "unhandled-rejections": { type: "string" },
- "console-depth": { type: "string" },
- "user-agent": { type: "string" },
- "cron-title": { type: "string" },
- "cron-period": { type: "string" },
- "main-fields": { type: "string" },
- "extension-order": { type: "string" },
- "tsconfig-override": { type: "string" },
- define: { type: "string", short: "d" },
- drop: { type: "string" },
- feature: { type: "string" },
- loader: { type: "string", short: "l" },
- "jsx-factory": { type: "string" },
- "jsx-fragment": { type: "string" },
- "jsx-import-source": { type: "string" },
- "jsx-runtime": { type: "string" },
- "env-file": { type: "string" },
- cwd: { type: "string" },
- },
- });
- // Bun leaves a following flag outside an optional value; parseArgs does not.
- bareOptional = parsed.tokens.find(
- (token): token is Extract<typeof token, { kind: "option" }> =>
- token.kind === "option" &&
- Object.hasOwn(optionalBunOptions, token.name) &&
- !token.inlineValue &&
- token.value?.startsWith("-")!,
- );
- if (bareOptional) {
- parsingArguments[bareOptional.index] = `--${bareOptional.name}=`;
- }
-} while (bareOptional);
const child = spawn("bun", testArguments, {
cwd: new URL("../", import.meta.url),
env: {
...process.env,
- CODEX_SECURITY_TEST_TIMEOUT_MS: parsed.values.timeout as string | undefined,
+ CODEX_SECURITY_TEST_TIMEOUT_MS: bunTestTimeout(testArguments),
},
stdio: "inherit",
windowsHide: true,
diff --git a/sdk/typescript/tests-ts/build-plugin.test.ts b/sdk/typescript/tests-ts/build-plugin.test.ts
index c5f6e351e..07f0060a9 100644
--- a/sdk/typescript/tests-ts/build-plugin.test.ts
+++ b/sdk/typescript/tests-ts/build-plugin.test.ts
@@ -97,197 +97,200 @@ describe("bundled plugin build", () => {
}
});
- test.each(["missing", "stale"])(
- "builds the MCP runtime from source with %s native wrappers and no npm launcher",
- async (emitted) => {
- const root = await temporaryDirectory();
- const plugin = fileURLToPath(
- new URL("../../../plugins/codex-security/", import.meta.url),
- );
- const source = join(root, "plugin");
- await cp(join(plugin, "mcp-app"), join(source, "mcp-app"), {
+ test("builds the MCP runtime from source with missing and stale native wrappers and no npm launcher", async () => {
+ const root = await temporaryDirectory();
+ const plugin = fileURLToPath(
+ new URL("../../../plugins/codex-security/", import.meta.url),
+ );
+ const source = join(root, "plugin");
+ await cp(join(plugin, "mcp-app"), join(source, "mcp-app"), {
+ recursive: true,
+ filter: (path) => !["node_modules", ".preview"].includes(basename(path)),
+ });
+ for (const directory of ["schemas", "shared"]) {
+ await cp(join(plugin, directory), join(source, directory), {
recursive: true,
- filter: (path) =>
- !["node_modules", ".preview"].includes(basename(path)),
});
- for (const directory of ["schemas", "shared"]) {
- await cp(join(plugin, directory), join(source, directory), {
- recursive: true,
- });
- }
- for (const file of [
- "reserved_artifact_paths.json",
- "codex_profile.mjs",
- "codex_profile.d.mts",
- "codex_session.mjs",
- "codex_session.d.mts",
- ]) {
- await writeFixture(
- source,
- `scripts/${file}`,
- await readFile(join(plugin, "scripts", file), "utf8"),
- );
- }
- await symlink(
- join(plugin, "mcp-app", "node_modules"),
- join(source, "mcp-app", "node_modules"),
- "junction",
- );
- for (const name of await readdir(join(plugin, "native"))) {
- if (name.endsWith(".mts")) {
- await writeFixture(
- source,
- `native/${name}`,
- await readFile(join(plugin, "native", name), "utf8"),
- );
- }
- }
- await symlink(
- join(plugin, "native", "prebuilt"),
- join(source, "native", "prebuilt"),
- "junction",
- );
+ }
+ for (const file of [
+ "reserved_artifact_paths.json",
+ "codex_profile.mjs",
+ "codex_profile.d.mts",
+ "codex_session.mjs",
+ "codex_session.d.mts",
+ ]) {
await writeFixture(
source,
- "plugin-files.json",
- await readFile(join(plugin, "plugin-files.json"), "utf8"),
+ `scripts/${file}`,
+ await readFile(join(plugin, "scripts", file), "utf8"),
);
- const platformSource = join(source, "native", "platform.mts");
- await writeFile(
- platformSource,
- `Object.defineProperty(globalThis, "syntheticNativeWrapper", { value: "fresh-wrapper-source" });\n${await readFile(platformSource, "utf8")}`,
- );
- if (emitted === "stale") {
+ }
+ await symlink(
+ join(plugin, "mcp-app", "node_modules"),
+ join(source, "mcp-app", "node_modules"),
+ "junction",
+ );
+ for (const name of await readdir(join(plugin, "native"))) {
+ if (name.endsWith(".mts")) {
await writeFixture(
source,
- "native/platform.mjs",
- 'throw new Error("stale-wrapper-output");\n',
+ `native/${name}`,
+ await readFile(join(plugin, "native", name), "utf8"),
);
}
- const bin = join(root, "bin");
- const launcher = process.platform === "win32" ? "npm.cmd" : "npm";
- await writeFixture(
- bin,
- launcher,
- process.platform === "win32"
- ? "@exit /b 91\r\n"
- : "#!/bin/sh\nexit 91\n",
+ }
+ await symlink(
+ join(plugin, "native", "prebuilt"),
+ join(source, "native", "prebuilt"),
+ "junction",
+ );
+ await writeFixture(
+ source,
+ "plugin-files.json",
+ await readFile(join(plugin, "plugin-files.json"), "utf8"),
+ );
+ for (const name of ["platform", "windows-files"]) {
+ const path = join(source, "native", name + ".mts");
+ await writeFile(
+ path,
+ `Object.defineProperty(globalThis, "${name}-marker", { value: "${name}-source-marker" });\n${await readFile(path, "utf8")}`,
);
- if (process.platform !== "win32") await chmod(join(bin, launcher), 0o755);
-
- const destination = join(root, "mcp");
- await execFileAsync(
- "node",
- [
- join(source, "mcp-app", "scripts", "build_mcp_app.mjs"),
- "--output",
- destination,
- ],
- {
- env: {
- ...process.env,
- PATH: [bin, process.env["PATH"]].filter(Boolean).join(delimiter),
- },
+ }
+ await writeFixture(
+ source,
+ "native/platform.mjs",
+ 'throw new Error("stale-wrapper-output");\n',
+ );
+ const bin = join(root, "bin");
+ const launcher = process.platform === "win32" ? "npm.cmd" : "npm";
+ await writeFixture(
+ bin,
+ launcher,
+ process.platform === "win32" ? "@exit /b 91\r\n" : "#!/bin/sh\nexit 91\n",
+ );
+ if (process.platform !== "win32") await chmod(join(bin, launcher), 0o755);
+
+ const destination = join(root, "mcp");
+ await execFileAsync(
+ "node",
+ [
+ join(source, "mcp-app", "scripts", "build_mcp_app.mjs"),
+ "--output",
+ destination,
+ ],
+ {
+ env: {
+ ...process.env,
+ PATH: [bin, process.env["PATH"]].filter(Boolean).join(delimiter),
},
- );
+ },
+ );
- const contract = JSON.parse(
- await readFile(
- new URL(
- "../../../plugins/codex-security/plugin-files.json",
- import.meta.url,
- ),
- "utf8",
+ const contract = JSON.parse(
+ await readFile(
+ new URL(
+ "../../../plugins/codex-security/plugin-files.json",
+ import.meta.url,
),
- ) as { shippedExact: string[] };
- expect(await files(destination)).toEqual(
- contract.shippedExact
- .filter((path) => path.startsWith("mcp/"))
- .map((path) => path.slice(4))
- .sort(),
- );
- const chunks = (await readdir(destination))
- .filter((name) => name.startsWith("helpers.mjs.br.part-"))
- .sort();
- const runtime = brotliDecompressSync(
- Buffer.concat(
- await Promise.all(
- chunks.map((name) => readFile(join(destination, name))),
- ),
+ "utf8",
+ ),
+ ) as { shippedExact: string[] };
+ expect(await files(destination)).toEqual(
+ contract.shippedExact
+ .filter((path) => path.startsWith("mcp/"))
+ .map((path) => path.slice(4))
+ .sort(),
+ );
+ const chunks = (await readdir(destination))
+ .filter((name) => name.startsWith("helpers.mjs.br.part-"))
+ .sort();
+ const runtime = brotliDecompressSync(
+ Buffer.concat(
+ await Promise.all(
+ chunks.map((name) => readFile(join(destination, name))),
),
- ).toString("utf8");
- expect(runtime.includes("fresh-wrapper-source")).toBe(true);
- expect(runtime.includes("stale-wrapper-output")).toBe(false);
- const helper = await execFileAsync("node", [
- join(destination, "helpers.mjs"),
- "resolve-security-md",
- "--repo",
- root,
- "--list",
- ]);
- expect(helper.stdout).toBe("[]\n");
- expect(helper.stderr).toBe("");
- const repository = await temporaryDirectory();
- const policy = "Preserve this synthetic inherited security policy.";
- await writeFixture(
- repository,
- "SECURITY.md",
- `# Synthetic policy\n${policy}\n`,
- );
- const alias = join(await temporaryDirectory(), "plugin link");
- await symlink(
- root,
- alias,
- process.platform === "win32" ? "junction" : "dir",
- );
- await mkdir(join(root, "scripts"), { recursive: true });
- await copyFile(
- join(plugin, "scripts", "launch_codex_security_mcp"),
- join(root, "scripts", "launch_codex_security_mcp"),
- );
- const node = (
- await execFileAsync("node", ["--print", "process.execPath"])
- ).stdout.trim();
- for (const pluginPath of [root, alias]) {
- const linkedHelper = join(pluginPath, "mcp", "helpers.mjs");
- const list = await execFileAsync(
- process.platform === "win32" ? node : "/bin/sh",
- [
- ...(process.platform === "win32"
- ? [linkedHelper]
- : [
- join(pluginPath, "scripts", "launch_codex_security_mcp"),
- "--helper",
- ]),
- "resolve-security-md",
- "--repo",
- repository,
- "--list",
- ],
- { env: { ...process.env, CODEX_MCP_NODE_PATH: node, NODE_PATH: "" } },
- );
- expect(list.stdout).toBe('["SECURITY.md"]\n');
- expect(list.stderr).toBe("");
- const guidance = await execFileAsync(node, [
- linkedHelper,
+ ),
+ ).toString("utf8");
+ for (const marker of [
+ "platform-source-marker",
+ "windows-files-source-marker",
+ ]) {
+ expect(runtime.includes(marker), marker).toBe(true);
+ }
+ expect(
+ runtime.includes("stale-wrapper-output"),
+ "stale-wrapper-output",
+ ).toBe(false);
+ const helper = await execFileAsync("node", [
+ join(destination, "helpers.mjs"),
+ "resolve-security-md",
+ "--repo",
+ root,
+ "--list",
+ ]);
+ expect(helper.stdout).toBe("[]\n");
+ expect(helper.stderr).toBe("");
+ const repository = await temporaryDirectory();
+ const policy = "Preserve this synthetic inherited security policy.";
+ await writeFixture(
+ repository,
+ "SECURITY.md",
+ `# Synthetic policy\n${policy}\n`,
+ );
+ const alias = join(await temporaryDirectory(), "plugin link");
+ await symlink(
+ root,
+ alias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ await mkdir(join(root, "scripts"), { recursive: true });
+ await copyFile(
+ join(plugin, "scripts", "launch_codex_security_mcp"),
+ join(root, "scripts", "launch_codex_security_mcp"),
+ );
+ const node = (
+ await execFileAsync("node", ["--print", "process.execPath"])
+ ).stdout.trim();
+ for (const pluginPath of [root, alias]) {
+ const linkedHelper = join(pluginPath, "mcp", "helpers.mjs");
+ const list = await execFileAsync(
+ process.platform === "win32" ? node : "/bin/sh",
+ [
+ ...(process.platform === "win32"
+ ? [linkedHelper]
+ : [
+ join(pluginPath, "scripts", "launch_codex_security_mcp"),
+ "--helper",
+ ]),
"resolve-security-md",
"--repo",
repository,
- "--scope",
- repository,
- "--out",
- "-",
- ]);
- expect(guidance.stdout).toContain(policy);
- expect(guidance.stderr).toBe("");
- }
+ "--list",
+ ],
+ { env: { ...process.env, CODEX_MCP_NODE_PATH: node, NODE_PATH: "" } },
+ );
+ expect(list.stdout).toBe('["SECURITY.md"]\n');
+ expect(list.stderr).toBe("");
+ const guidance = await execFileAsync(node, [
+ linkedHelper,
+ "resolve-security-md",
+ "--repo",
+ repository,
+ "--scope",
+ repository,
+ "--out",
+ "-",
+ ]);
+ expect(guidance.stdout).toContain(policy);
+ expect(guidance.stderr).toBe("");
+ }
- const imported = await execFileAsync(
- "node",
- [
- "--input-type=module",
- "--eval",
- `
+ const imported = await execFileAsync(
+ "node",
+ [
+ "--input-type=module",
+ "--eval",
+ `
import assert from "node:assert/strict";
import { pathToFileURL } from "node:url";
const { default: helpers } = await import(pathToFileURL(process.argv[2]).href);
@@ -305,19 +308,19 @@ describe("bundled plugin build", () => {
}));
assert.equal(process.exitCode, undefined);
`,
- "helper-import-test",
- join(destination, "helpers.mjs"),
- ],
- { cwd: root, env: { ...process.env, NODE_PATH: "" } },
- );
- expect(imported.stdout).toBe("");
- expect(imported.stderr).toBe("");
- const workerImport = await execFileAsync(
- "node",
- [
- "--input-type=module",
- "--eval",
- `
+ "helper-import-test",
+ join(destination, "helpers.mjs"),
+ ],
+ { cwd: root, env: { ...process.env, NODE_PATH: "" } },
+ );
+ expect(imported.stdout).toBe("");
+ expect(imported.stderr).toBe("");
+ const workerImport = await execFileAsync(
+ "node",
+ [
+ "--input-type=module",
+ "--eval",
+ `
import assert from "node:assert/strict";
import { Worker } from "node:worker_threads";
import { pathToFileURL } from "node:url";
@@ -334,34 +337,33 @@ describe("bundled plugin build", () => {
});
assert.deepEqual(messages, ["imported"]);
`,
- join(destination, "helpers.mjs"),
- ],
- { cwd: root, env: { ...process.env, NODE_PATH: "" } },
- );
- expect(workerImport.stdout).toBe("");
- expect(workerImport.stderr).toBe("");
- const preflight = await execFileAsync(
- "node",
- [
- "--input-type=module",
- "--eval",
- `const runtime = await import(process.argv[1]);
+ join(destination, "helpers.mjs"),
+ ],
+ { cwd: root, env: { ...process.env, NODE_PATH: "" } },
+ );
+ expect(workerImport.stdout).toBe("");
+ expect(workerImport.stderr).toBe("");
+ const preflight = await execFileAsync(
+ "node",
+ [
+ "--input-type=module",
+ "--eval",
+ `const runtime = await import(process.argv[1]);
console.log(JSON.stringify({
preflight: typeof runtime.preflightDeepScanWorkerPermissionProfile,
profileId: runtime.DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,
}));`,
- pathToFileURL(join(destination, "permission-profile-preflight.mjs"))
- .href,
- ],
- { cwd: root },
- );
- expect(JSON.parse(preflight.stdout)).toEqual({
- preflight: "function",
- profileId: "codex_security_deep_scan_worker",
- });
- expect(preflight.stderr).toBe("");
- },
- );
+ pathToFileURL(join(destination, "permission-profile-preflight.mjs"))
+ .href,
+ ],
+ { cwd: root },
+ );
+ expect(JSON.parse(preflight.stdout)).toEqual({
+ preflight: "function",
+ profileId: "codex_security_deep_scan_worker",
+ });
+ expect(preflight.stderr).toBe("");
+ });
test.each(["compiler", "file contract"])(
"preserves the previous bundle when the %s fails",
@@ -605,42 +607,3 @@ describe("generated plugin ownership", () => {
);
});
});
-
-test("failed compiler preserves the previous bundle and its diagnostics", async () => {
- const root = await temporaryDirectory();
- const source = join(root, "source");
- const destination = join(root, "bundle");
- const contractPath = join(source, "plugin-files.json");
- await writeFixture(
- source,
- "plugin-files.json",
- JSON.stringify({
- externalOwnedExact: [".codex-plugin/plugin.json"],
- shippedExact: ["mcp/server.mjs"],
- }),
- );
- await writeFixture(source, ".codex-plugin/plugin.json", "{}");
- await writeFixture(
- source,
- "mcp-app/scripts/build_mcp_app.mjs",
- 'console.log("synthetic compiler diagnostic"); process.exit(1);',
- );
- await writeFixture(destination, "previous.txt", "previous valid bundle");
- const driver = join(root, "driver.mjs");
- await writeFile(
- driver,
- `import { buildBundledPlugin } from ${JSON.stringify(new URL("../scripts/build-plugin.mjs", import.meta.url).href)};
-try { await buildBundledPlugin(${JSON.stringify({ contractPath, destination, source })}); }
-catch (error) { console.error(error.message); process.exitCode = 1; }`,
- );
- const result = await execFileAsync(process.execPath, [driver]).then(
- () => {
- throw new Error("synthetic compiler unexpectedly succeeded");
- },
- (error: { stdout: string; stderr: string }) => error,
- );
- expect(result.stdout).toContain("synthetic compiler diagnostic");
- expect(await readFile(join(destination, "previous.txt"), "utf8")).toBe(
- "previous valid bundle",
- );
-});
diff --git a/sdk/typescript/tests-ts/package-tar-listing.test.ts b/sdk/typescript/tests-ts/package-tar-listing.test.ts
index 2f22f41ad..138fcf7dc 100644
--- a/sdk/typescript/tests-ts/package-tar-listing.test.ts
+++ b/sdk/typescript/tests-ts/package-tar-listing.test.ts
@@ -198,6 +198,28 @@ function commandPath(command: string): string {
return path;
}
+let cachedNode: string | undefined;
+const node = () => (cachedNode ??= commandPath("node"));
+let fixtureNpm: ReturnType<typeof resolveFixtureNpm> | undefined;
+
+// All consumers use the same Node/npm installation and keep independent npm configs and caches.
+async function resolveFixtureNpm() {
+ const resolved = await execFileAsync(
+ node(),
+ [
+ "--input-type=module",
+ "-e",
+ `import { resolveNpm } from ${JSON.stringify(new URL("../scripts/package-smoke-npm.mjs", import.meta.url).href)}; console.log(JSON.stringify(await resolveNpm()));`,
+ ],
+ { encoding: "utf8", windowsHide: true },
+ );
+ if (resolved.stderr) throw new Error(resolved.stderr);
+ return JSON.parse(resolved.stdout) as {
+ command: string;
+ args: string[];
+ };
+}
+
async function installPackage(
root: string,
archivePath: string,
@@ -209,20 +231,7 @@ async function installPackage(
join(consumer, "package.json"),
JSON.stringify({ name: "synthetic-consumer", private: true }),
);
- const resolved = await execFileAsync(
- commandPath("node"),
- [
- "--input-type=module",
- "-e",
- `import { resolveNpm } from ${JSON.stringify(new URL("../scripts/package-smoke-npm.mjs", import.meta.url).href)}; console.log(JSON.stringify(await resolveNpm()));`,
- ],
- { encoding: "utf8", env: environment, windowsHide: true },
- );
- expect(resolved.stderr).toBe("");
- const npm = JSON.parse(resolved.stdout) as {
- command: string;
- args: string[];
- };
+ const npm = await (fixtureNpm ??= resolveFixtureNpm());
return runPackageCommand(
consumer,
npm.command,
@@ -252,7 +261,7 @@ function checkPackage(
): Promise<{ status: number; stderr: string }> {
return runPackageCommand(
root,
- commandPath("node"),
+ node(),
[
fileURLToPath(new URL("../scripts/check-package.mjs", import.meta.url)),
archivePath,
diff --git a/sdk/typescript/tests-ts/release-automation.test.ts b/sdk/typescript/tests-ts/release-automation.test.ts
index 28a2d55e4..dd7e13a1e 100644
--- a/sdk/typescript/tests-ts/release-automation.test.ts
+++ b/sdk/typescript/tests-ts/release-automation.test.ts
@@ -1665,19 +1665,6 @@ describe("GitHub release workflow safeguards", () => {
expect(result.stderr).not.toContain("late stderr");
});
- test("rejects unsupported jq mock filters", () => {
- const result = spawnSync(
- bash,
- [
- "-c",
- `${jqMock}\nprintf '%s\\n' '{"object":{"type":"commit","sha":"abc"}}' | jq -r '.wrong | @tsv'`,
- ],
- { encoding: "utf8" },
- );
-
- expect(result.status).toBe(64);
- });
-
test("requires a real tag for protected npm publication", () => {
expect(protectedReleaseWorkflow).toContain("release-tag");
expect(protectedReleaseWorkflow).toContain('"$GITHUB_REF_TYPE"');
@@ -1850,6 +1837,78 @@ describe("GitHub release workflow safeguards", () => {
).toBe(scenario.expected);
});
+ test("only consults release metadata for a CI commit on main", async () => {
+ const cwd = directories.create("release-cut-ancestry-");
+ // A maintainer may be running with GIT_DIR, a custom template or global hooks.
+ const env = {
+ PATH: process.env["PATH"],
+ SYSTEMROOT: process.env["SYSTEMROOT"],
+ HOME: cwd,
+ GIT_CONFIG_NOSYSTEM: "1",
+ };
+ const setup = await runCommand(
+ bash,
+ [
+ "--noprofile",
+ "--norc",
+ "-c",
+ `
+set -eu
+git init --quiet --bare --template= -b main .
+git init --quiet --bare --template= -b main remote.git
+git config --local user.name "Release fixture"
+git config --local user.email "[email protected]"
+tree=$(git mktree </dev/null)
+qualified=$(git commit-tree "$tree" -m qualified)
+main=$(git commit-tree "$tree" -p "$qualified" -m main)
+candidate=$(git commit-tree "$tree" -p "$qualified" -m off-main)
+git push --quiet ./remote.git "$main:refs/heads/main"
+git remote add origin ./remote.git
+printf '%s\\n%s\\n%s\\n' "$qualified" "$main" "$candidate"
+`,
+ ],
+ { cwd, env },
+ );
+ expect(setup.status, setup.stderr).toBe(0);
+ const [qualified, main, candidate] = setup.stdout.trim().split(/\r?\n/u);
+ const script = `
+# actions/checkout detaches HEAD at the selected release SHA.
+git update-ref --no-deref HEAD "$RELEASE_SHA" || exit 1
+node() { echo "release metadata lookup" >&2; return 64; }
+npm() { echo "unexpected registry lookup" >&2; return 65; }
+${workflowStepShell(releaseCutWorkflow, "Resolve the stable package version")}
+`;
+ for (const [workflowSha, releaseSha, expectedStatus, expectedMessage] of [
+ [main, candidate, 1, "Release tags can only be cut from commits on main"],
+ [
+ candidate,
+ qualified,
+ 1,
+ "Release tags can only be cut from commits on main",
+ ],
+ [main, qualified, 64, "release metadata lookup"],
+ ] as const) {
+ const result = await runCommand(
+ bash,
+ ["--noprofile", "--norc", "-c", script],
+ {
+ cwd,
+ env: {
+ ...env,
+ GITHUB_REF: "refs/heads/main",
+ GITHUB_EVENT_NAME: "workflow_run",
+ GITHUB_OUTPUT: "/dev/null",
+ GITHUB_SHA: workflowSha,
+ RELEASE_SHA: releaseSha,
+ },
+ },
+ );
+ expect(result.status, result.stderr).toBe(expectedStatus);
+ expect(result.stderr).toContain(expectedMessage);
+ expect(result.stderr).not.toContain("unexpected registry lookup");
+ }
+ });
+
test("executes the manual release cut against all published versions", async () => {
const script = workflowStepShell(
releaseCutWorkflow,
diff --git a/sdk/typescript/tests-ts/release-cut-workflow.test.ts b/sdk/typescript/tests-ts/release-cut-workflow.test.ts
index 420afdd02..ab91a5ff2 100644
--- a/sdk/typescript/tests-ts/release-cut-workflow.test.ts
+++ b/sdk/typescript/tests-ts/release-cut-workflow.test.ts
@@ -1,34 +1,36 @@
import { readFileSync } from "node:fs";
import { expect, test } from "bun:test";
-const releaseCutWorkflow = readFileSync(
- new URL("../../../.github/workflows/node-release-cut.yml", import.meta.url),
- "utf8",
-);
-
-test("starts npm publication only after node-ci succeeds on main", () => {
- expect(releaseCutWorkflow).toContain("workflow_run:");
- expect(releaseCutWorkflow).toContain('workflows: ["node-ci"]');
- expect(releaseCutWorkflow).toContain("types: [completed]");
- expect(releaseCutWorkflow).toContain(
- "github.event.workflow_run.conclusion == 'success'",
- );
- expect(releaseCutWorkflow).toContain(
- "github.event.workflow_run.head_branch == 'main'",
- );
- expect(releaseCutWorkflow).not.toContain(" push:\n");
-});
-
-test("cuts the protected release tag from the exact successful CI commit", () => {
- expect(releaseCutWorkflow).toContain(
- "RELEASE_SHA: ${{ github.event.workflow_run.head_sha || github.sha }}",
- );
- expect(releaseCutWorkflow).toContain(
- "ref: ${{ github.event.workflow_run.head_sha || github.sha }}",
- );
- expect(releaseCutWorkflow).toContain(
- 'git merge-base --is-ancestor "$RELEASE_SHA" origin/main',
- );
- expect(releaseCutWorkflow).toContain('git rev-parse "$RELEASE_SHA^"');
- expect(releaseCutWorkflow).toContain('-f "sha=$RELEASE_SHA"');
+test("checks out the same revision used to cut tags after main CI or a manual dispatch", () => {
+ const workflow = Bun.YAML.parse(
+ readFileSync(
+ new URL(
+ "../../../.github/workflows/node-release-cut.yml",
+ import.meta.url,
+ ),
+ "utf8",
+ ),
+ ) as {
+ on: Record<string, unknown>;
+ jobs: {
+ cut: {
+ env: { RELEASE_SHA: string };
+ steps: { uses?: string; with?: { ref?: string } }[];
+ };
+ };
+ };
+ expect(workflow.on).toEqual({
+ workflow_run: {
+ workflows: ["node-ci"],
+ types: ["completed"],
+ branches: ["main"],
+ },
+ workflow_dispatch: null,
+ });
+ const { env, steps } = workflow.jobs.cut;
+ const verifiedSha = "${{ github.event.workflow_run.head_sha || github.sha }}";
+ expect(env.RELEASE_SHA).toBe(verifiedSha);
+ expect(
+ steps.find(({ uses }) => uses?.startsWith("actions/checkout@"))?.with?.ref,
+ ).toBe(verifiedSha);
});
diff --git a/sdk/typescript/tests-ts/release-pr.test.ts b/sdk/typescript/tests-ts/release-pr.test.ts
index 332ee0a4f..8e820b7d7 100644
--- a/sdk/typescript/tests-ts/release-pr.test.ts
+++ b/sdk/typescript/tests-ts/release-pr.test.ts
@@ -1,5 +1,7 @@
-import { gitText } from "./support/shell.js";
-import { cpSync, readFileSync } from "node:fs";
+import { gitText, nodeCommand, runCommand } from "./support/shell.js";
+import { cpSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { afterAll, afterEach, describe, expect, test } from "bun:test";
import { check } from "prettier";
import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
@@ -100,7 +102,10 @@ const {
};
} | null,
) => Plan;
- createGitRepository: (directory: string) => GitRepository;
+ createGitRepository: (
+ directory: string,
+ env?: NodeJS.ProcessEnv,
+ ) => GitRepository;
createGitHubClient: (
repository: string,
token: string,
@@ -137,7 +142,7 @@ const workflow = readFileSync(
new URL("../../../.github/workflows/node-release-pr.yml", import.meta.url),
"utf8",
);
-const directories = createTemporaryDirectoriesSync();
+const directories = createTemporaryDirectoriesSync(true);
afterEach(directories.cleanup);
const templates = createTemporaryDirectoriesSync();
afterAll(templates.cleanup);
@@ -262,7 +267,16 @@ class Fixture {
}
readonly directory = directories.create("release pr test ");
- readonly repo = createGitRepository(this.directory);
+ readonly environment: NodeJS.ProcessEnv = {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ ComSpec: process.env["ComSpec"],
+ PATHEXT: process.env["PATHEXT"],
+ HOME: this.directory,
+ USERPROFILE: this.directory,
+ GIT_CONFIG_NOSYSTEM: "1",
+ };
+ readonly repo = createGitRepository(this.directory, this.environment);
readonly github = new FakeGitHub(this);
readonly git = this.repo.git;
@@ -271,7 +285,7 @@ class Fixture {
cpSync(repositoryTemplate, this.directory, { recursive: true });
return;
}
- this.git("init", "-b", "main");
+ this.git("init", "--template=", "-b", "main");
this.git("config", "user.name", "Release Test");
this.git("config", "user.email", "[email protected]");
this.git("config", "commit.gpgsign", "false");
@@ -299,19 +313,29 @@ class Fixture {
}
tree(base: string | null, files: Record<string, string | null>) {
+ const entries = Object.entries(files);
+ if (base !== null && entries.length === 0)
+ return this.git("rev-parse", `${base}^{tree}`).trim();
+
this.git("read-tree", base ?? "--empty");
- for (const [path, content] of Object.entries(files)) {
+ const edits: string[] = [];
+ for (const [path, content] of entries) {
if (content === null) {
- this.git("update-index", "--force-remove", "--", path);
+ edits.push(`./${path}`);
} else {
const blob = gitText(["hash-object", "-w", "--stdin"], {
cwd: this.directory,
+ env: this.environment,
input: content,
stdio: ["pipe", "pipe", "pipe"],
}).trim();
- this.git("update-index", "--add", "--cacheinfo", "100644", blob, path);
+ edits.push("--cacheinfo", "100644", blob, path);
}
}
+ if (edits.length > 0) {
+ // --cacheinfo stages blobs; --force-remove applies to plain path arguments.
+ this.git("update-index", "--add", "--force-remove", ...edits);
+ }
return this.git("write-tree").trim();
}
@@ -746,7 +770,7 @@ describe("GitHub request transport", () => {
},
);
- test("creates and updates a release PR through serialized requests, including a concurrent commit conflict", async () => {
+ test("publishes through a concurrent commit conflict", async () => {
const fixture = new Fixture();
fixture.merge("feat: initial feature");
let conflicts = 0;
@@ -1291,6 +1315,48 @@ describe("human note ownership", () => {
});
});
+test("previews a pending release from the maintainer CLI without writing to Git or GitHub", async () => {
+ const fixture = new Fixture();
+ const main = fixture.merge("feat: initial feature");
+ const refs = fixture.git("show-ref");
+ const preload = join(fixture.directory, "github-reads.mjs");
+ writeFileSync(
+ preload,
+ `
+ globalThis.fetch = async (url, { method }) => {
+ if (method !== "GET") throw new Error("Unexpected GitHub write: " + method);
+ const path = new URL(url).pathname;
+ if (path.endsWith("/git/ref/heads/main")) return Response.json({ object: { sha: ${JSON.stringify(main)} } });
+ if (path.includes("/git/ref/heads/")) return new Response(null, { status: 404 });
+ if (path.endsWith("/pulls")) return Response.json([]);
+ throw new Error("Unexpected GitHub read: " + path);
+ };
+ `,
+ );
+ const result = await runCommand(
+ nodeCommand().command,
+ ["--import", pathToFileURL(preload).href, fileURLToPath(script)],
+ {
+ env: {
+ ...fixture.environment,
+ GH_TOKEN: "synthetic-release-token",
+ GITHUB_REPOSITORY: fixture.github.repository,
+ GIT_DIR: join(fixture.directory, ".git"),
+ GIT_WORK_TREE: fixture.directory,
+ RELEASE_PR_DRY_RUN: "true",
+ },
+ timeout: 30_000,
+ },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ action: "would-create",
+ dryRun: true,
+ plan: { version: "0.1.24", title: "chore(release): 0.1.24" },
+ });
+ expect(fixture.git("show-ref")).toBe(refs);
+});
+
describe("rolling release reconciliation", () => {
test("adds and refreshes the example pin from current main without introducing it into earlier history", async () => {
const fixture = new Fixture();
@@ -1368,31 +1434,12 @@ describe("rolling release reconciliation", () => {
expect((await fixture.run()).action).toBe("unchanged");
});
- test.each([true, false])(
- "leaves an empty release cycle unchanged with dryRun=%p",
- async (dryRun) => {
- const fixture = new Fixture();
- const result = await fixture.run(dryRun);
- expect(result.action).toBe("unchanged");
- expect(result.plan.changes).toHaveLength(0);
- expect(result.pull).toBeUndefined();
- expect(fixture.head(result.plan.branch)).toBeNull();
- expect(fixture.github.writes).toHaveLength(0);
- expect(fixture.github.pulls).toHaveLength(0);
- },
- );
-
- test("previews without writes and then creates one ready PR, refreshes it, and reuses its branch", async () => {
+ test("creates one ready PR, refreshes it, and reuses its branch", async () => {
const fixture = new Fixture();
fixture.merge("feat: initial feature", {
"plugins/codex-security/skills/example/SKILL.md":
"Example plugin instructions.\n",
});
- const preview = await fixture.run(true);
- expect(preview.action).toBe("would-create");
- expect(preview.plan.version).toBe("0.1.24");
- expect(preview.plan.title).toBe("chore(release): 0.1.24");
- expect(fixture.github.writes).toHaveLength(0);
const first = await fixture.run();
expect(first.action).toBe("created");
expect(first.reviewRequested).toBe(true);
@@ -1441,18 +1488,10 @@ describe("rolling release reconciliation", () => {
});
test("retitles an existing release PR without changing an up-to-date branch", async () => {
- const fixture = new Fixture();
- fixture.merge("fix: initial fix");
- const first = await fixture.run();
- const pull = fixture.github.pulls.find(
- (candidate) => candidate.number === first.pull,
- )!;
+ const { fixture, first, pull } = await Fixture.withInitialPull();
pull.title = "release: prepare the next Codex Security release";
const body = pull.body;
const writes = fixture.github.writes.length;
- const preview = await fixture.run(true);
- expect(preview.action).toBe("would-update");
- expect(fixture.github.writes).toHaveLength(writes);
const updated = await fixture.run();
expect(updated.action).toBe("updated");
expect(updated.headSha).toBe(first.headSha);
@@ -1783,6 +1822,47 @@ describe("rolling release reconciliation", () => {
fixture.github.pulls.filter((pull) => pull.state === "open"),
).toHaveLength(1);
});
+});
+
+describe("read-only release previews and Git history", () => {
+ test.each([true, false])(
+ "leaves an empty release cycle unchanged with dryRun=%p",
+ async (dryRun) => {
+ const fixture = new Fixture();
+ const result = await fixture.run(dryRun);
+ expect(result.action).toBe("unchanged");
+ expect(result.plan.changes).toHaveLength(0);
+ expect(result.pull).toBeUndefined();
+ expect(fixture.head(result.plan.branch)).toBeNull();
+ expect(fixture.github.writes).toHaveLength(0);
+ expect(fixture.github.pulls).toHaveLength(0);
+ },
+ );
+
+ test("previews a title update and holds the proposal after an unrelated edit", async () => {
+ const { fixture, first, pull } = await Fixture.withInitialPull();
+ const previousTitle = "release: prepare the next Codex Security release";
+ pull.title = previousTitle;
+ const refs = fixture.git("show-ref");
+ const writes = fixture.github.writes.length;
+ const preview = await fixture.run(true);
+ expect(preview.action).toBe("would-update");
+ expect(preview.plan.title).toBe(first.plan.title);
+ expect(fixture.git("show-ref")).toBe(refs);
+
+ fixture.commit(
+ first.plan.branch,
+ { "sdk/typescript/src/example.ts": "export const changed = true;\n" },
+ "fix: unrelated source change",
+ );
+ const editedRefs = fixture.git("show-ref");
+ const held = await fixture.run(true);
+ expect(held.action).toBe("held");
+ expect(held.reason).toContain("other file edits");
+ expect(fixture.git("show-ref")).toBe(editedRefs);
+ expect(pull.title).toBe(previousTitle);
+ expect(fixture.github.writes).toHaveLength(writes);
+ });
test("deduplicates rebased PRs and recognizes breaking direct commits", async () => {
const fixture = new Fixture();
diff --git a/sdk/typescript/tests-ts/skeleton.test.ts b/sdk/typescript/tests-ts/skeleton.test.ts
index 729147b29..22afa5e6f 100644
--- a/sdk/typescript/tests-ts/skeleton.test.ts
+++ b/sdk/typescript/tests-ts/skeleton.test.ts
@@ -402,18 +402,6 @@ describe("TypeScript package skeleton", () => {
}
});
- test("installs ripgrep before the independent MCP job", async () => {
- const { jobs } = await workflow("node-ci.yml");
- const steps = jobs["mcp"]!.steps!;
- const ripgrep = steps.findIndex(({ name }) => name === "Install ripgrep");
- const tests = steps.findIndex(({ name }) => name === "Test MCP app");
- expect(steps[ripgrep]?.run).toBe(".github/scripts/install-ripgrep.sh");
- expect(ripgrep).toBeLessThan(tests);
- expect(
- jobs["test"]!.steps!.some(({ name }) => name === "Test MCP app"),
- ).toBe(false);
- });
-
test("runs static checks independently and keeps diagnostic uploads non-blocking", async () => {
const { jobs } = await workflow("node-ci.yml");
const steps = Object.values(jobs).flatMap((job) => job.steps ?? []);
@@ -441,13 +429,6 @@ describe("TypeScript package skeleton", () => {
"continue-on-error": true,
});
}
- expect(
- jobs["plugin-source"]!.steps!.find(
- ({ name }) => name === "Test Python source contracts",
- )?.run,
- ).toContain(
- "-n 4 --dist worksteal --max-worker-restart 0 --durations=30 --junitxml=reports/python.xml",
- );
});
test("runs Windows native proofs with and without symbolic-link privileges", async () => {
diff --git a/sdk/typescript/tests-ts/test-shards.test.ts b/sdk/typescript/tests-ts/test-shards.test.ts
index 0ff4129ec..034a89b6f 100644
--- a/sdk/typescript/tests-ts/test-shards.test.ts
+++ b/sdk/typescript/tests-ts/test-shards.test.ts
@@ -9,12 +9,17 @@ import {
import { tmpdir } from "node:os";
import { delimiter, dirname, join } from "node:path";
import { expect, test } from "bun:test";
+import { bunTestTimeout } from "../scripts/bun-test-timeout.mts";
import { partitionTests, type TestTimings } from "../scripts/test-shards.mts";
import { readSubprocess } from "./support/shell.js";
import { temporaryDirectory } from "./support/temporary-directories.js";
async function copyRunner(root: string, timings: TestTimings = {}) {
- for (const name of ["run-ci-tests.mts", "test-shards.mts"]) {
+ for (const name of [
+ "run-ci-tests.mts",
+ "test-shards.mts",
+ "bun-test-timeout.mts",
+ ]) {
await copyFile(
new URL(`../scripts/${name}`, import.meta.url),
join(root, "scripts", name),
@@ -66,74 +71,88 @@ test("uses each platform's history and includes new files without selecting dele
});
test.each([3, 6, 7, 14])(
- "runs each eligible file once across %i native shards, including new files",
- async (count) => {
- const node = Bun.which("node");
- expect(node).not.toBeNull();
- const root = await temporaryDirectory("codex-security-native-shards-");
- try {
- await mkdir(join(root, "scripts"));
- await mkdir(join(root, "tests-ts"));
- await copyRunner(root, {
- "probe-0.test.ts": { linux: 100, darwin: 100, win32: 100 },
- "probe-1.test.ts": { linux: 80, darwin: 80, win32: 80 },
- "deleted.test.ts": { linux: 1_000, darwin: 1_000, win32: 1_000 },
- });
- const files = [
- ...Array.from({ length: 20 }, (_, index) => `probe-${index}.test.ts`),
- "newly-added.test.ts",
- ];
- const executionLog = join(root, "executed.txt");
- for (const file of files) {
- await writeFile(
- join(root, "tests-ts", file),
- `import { appendFileSync } from "node:fs";
+ "assigns each discovered file once across %i shards",
+ (count) => {
+ const files = Array.from(
+ { length: 20 },
+ (_, index) => `probe-${index}.test.ts`,
+ );
+ const shards = partitionTests(
+ files,
+ count,
+ { "deleted.test.ts": { linux: 100 } },
+ "linux",
+ );
+ expect(shards).toHaveLength(count);
+ expect(shards.every((shard) => shard.length > 0)).toBe(true);
+ expect(shards.flat().sort()).toEqual(files.sort());
+ },
+);
+
+test("runs every discovered file once across two real shards, excluding machine policy", async () => {
+ const count = 2;
+ const node = Bun.which("node");
+ expect(node).not.toBeNull();
+ const root = await temporaryDirectory("codex-security-native-shards-");
+ try {
+ await mkdir(join(root, "scripts"));
+ await mkdir(join(root, "tests-ts"));
+ await copyRunner(root, {
+ "probe-0.test.ts": { linux: 100, darwin: 100, win32: 100 },
+ "probe-1.test.ts": { linux: 80, darwin: 80, win32: 80 },
+ "deleted.test.ts": { linux: 1_000, darwin: 1_000, win32: 1_000 },
+ });
+ const files = ["probe-0.test.ts", "probe-1.test.ts", "newly-added.test.ts"];
+ const executionLog = join(root, "executed.txt");
+ for (const file of files) {
+ await writeFile(
+ join(root, "tests-ts", file),
+ `import { appendFileSync } from "node:fs";
import { test } from "bun:test";
test(${JSON.stringify(file)}, () => {
appendFileSync(${JSON.stringify(executionLog)}, ${JSON.stringify(`${file}\n`)});
});\n`,
- );
- }
- await writeFile(
- join(root, "tests-ts", "windows-machine-policy.test.ts"),
- 'throw new Error("Machine policy test must run separately");\n',
);
- const executed: string[] = [];
- for (let shard = 1; shard <= count; shard++) {
- await writeFile(executionLog, "");
- const child = Bun.spawn({
- cmd: [
- node!,
- "--experimental-strip-types",
- join(root, "scripts", "run-ci-tests.mts"),
- `${shard}/${count}`,
- ],
- env: {
- ...process.env,
- PATH: `${dirname(process.execPath)}${delimiter}${process.env["PATH"] ?? ""}`,
- },
- stdin: "ignore",
- stdout: "pipe",
- stderr: "pipe",
- timeout: 30_000,
- windowsHide: true,
- });
- const { status, stdout, stderr } = await readSubprocess(child);
- expect(status, stderr).toBe(0);
- const shardFiles = (await readFile(executionLog, "utf8"))
- .trim()
- .split("\n");
- expect(stdout).toContain(
- `Test shard ${shard}/${count}: ${shardFiles.sort().join(" ")}`,
- );
- executed.push(...shardFiles);
- }
- expect(executed.sort()).toEqual(files.sort());
- } finally {
- await rm(root, { recursive: true, force: true });
}
- },
-);
+ await writeFile(
+ join(root, "tests-ts", "windows-machine-policy.test.ts"),
+ 'throw new Error("Machine policy test must run separately");\n',
+ );
+ const executed: string[] = [];
+ for (let shard = 1; shard <= count; shard++) {
+ await writeFile(executionLog, "");
+ const child = Bun.spawn({
+ cmd: [
+ node!,
+ "--experimental-strip-types",
+ join(root, "scripts", "run-ci-tests.mts"),
+ `${shard}/${count}`,
+ ],
+ env: {
+ ...process.env,
+ PATH: `${dirname(process.execPath)}${delimiter}${process.env["PATH"] ?? ""}`,
+ },
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ timeout: 30_000,
+ windowsHide: true,
+ });
+ const { status, stdout, stderr } = await readSubprocess(child);
+ expect(status, stderr).toBe(0);
+ const shardFiles = (await readFile(executionLog, "utf8"))
+ .trim()
+ .split("\n");
+ expect(stdout).toContain(
+ `Test shard ${shard}/${count}: ${shardFiles.sort().join(" ")}`,
+ );
+ executed.push(...shardFiles);
+ }
+ expect(executed.sort()).toEqual(files.sort());
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
test("rejects an empty shard while allowing a nonempty shard with the same count", async () => {
const node = Bun.which("node");
@@ -192,6 +211,12 @@ test("propagates a subprocess exit after successful test assertions", async () =
await mkdir(join(root, "scripts"));
await mkdir(join(root, "tests-ts"));
await copyRunner(root);
+ // Exercise the two-digit selector used by Windows CI without extra processes.
+ await Promise.all(
+ Array.from({ length: 13 }, (_, index) =>
+ writeFile(join(root, "tests-ts", `earlier-${index}.test.ts`), ""),
+ ),
+ );
await writeFile(
join(root, "tests-ts", "probe.test.ts"),
`import { writeFileSync } from "node:fs";
@@ -208,7 +233,7 @@ afterAll(() => { process.exit(7); });
node!,
"--experimental-strip-types",
join(root, "scripts", "run-ci-tests.mts"),
- "1/1",
+ "14/14",
],
env: {
...process.env,
@@ -231,29 +256,38 @@ afterAll(() => { process.exit(7); });
const defaultTimeoutMs = process.platform === "win32" ? "120000" : "30000";
test.each([
- [defaultTimeoutMs, [], "available", false],
+ [defaultTimeoutMs, []],
+ ["5000", ["--timeout", "5000"]],
+ ["5000", ["--timeout=5000"]],
+ ["5000", ["--timeout", "9000", "--timeout=5000"]],
+ ["5000", ["--timeout=9000", "--timeout", "5000"]],
+ [defaultTimeoutMs, ["--", "--timeout", "5000"]],
+ [defaultTimeoutMs, ["-t", "--timeout=5000"]],
+ [defaultTimeoutMs, ["--grep", "--timeout=5000"]],
+ [defaultTimeoutMs, ["--test-name-pattern", "--timeout=5000"]],
+ ["7000", ["--timeout", "7000", "-t", "--timeout=5000"]],
+ [defaultTimeoutMs, ["--coverage-dir", "--timeout=5000"]],
+ [defaultTimeoutMs, ["--title", "--timeout=5000"]],
+ ["7000", ["--config", "--timeout=7000"]],
+ ["7000", ["-c", "--timeout=7000"]],
+ ["7000", ["--bail", "--timeout=7000"]],
+] as const)("uses timeout %s when Bun receives %p", (expected, options) => {
+ expect(
+ bunTestTimeout([
+ "test",
+ "--timeout",
+ defaultTimeoutMs,
+ ...options,
+ "./tests-ts/probe.test.ts",
+ ]),
+ ).toBe(expected);
+});
+
+test.each([
+ ["7000", ["--config", "--timeout=7000"], "available", false],
[defaultTimeoutMs, [], "available", true],
- [defaultTimeoutMs, [], "blocked directory", false],
+ [defaultTimeoutMs, ["-t", "--timeout=5000"], "blocked directory", false],
[defaultTimeoutMs, [], "blocked directory", true],
- ["5000", ["--timeout", "5000"], "available", false],
- ["5000", ["--timeout=5000"], "available", false],
- ["5000", ["--timeout", "9000", "--timeout=5000"], "available", false],
- ["5000", ["--timeout=9000", "--timeout", "5000"], "available", false],
- [defaultTimeoutMs, ["--", "--timeout", "5000"], "available", false],
- [defaultTimeoutMs, ["-t", "--timeout=5000"], "available", false],
- [defaultTimeoutMs, ["--grep", "--timeout=5000"], "available", false],
- [
- defaultTimeoutMs,
- ["--test-name-pattern", "--timeout=5000"],
- "available",
- false,
- ],
- ["7000", ["--timeout", "7000", "-t", "--timeout=5000"], "available", false],
- [defaultTimeoutMs, ["--coverage-dir", "--timeout=5000"], "available", false],
- [defaultTimeoutMs, ["--title", "--timeout=5000"], "available", false],
- ["7000", ["--config", "--timeout=7000"], "available", false],
- ["7000", ["-c", "--timeout=7000"], "available", false],
- ["7000", ["--bail", "--timeout=7000"], "available", false],
] as const)(
"uses timeout %s with %p, %s reports and failure=%p",
async (timeout, options, report, fail) => {