OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(windows): tolerate executable metadata changes on first launch (#2555)
Michael D'Angelofce296540c5e
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex d212d18e9..1a81d94c1 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -1,6 +1,7 @@-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";import {type BigIntStats,+ createReadStream,existsSync,promises as fs,readdirSync,@@ -84,6 +85,7 @@ export interface CodexSdkWorkerArtifactContext {interface BoundCodexExecutable {readonly path: string;readonly identity: BigIntStats;+ readonly sha256?: string;}interface CodexSdkWorkerRuntimeSettings {@@ -99,7 +101,10 @@ interface CodexSdkWorkerRuntimeSettings {export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {private runtimeSettings?: Promise<CodexSdkWorkerRuntimeSettings>;// Each live coordinator keeps the executable selected for its first worker.- private codexExecutable?: Promise<BoundCodexExecutable>;+ private codexExecutable?: {+ signal: AbortSignal;+ promise: Promise<BoundCodexExecutable>;+ };private parentCyberAccessProgram?: Promise<CyberAccessProgram | undefined>;private pluginVersion?: Promise<string | undefined>;@@ -131,6 +136,49 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {return turn.finalResponse;}+ private async getCodexExecutable(+ environment: NodeJS.ProcessEnv,+ cwd: string,+ signal: AbortSignal,+ ): Promise<BoundCodexExecutable> {+ while (true) {+ signal.throwIfAborted();+ let binding = this.codexExecutable;+ if (!binding) {+ binding = {+ signal,+ promise: bindCodexExecutable(environment, cwd, signal).catch(+ (error) => {+ // An unsuccessful snapshot has not pinned an executable yet.+ if (this.codexExecutable === binding)+ this.codexExecutable = undefined;+ throw error;+ },+ ),+ };+ this.codexExecutable = binding;+ }+ const aborted = Promise.withResolvers<never>();+ const onAbort = () => aborted.reject(signal.reason);+ signal.addEventListener("abort", onAbort, { once: true });+ if (signal.aborted) onAbort();+ try {+ const executable = await Promise.race([+ binding.promise,+ aborted.promise,+ ]);+ signal.throwIfAborted();+ return executable;+ } catch (error) {+ signal.throwIfAborted();+ // Another worker's cancellation does not cancel this caller's first lookup.+ if (!binding.signal.aborted) throw error;+ } finally {+ signal.removeEventListener("abort", onAbort);+ }+ }+ }+private async runTurn(request:| CodexWorkerRequest@@ -153,6 +201,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {? undefined: resolve(dirname(discovery.promptPath), `limits-${randomUUID()}.toml`);try {+ request.signal.throwIfAborted();const parentSandbox = this.modelSettings.parentSandbox;if (!parentSandbox) {throw new DeepScanNonRetryableError(@@ -331,15 +380,12 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {"CODEX_API_KEY",process.platform,)?.trim();- const executable = await (this.codexExecutable ??= bindCodexExecutable(+ const executable = await this.getCodexExecutable(childEnv,originalCwd,- ).catch((error) => {- // A failed first lookup has not pinned an executable yet; allow startup retries.- this.codexExecutable = undefined;- throw error;- }));- await verifyBoundCodexExecutable(executable);+ request.signal,+ );+ await verifyBoundCodexExecutable(executable, request.signal);const preflightOptions = {codexPath: executable.path,cwd: request.workingDirectory,@@ -446,7 +492,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {try {// Detect updates during preflight before starting a fresh or resumed worker.- await verifyBoundCodexExecutable(executable);+ await verifyBoundCodexExecutable(executable, controller.signal);const { events } = await thread.runStreamed(input, {signal: controller.signal,...(request.kind === "compare" && { outputSchema: request.schema }),@@ -520,6 +566,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {request.signal.removeEventListener("abort", forwardAbort);}} catch (error) {+ // Pin checks throw the caller's reason directly; keep SDK worker errors intact.+ if (request.signal.aborted && error === request.signal.reason)+ throw error;throw classifyCodexWorkerError(error);} finally {if (includePathsFile !== undefined)@@ -781,34 +830,101 @@ function isRecord(value: unknown): value is Record<string, unknown> {async function bindCodexExecutable(env: NodeJS.ProcessEnv,originalCwd: string,+ signal?: AbortSignal,): Promise<BoundCodexExecutable> {+ signal?.throwIfAborted();const path = resolveCodexPath(env,process.platform,process.arch,originalCwd,);- return { path, identity: await codexExecutableIdentity(path) };+ const identity = await codexExecutableIdentity(path);+ signal?.throwIfAborted();+ if (process.platform !== "win32") return { path, identity };+ const sha256 = await codexExecutableDigest(path, signal);+ const after = await codexExecutableIdentity(path);+ signal?.throwIfAborted();+ if (+ !sameCodexExecutableFile(after, identity) ||+ after.ctimeNs !== identity.ctimeNs+ )+ throw codexExecutableChangedError(path);+ return { path, identity, sha256 };}async function verifyBoundCodexExecutable(executable: BoundCodexExecutable,+ signal?: AbortSignal,): Promise<void> {+ signal?.throwIfAborted();let identity: BigIntStats;try {identity = await codexExecutableIdentity(executable.path);+ signal?.throwIfAborted();} catch (error) {+ signal?.throwIfAborted();throw codexExecutableChangedError(executable.path, error);}- if (- identity.dev !== executable.identity.dev ||- identity.ino !== executable.identity.ino ||- identity.size !== executable.identity.size ||- identity.mtimeNs !== executable.identity.mtimeNs ||- identity.ctimeNs !== executable.identity.ctimeNs- ) {+ if (!sameCodexExecutableFile(identity, executable.identity)) {throw codexExecutableChangedError(executable.path);}+ if (identity.ctimeNs !== executable.identity.ctimeNs) {+ if (process.platform === "win32" && executable.sha256 !== undefined) {+ // Windows can advance change time on first execution without changing bytes.+ try {+ while (true) {+ signal?.throwIfAborted();+ const sha256 = await codexExecutableDigest(executable.path, signal);+ const after = await codexExecutableIdentity(executable.path);+ signal?.throwIfAborted();+ if (+ !sameCodexExecutableFile(after, executable.identity) ||+ sha256 !== executable.sha256+ )+ break;+ if (after.ctimeNs === identity.ctimeNs) return;+ // Confirm a stable content snapshot if change time advanced during the read.+ identity = after;+ }+ } catch (error) {+ signal?.throwIfAborted();+ throw codexExecutableChangedError(executable.path, error);+ }+ }+ throw codexExecutableChangedError(executable.path);+ }+}++async function codexExecutableDigest(+ path: string,+ signal?: AbortSignal,+): Promise<string> {+ signal?.throwIfAborted();+ const digest = createHash("sha256");+ try {+ for await (const bytes of createReadStream(path, { signal })) {+ signal?.throwIfAborted();+ digest.update(bytes);+ }+ } catch (error) {+ signal?.throwIfAborted();+ throw error;+ }+ signal?.throwIfAborted();+ return digest.digest("hex");+}++function sameCodexExecutableFile(+ actual: BigIntStats,+ expected: BigIntStats,+): boolean {+ return (+ actual.dev === expected.dev &&+ actual.ino === expected.ino &&+ actual.size === expected.size &&+ actual.mtimeNs === expected.mtimeNs+ );}async function codexExecutableIdentity(path: string): Promise<BigIntStats> {diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.tsindex 6e4f4cf85..cda76c03f 100644--- a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts+++ b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts@@ -1,4 +1,5 @@import assert from "node:assert/strict";+import { existsSync, promises as fs } from "node:fs";import childProcess, { type SpawnOptions } from "node:child_process";import {copyFile,@@ -65,6 +66,8 @@ export async function testExecutorExecutablePinning({await testExecutorPinsCodexExecutableAcrossWorkers();await testExecutorRejectsChangedPinnedExecutable();await testExecutorRejectsReplacementAfterPreflight();+ await testExecutorPinCancellation();+ await testConcurrentPinCancellation();} finally {childProcess.spawn = originalSpawn;syncBuiltinESMExports();@@ -333,6 +336,121 @@ export async function testExecutorExecutablePinning({}}+ async function testExecutorPinCancellation() {+ for (const phase of ["binding", "after-preflight"]) {+ await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {+ await writeFile(promptPath, "fixture executable pin cancellation\n");+ const controller = new AbortController();+ const reason = { message: "synthetic worker cancellation", phase };+ const originalStat = fs.stat;+ fs.stat = (async (...args: Parameters<typeof fs.stat>) => {+ const result = await originalStat(...args);+ if (+ args[0] === fixture.executablePath &&+ (phase === "binding" || existsSync(fixture.preflightMarkerPath))+ ) {+ controller.abort(reason);+ }+ return result;+ }) as typeof fs.stat;+ try {+ await assert.rejects(+ new CodexSdkWorkerExecutor({ parentSandbox }).run(+ workerRequest(promptPath, workingDirectory, {+ signal: controller.signal,+ }),+ ),+ (error) => error === reason,+ );+ } finally {+ fs.stat = originalStat;+ }+ assert.equal(+ existsSync(fixture.preflightMarkerPath),+ phase === "after-preflight",+ );+ assert.equal(existsSync(fixture.markerPath), false);+ });+ }+ }++ async function testConcurrentPinCancellation() {+ for (const canceled of ["owner", "waiter"]) {+ await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {+ await writeFile(+ promptPath,+ "fixture shared executable pin cancellation\n",+ );+ const owner = new AbortController();+ const waiter = new AbortController();+ const reason = new Error(`synthetic ${canceled} cancellation`);+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const waiting = Promise.withResolvers<void>();+ const originalStat = fs.stat;+ const originalAdd = waiter.signal.addEventListener;+ let held = false;+ fs.stat = (async (...args: Parameters<typeof fs.stat>) => {+ const result = await originalStat(...args);+ if (args[0] === fixture.executablePath && !held) {+ held = true;+ entered.resolve();+ await release.promise;+ }+ return result;+ }) as typeof fs.stat;+ waiter.signal.addEventListener = function (+ ...args: Parameters<AbortSignal["addEventListener"]>+ ) {+ const result = originalAdd.apply(this, args);+ if (args[0] === "abort") waiting.resolve();+ return result;+ };+ const executor = new CodexSdkWorkerExecutor({ parentSandbox });+ const first = executor.run(+ workerRequest(promptPath, workingDirectory, { signal: owner.signal }),+ );+ let second: ReturnType<typeof executor.run> | undefined;+ try {+ await entered.promise;+ second = executor.run(+ workerRequest(promptPath, workingDirectory, {+ signal: waiter.signal,+ }),+ );+ const completed = Promise.allSettled([first, second]);+ await waiting.promise;+ (canceled === "owner" ? owner : waiter).abort(reason);+ release.resolve();+ const results = await completed;+ const rejected = results[canceled === "owner" ? 0 : 1]!;+ const fulfilled = results[canceled === "owner" ? 1 : 0]!;+ assert.equal(rejected.status, "rejected");+ if (rejected.status === "rejected")+ assert.equal(rejected.reason, reason);+ assert.equal(fulfilled.status, "fulfilled");+ if (fulfilled.status === "fulfilled")+ assert.equal(fulfilled.value.threadId, "fixture-thread-id");+ // A successful pin survives its original caller's later cancellation.+ (canceled === "owner" ? waiter : owner).abort(+ new Error("fixture completed"),+ );+ const next = await executor.run(+ workerRequest(promptPath, workingDirectory),+ );+ assert.equal(next.threadId, "fixture-thread-id");+ } finally {+ release.resolve();+ owner.abort(reason);+ waiter.abort(reason);+ fs.stat = originalStat;+ waiter.signal.addEventListener = originalAdd;+ await Promise.allSettled([first, ...(second ? [second] : [])]);+ }+ });+ }+ }+async function withWorkerFixture(action: (fixture: Fixture,diff --git a/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts b/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.tsindex 7d70488e1..00dc47951 100644--- a/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts+++ b/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts@@ -14,7 +14,7 @@ export const executor = await importModule({stdin: {// Expose internal worker checks only to the test fixtures.contents: `${await readFile(executorSource, "utf8")}-export { snapshotWorkerEnvironment, appendItemDiagnostic, verifyBoundCodexExecutable };+export { snapshotWorkerEnvironment, appendItemDiagnostic, bindCodexExecutable, verifyBoundCodexExecutable };export { parseDeepScan } from "./response.js";`,loader: "ts",resolveDir: path.dirname(fileURLToPath(executorSource)),@@ -22,7 +22,18 @@ export { parseDeepScan } from "./response.js";`,},});-export const verifyBoundCodexExecutable: (executable: {- path: string;- identity: import("node:fs").BigIntStats;-}) => Promise<void> = executor.verifyBoundCodexExecutable;+export const verifyBoundCodexExecutable: (+ executable: {+ path: string;+ identity: import("node:fs").BigIntStats;+ sha256?: string;+ },+ signal?: AbortSignal,+) => Promise<void> = executor.verifyBoundCodexExecutable;++export const bindCodexExecutable: (+ environment: NodeJS.ProcessEnv,+ cwd: string,+ signal?: AbortSignal,+) => Promise<Parameters<typeof verifyBoundCodexExecutable>[0]> =+ executor.bindCodexExecutable;diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex 0ce4f8508..4f9de0a89 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -95,9 +95,9 @@ try {);await check(t, testWorkerTerminalEvents);await check(t, testCompletedWorkerSettlesWithoutWaitingForProcessExit);+ await check(t, testAbortPropagation);if (process.platform !== "win32") {await check(t, testStreamTerminationWithoutTerminalEventFails);- await check(t, testAbortPropagation);}});diff --git a/plugins/codex-security/mcp-app/tests/test_helper_files.ts b/plugins/codex-security/mcp-app/tests/test_helper_files.tsindex ae790d5c7..75c1efb7f 100644--- a/plugins/codex-security/mcp-app/tests/test_helper_files.ts+++ b/plugins/codex-security/mcp-app/tests/test_helper_files.ts@@ -9,6 +9,7 @@ import { after, test } from "node:test";import { importModule, importSource } from "./import-module.ts";import { createTemporaryDirectories } from "./support/temporary-directories.ts";import { registerWorkerExecutableFirstLaunchTests } from "./windows_executable_first_launch_cases.ts";+import { registerWorkerExecutableCancellationTests } from "./windows_executable_cancellation_cases.ts";const packagedHelper = new URL("../../../../sdk/typescript/_bundled_plugin/mcp/helpers.mjs",@@ -307,3 +308,4 @@ test(// The Windows CI job runs this entry point directly and retains native TAP results.registerWorkerExecutableFirstLaunchTests();+registerWorkerExecutableCancellationTests();diff --git a/plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.ts b/plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.tsnew file mode 100644index 000000000..c7543217a--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.ts@@ -0,0 +1,132 @@+import assert from "node:assert/strict";+import fs, { promises } from "node:fs";+import { rm, writeFile } from "node:fs/promises";+import { syncBuiltinESMExports } from "node:module";+import path from "node:path";+import test from "node:test";+import { temporaryDirectory } from "./support/temporary-directories.ts";+import {+ bindCodexExecutable,+ verifyBoundCodexExecutable,+} from "./support/deep-scan-executor-module.ts";++export function registerWorkerExecutableCancellationTests(): void {+ for (const phase of ["binding", "verification"]) {+ test(`the worker pin preserves cancellation before ${phase}`, async (t) => {+ const root = await temporaryDirectory("worker-cancelled-pin-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ await writeFile(executable, "fixture original bytes\n");+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ const controller = new AbortController();+ const reason = { message: "synthetic caller cancellation", phase };+ controller.abort(reason);+ const inspect = t.mock.method(promises, "stat", () => {+ throw new Error("An aborted pin operation must not inspect the file.");+ });+ await assert.rejects(+ phase === "binding"+ ? bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ controller.signal,+ )+ : verifyBoundCodexExecutable(bound, controller.signal),+ (error) => error === reason,+ );+ assert.equal(inspect.mock.callCount(), 0);+ });+ }++ test(+ "the worker pin cancels an active binding content stream",+ {+ skip: process.platform !== "win32",+ },+ async (t) => {+ const root = await temporaryDirectory("worker-cancelled-stream-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ await writeFile(executable, "fixture original bytes\n".repeat(8192));+ const controller = new AbortController();+ const reason = new Error("synthetic cancellation during binding read");+ const originalRead = fs.createReadStream;+ let observed: fs.ReadStream | undefined;+ const reading = t.mock.method(+ fs,+ "createReadStream",+ (...args: Parameters<typeof fs.createReadStream>) => {+ const stream = originalRead(...args);+ if (args[0] === executable) {+ observed = stream;+ stream.once("data", () => controller.abort(reason));+ }+ return stream;+ },+ );+ syncBuiltinESMExports();+ try {+ await assert.rejects(+ bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ controller.signal,+ ),+ (error) => error === reason,+ );+ } finally {+ reading.mock.restore();+ syncBuiltinESMExports();+ }+ assert.ok(observed);+ if (!observed.closed)+ await new Promise<void>((resolve) => observed!.once("close", resolve));+ assert.equal(observed.destroyed, true);+ assert.equal(observed.closed, true);+ },+ );++ test(+ "the worker pin cancels metadata churn with the caller's reason",+ {+ skip: process.platform !== "win32",+ },+ async (t) => {+ const root = await temporaryDirectory("worker-cancelled-churn-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ await writeFile(executable, "fixture original bytes\n");+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ const controller = new AbortController();+ const reason = new Error("synthetic cancellation during metadata churn");+ const originalStat = promises.stat;+ let observations = 0;+ t.mock.method(+ promises,+ "stat",+ async (...args: Parameters<typeof promises.stat>) => {+ if (args[0] !== executable) return originalStat(...args);+ observations++;+ if (observations === 3) controller.abort(reason);+ const identity = await originalStat(args[0], { bigint: true });+ // Keep the real file and content stream while deterministically advancing+ // the metadata observation, independent of filesystem chmod timestamps.+ return Object.assign(identity, {+ ctimeNs: bound.identity.ctimeNs + BigInt(observations),+ });+ },+ );+ await assert.rejects(+ verifyBoundCodexExecutable(bound, controller.signal),+ (error) => error === reason,+ );+ assert.equal(observations, 3);+ },+ );+}diff --git a/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts b/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.tsindex cf79401bc..7b50bb968 100644--- a/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts+++ b/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts@@ -1,8 +1,16 @@import assert from "node:assert/strict";import { execFile } from "node:child_process";import { createHash } from "node:crypto";-import { createReadStream } from "node:fs";-import { copyFile, rm, stat, utimes, writeFile } from "node:fs/promises";+import { createReadStream, promises as fs } from "node:fs";+import {+ copyFile,+ mkdir,+ rename,+ rm,+ stat,+ utimes,+ writeFile,+} from "node:fs/promises";import path from "node:path";import test from "node:test";import { setTimeout as delay } from "node:timers/promises";@@ -21,49 +29,47 @@ export function registerWorkerExecutableFirstLaunchTests(): void {"the first Windows version launch preserves the executable pin",{ skip: process.platform !== "win32" },async (t) => {- const { verifyBoundCodexExecutable } =+ const { bindCodexExecutable, verifyBoundCodexExecutable } =await import("./support/deep-scan-executor-module.ts");const root = await temporaryDirectory("worker-first-launch-", true);t.after(() => rm(root, { recursive: true, force: true }));- const executable = path.join(root, "version-fixture.exe");- await copyFile(process.execPath, executable);- const beforeDigest = await digest(executable);- const identity = await stat(executable, { bigint: true });- await verifyBoundCodexExecutable({ path: executable, identity });- const { stdout } = await promisify(execFile)(- executablePathForSpawn(executable),- ["--version"],- {- windowsHide: true,- },- );- assert.equal(stdout.trim(), process.version);- const after = await stat(executable, { bigint: true });- assert.equal(await digest(executable), beforeDigest);- assert.equal(after.dev, identity.dev);- assert.equal(after.ino, identity.ino);- assert.equal(after.size, identity.size);- assert.equal(after.mtimeNs, identity.mtimeNs);- try {- await verifyBoundCodexExecutable({ path: executable, identity });- } catch (error) {- if (- after.ctimeNs !== identity.ctimeNs &&- error instanceof Error &&- error.name === "DeepScanNonRetryableError" &&- error.cause === undefined- ) {- t.todo(- "The current worker pin rejects an ordinary launch when only Windows change time advances.",+ for (const name of [+ "version-fixture.exe",+ path.join(...Array(10).fill("nested executable directory"), "node.exe"),+ ]) {+ const executable = path.join(root, name);+ await mkdir(path.dirname(executable), { recursive: true });+ await copyFile(process.execPath, executable);+ const beforeDigest = await digest(executable);+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ const { identity } = bound;+ await verifyBoundCodexExecutable(bound);+ for (let launch = 0; launch < 2; launch++) {+ const { stdout } = await promisify(execFile)(+ executablePathForSpawn(executable),+ ["--version"],+ {+ windowsHide: true,+ },);+ assert.equal(stdout.trim(), process.version);+ const after = await stat(executable, { bigint: true });+ assert.equal(await digest(executable), beforeDigest);+ assert.equal(after.dev, identity.dev);+ assert.equal(after.ino, identity.ino);+ assert.equal(after.size, identity.size);+ assert.equal(after.mtimeNs, identity.mtimeNs);+ await verifyBoundCodexExecutable(bound);}- throw error;}},);test("the worker pin rejects a changed synthetic file of the same size", async (t) => {- const { verifyBoundCodexExecutable } =+ const { bindCodexExecutable, verifyBoundCodexExecutable } =await import("./support/deep-scan-executor-module.ts");const root = await temporaryDirectory("worker-changed-pin-", true);t.after(() => rm(root, { recursive: true, force: true }));@@ -72,8 +78,12 @@ export function registerWorkerExecutableFirstLaunchTests(): void {const fixedTime = new Date("2025-01-01T00:00:00Z");await writeFile(executable, "fixture revision A\n");await utimes(executable, fixedTime, fixedTime);- const identity = await stat(executable, { bigint: true });- await verifyBoundCodexExecutable({ path: executable, identity });+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ const { identity } = bound;+ await verifyBoundCodexExecutable(bound);// Retry a real equal-length revision on a later tick if the first write is too fast.for (const [wait, revision] of [[0, "B"],@@ -86,10 +96,9 @@ export function registerWorkerExecutableFirstLaunchTests(): void {assert.equal(updated.size, identity.size);assert.equal(updated.mtimeNs, identity.mtimeNs);if (updated.ctimeNs !== identity.ctimeNs) {- await assert.rejects(- verifyBoundCodexExecutable({ path: executable, identity }),- { name: "DeepScanNonRetryableError" },- );+ await assert.rejects(verifyBoundCodexExecutable(bound), {+ name: "DeepScanNonRetryableError",+ });return;}}@@ -97,4 +106,150 @@ export function registerWorkerExecutableFirstLaunchTests(): void {"The fixture filesystem reported the same change time across two separately timed content revisions.",);});++ test("the worker pin rejects a same-content file replacement", async (t) => {+ const { bindCodexExecutable, verifyBoundCodexExecutable } =+ await import("./support/deep-scan-executor-module.ts");+ const root = await temporaryDirectory("worker-replaced-pin-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ const replacement = path.join(root, "replacement.exe");+ const fixedTime = new Date("2025-01-01T00:00:00Z");+ await writeFile(executable, "fixture original bytes\n");+ await utimes(executable, fixedTime, fixedTime);+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ await copyFile(executable, replacement);+ await utimes(replacement, fixedTime, fixedTime);+ assert.equal(await digest(replacement), await digest(executable));+ await rename(replacement, executable);+ const replaced = await stat(executable, { bigint: true });+ assert.notEqual(replaced.ino, bound.identity.ino);+ assert.equal(replaced.size, bound.identity.size);+ assert.equal(replaced.mtimeNs, bound.identity.mtimeNs);+ await assert.rejects(verifyBoundCodexExecutable(bound), {+ name: "DeepScanNonRetryableError",+ });+ });++ test("the worker pin rejects a changed modification time with identical content", async (t) => {+ const { bindCodexExecutable, verifyBoundCodexExecutable } =+ await import("./support/deep-scan-executor-module.ts");+ const root = await temporaryDirectory("worker-modified-pin-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ await writeFile(executable, "fixture original bytes\n");+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ const beforeDigest = await digest(executable);+ const changedTime = new Date("2025-01-01T00:00:00Z");+ await utimes(executable, changedTime, changedTime);+ assert.equal(await digest(executable), beforeDigest);+ assert.notEqual(+ (await stat(executable, { bigint: true })).mtimeNs,+ bound.identity.mtimeNs,+ );+ await assert.rejects(verifyBoundCodexExecutable(bound), {+ name: "DeepScanNonRetryableError",+ });+ });++ for (const phase of ["binding", "verification"]) {+ test(+ `the worker pin rejects a revision during content ${phase}`,+ {+ skip: process.platform !== "win32",+ },+ async (t) => {+ const { bindCodexExecutable, verifyBoundCodexExecutable } =+ await import("./support/deep-scan-executor-module.ts");+ const root = await temporaryDirectory("worker-streamed-pin-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ const fixedTime = new Date("2025-01-01T00:00:00Z");+ await writeFile(executable, "fixture revision A\n");+ await utimes(executable, fixedTime, fixedTime);+ const bind = () =>+ bindCodexExecutable({ CODEX_CLI_PATH: executable }, root);+ const bound = phase === "verification" ? await bind() : undefined;+ const originalStat = fs.stat;+ let observations = 0;+ let revised = false;+ let changeTime = bound?.identity.ctimeNs;+ t.mock.method(+ fs,+ "stat",+ async (...args: Parameters<typeof fs.stat>) => {+ if (args[0] !== executable) return originalStat(...args);+ observations++;+ if (observations === 2) {+ await writeFile(executable, "fixture revision B\n");+ await utimes(executable, fixedTime, fixedTime);+ revised = true;+ }+ const identity = await originalStat(args[0], { bigint: true });+ // chmod does not advance change time on every Windows filesystem.+ // Inject only that observation while reading and revising real bytes.+ changeTime ??= identity.ctimeNs;+ return Object.assign(identity, {+ ctimeNs: changeTime + BigInt(observations),+ });+ },+ );+ await assert.rejects(+ bound ? verifyBoundCodexExecutable(bound) : bind(),+ {+ name: "DeepScanNonRetryableError",+ },+ );+ assert.equal(revised, true);+ assert.equal(observations, phase === "verification" ? 3 : 2);+ assert.equal(+ await fs.readFile(executable, "utf8"),+ "fixture revision B\n",+ );+ },+ );+ }++ test(+ "the worker pin accepts a metadata-only change during content verification",+ {+ skip: process.platform !== "win32",+ },+ async (t) => {+ const { bindCodexExecutable, verifyBoundCodexExecutable } =+ await import("./support/deep-scan-executor-module.ts");+ const root = await temporaryDirectory("worker-metadata-pin-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const executable = path.join(root, "content-fixture.exe");+ await writeFile(executable, "fixture original bytes\n");+ const bound = await bindCodexExecutable(+ { CODEX_CLI_PATH: executable },+ root,+ );+ const beforeDigest = await digest(executable);+ const originalStat = fs.stat;+ let observations = 0;+ let changedMetadata = false;+ t.mock.method(fs, "stat", async (...args: Parameters<typeof fs.stat>) => {+ if (args[0] !== executable) return originalStat(...args);+ observations++;+ if (observations === 2) changedMetadata = true;+ const identity = await originalStat(args[0], { bigint: true });+ // Report one metadata transition during the real content read, then stability.+ return Object.assign(identity, {+ ctimeNs: bound.identity.ctimeNs + BigInt(Math.min(observations, 2)),+ });+ });+ await verifyBoundCodexExecutable(bound);+ assert.equal(changedMetadata, true);+ assert.equal(observations, 3);+ assert.equal(await digest(executable), beforeDigest);+ },+ );}