@memnexus-ai/mx-agent-cli 0.1.270 → 0.1.272

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,7 @@
21
21
  * below a complete record of every `unlinkSync` the deploy performed.
22
22
  */
23
23
  import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
24
+ import { execFileSync } from 'child_process';
24
25
  import { join } from 'path';
25
26
  import { tmpdir } from 'os';
26
27
  const race = vi.hoisted(() => ({
@@ -28,8 +29,36 @@ const race = vi.hoisted(() => ({
28
29
  beforeOpen: null,
29
30
  /** Runs immediately AFTER a real fd-based `writeFileSync`, with the temp path. */
30
31
  afterWrite: null,
32
+ /** Runs immediately AFTER a real `renameSync`, with the DESTINATION path. */
33
+ afterRename: null,
34
+ /**
35
+ * Runs immediately AFTER a real path-based `lstatSync`, with the path, the real result,
36
+ * and whether the caller asked for `bigint` stats. Returning a value REPLACES the stat
37
+ * the caller sees; throwing makes the `lstat` fail. This is the only instrument that can
38
+ * put the filesystem into states a test cannot build with real syscalls — a directory on
39
+ * a different DEVICE with the same inode number, and a directory that exists but cannot
40
+ * be examined — both of which are fail-closed branches with no other way to reach them.
41
+ */
42
+ onLstat: null,
43
+ /**
44
+ * The path behind every descriptor the deploy read a whole file from. The deploy reads
45
+ * by descriptor in two places — the roleguide, and the acceptance comparing the landed
46
+ * artifact bytes — so this is how a test asks whether an attacker-influenced artifact was
47
+ * read into memory in full (SF-4).
48
+ */
49
+ fdReads: [],
50
+ /**
51
+ * Runs immediately BEFORE a real fd-based `readFileSync`, with the path behind the
52
+ * descriptor. Throwing makes the read fail — the only way to reach the acceptance's own
53
+ * `catch`, which is a fail-CLOSED branch (round 9 SF-C completeness pass).
54
+ */
55
+ onFdRead: null,
56
+ /** fd → the path it was opened on, so an fd-based read can be attributed. */
57
+ fdPaths: new Map(),
31
58
  /** Every path the deploy passed to `unlinkSync`, in order. */
32
59
  unlinked: [],
60
+ /** Every path the deploy passed to `openSync`, in order. */
61
+ opened: [],
33
62
  /** The last temp path opened — the write is fd-based, so it carries no path. */
34
63
  lastOpened: '',
35
64
  }));
@@ -40,9 +69,29 @@ vi.mock('fs', async (importOriginal) => {
40
69
  openSync: ((path, flags, mode) => {
41
70
  if (typeof path === 'string') {
42
71
  race.lastOpened = path;
72
+ race.opened.push(path);
43
73
  race.beforeOpen?.(path);
44
74
  }
45
- return actual.openSync(path, flags, mode);
75
+ const fd = actual.openSync(path, flags, mode);
76
+ if (typeof path === 'string')
77
+ race.fdPaths.set(fd, path);
78
+ return fd;
79
+ }),
80
+ lstatSync: ((path, options) => {
81
+ const real = actual.lstatSync(path, options);
82
+ if (typeof path === 'string' && race.onLstat) {
83
+ const bigint = Boolean(options?.bigint);
84
+ const replaced = race.onLstat(path, real, bigint);
85
+ if (replaced !== undefined)
86
+ return replaced;
87
+ }
88
+ return real;
89
+ }),
90
+ renameSync: ((from, to) => {
91
+ const result = actual.renameSync(from, to);
92
+ if (typeof to === 'string')
93
+ race.afterRename?.(to);
94
+ return result;
46
95
  }),
47
96
  writeFileSync: ((file, data, options) => {
48
97
  const opened = race.lastOpened;
@@ -51,6 +100,14 @@ vi.mock('fs', async (importOriginal) => {
51
100
  race.afterWrite?.(opened);
52
101
  return result;
53
102
  }),
103
+ readFileSync: ((file, options) => {
104
+ if (typeof file === 'number') {
105
+ const path = race.fdPaths.get(file) ?? `fd:${file}`;
106
+ race.fdReads.push(path);
107
+ race.onFdRead?.(path);
108
+ }
109
+ return actual.readFileSync(file, options);
110
+ }),
54
111
  unlinkSync: ((path) => {
55
112
  race.unlinked.push(String(path));
56
113
  return actual.unlinkSync(path);
@@ -58,11 +115,27 @@ vi.mock('fs', async (importOriginal) => {
58
115
  };
59
116
  return { ...patched, default: patched };
60
117
  });
61
- const { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync, } = await import('fs');
118
+ const { chmodSync, closeSync, constants: fsConstants, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync, writeSync, } = await import('fs');
62
119
  const { deployCodexConfigOnly, resolveCodexDeployTarget } = await import('../commands/codex-deploy-config.js');
63
120
  const { BEHAVIORAL_END_MARKER, BEHAVIORAL_START_MARKER } = await import('../lib/behavioral-injection.js');
64
121
  const { AGENTS_OVERRIDE_FILENAME, CODEX_CONFIG_FILENAME, CODEX_HOOKS_FILENAME } = await import('../lib/runtime/codex-config.js');
65
122
  const TEAM = 'demo';
123
+ /**
124
+ * A real stat with some members replaced — the `onLstat` instrument's only way to build the
125
+ * states real syscalls cannot build inside one deploy. Everything not named in `patch`
126
+ * answers exactly as the kernel answered, including the type predicates, which are bound
127
+ * back to the real stat because they read its private mode field.
128
+ */
129
+ const statReporting = (real, patch) => new Proxy(real, {
130
+ get(target, prop, receiver) {
131
+ if (typeof prop === 'string' && prop in patch)
132
+ return patch[prop];
133
+ const value = Reflect.get(target, prop, receiver);
134
+ return typeof value === 'function'
135
+ ? value.bind(target)
136
+ : value;
137
+ },
138
+ });
66
139
  let root;
67
140
  let worktree;
68
141
  /** Stands in for the MAIN REPO — the destination every one of these attacks aims at. */
@@ -72,7 +145,13 @@ const MAIN_OVERRIDE_SENTINEL = '# MAIN override — do-not-touch\n';
72
145
  beforeEach(() => {
73
146
  race.beforeOpen = null;
74
147
  race.afterWrite = null;
148
+ race.afterRename = null;
149
+ race.onLstat = null;
150
+ race.onFdRead = null;
75
151
  race.unlinked = [];
152
+ race.opened = [];
153
+ race.fdReads = [];
154
+ race.fdPaths = new Map();
76
155
  race.lastOpened = '';
77
156
  root = mkdtempSync(join(tmpdir(), 'mx-race-root-'));
78
157
  worktree = join(root, '.worktrees', `${TEAM}-20260101`);
@@ -94,6 +173,9 @@ beforeEach(() => {
94
173
  afterEach(() => {
95
174
  race.beforeOpen = null;
96
175
  race.afterWrite = null;
176
+ race.afterRename = null;
177
+ race.onLstat = null;
178
+ race.onFdRead = null;
97
179
  rmSync(root, { recursive: true, force: true });
98
180
  });
99
181
  const deploy = () => {
@@ -125,6 +207,11 @@ const mainRepoTemps = () => readdirSync(mainCodex).filter((entry) => entry.inclu
125
207
  * 5 window hits / 0 main-repo overwrites; this build 135 hits / 4 overwrites, all four
126
208
  * reported as WRITTEN, plus 33 `.mx-tmp-*` files left inside the main repo.
127
209
  *
210
+ * (Label correction, #4897: the "predecessor" arm was originally labelled as commit
211
+ * `85fe36faf`; the round-7 reviewer rebuilt both arms from source and found that arm was a
212
+ * hand-made hybrid rather than that commit. Re-measured against the real commit, the
213
+ * conclusion was unchanged.)
214
+ *
128
215
  * The remediation identifies the parent directory by `{dev, ino}` before the open and
129
216
  * re-checks it twice. Both checks are exercised below, at the two points the swap can land.
130
217
  */
@@ -196,6 +283,286 @@ describe('write path — the parent directory is identified, not just named', ()
196
283
  expect(outcome.writeFailures).toEqual([]);
197
284
  });
198
285
  });
286
+ /**
287
+ * ───────────────── SF-M (round 7): THE FAIL-CLOSED BRANCHES, PINNED ───────────
288
+ * The round-7 reviewer ran seven mutants past the eight the implementer ran, and three
289
+ * survived with the whole suite green. The shipped code is CORRECT in all three — nothing
290
+ * below changes it. What was missing was an assertion that would notice if a later edit
291
+ * broke one, and one of the three (RV-2) is a single line away from turning a refusal into
292
+ * a write into the main repo:
293
+ *
294
+ * RV-1 `assertSameDirectory` compares `ino` and ignores `dev` — two directories on
295
+ * different filesystems that happen to share an inode number compare EQUAL.
296
+ * RV-2 `assertSameDirectory`'s `catch` RETURNS instead of throwing — the directory that
297
+ * cannot be examined goes from fail-CLOSED to fail-OPEN.
298
+ * RV-3 `directoryIdentity` accepts a symlinked parent at capture — the identity then
299
+ * describes the LINK, both later checks agree with it, and every byte plus the
300
+ * install lands wherever the link points.
301
+ *
302
+ * Two of the three cannot be built out of real syscalls in a unit test: nothing a test can
303
+ * do gives one name the same inode number on two devices, and a directory that exists but
304
+ * cannot be `lstat`ed needs a permission change that would break the rename too, which
305
+ * would hide the fail-open. So `lstatSync` is instrumented the same way `openSync` already
306
+ * is — a real call whose result the test may replace or make fail, at a moment the test
307
+ * chooses. The filesystem stays real everywhere else, including for the containment walk,
308
+ * which takes NON-bigint stats and so is never touched by the hooks below.
309
+ */
310
+ describe('write path — the directory-identity comparison itself (SF-M mutation pins)', () => {
311
+ /** The same stat, reporting a different DEVICE. `dev` is a bigint under `bigint: true`. */
312
+ const onAnotherDevice = (real) => new Proxy(real, {
313
+ get(target, prop, receiver) {
314
+ if (prop === 'dev')
315
+ return Reflect.get(target, prop) + 1n;
316
+ const value = Reflect.get(target, prop, receiver);
317
+ return typeof value === 'function'
318
+ ? value.bind(target)
319
+ : value;
320
+ },
321
+ });
322
+ /**
323
+ * The same stat, of the same device and inode number, reporting that it is NOT a
324
+ * directory — what an inode number reused by a non-directory looks like to `lstat`.
325
+ */
326
+ const notADirectory = (real) => statReporting(real, { isDirectory: () => false });
327
+ const worktreeCodexDir = () => join(worktree, '.codex');
328
+ it('RV-1: a parent with the SAME inode number on a DIFFERENT DEVICE is refused', () => {
329
+ expect(deploy().ok).toBe(true);
330
+ race.beforeOpen = (path) => {
331
+ if (!path.includes('hooks.json.mx-tmp-'))
332
+ return;
333
+ race.beforeOpen = null;
334
+ // The identity was captured one syscall ago. From here the name answers with the
335
+ // same inode number on another device — a different directory by every measure
336
+ // except the one a `ino`-only comparison makes.
337
+ race.onLstat = (p, real, bigint) => p === worktreeCodexDir() && bigint ? onAnotherDevice(real) : undefined;
338
+ };
339
+ const outcome = deploy();
340
+ race.onLstat = null;
341
+ expect(outcome.ok).toBe(false);
342
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
343
+ const refusal = outcome.writeRefusals.join('\n');
344
+ expect(refusal).toContain('was REPLACED');
345
+ // The pin: the two identities differ ONLY in `dev`, so a comparison that reads `ino`
346
+ // alone calls them the same directory and writes.
347
+ const identities = /device (\d+)\/inode (\d+) when containment passed, and is now device (\d+)\/inode (\d+)/.exec(refusal);
348
+ expect(identities).not.toBeNull();
349
+ const [, expectedDev, expectedIno, observedDev, observedIno] = identities;
350
+ expect(observedIno).toBe(expectedIno);
351
+ expect(observedDev).not.toBe(expectedDev);
352
+ });
353
+ it('RV-2: a parent that cannot be EXAMINED is refused, never written into', () => {
354
+ expect(deploy().ok).toBe(true);
355
+ const hooks = join(worktree, CODEX_HOOKS_FILENAME);
356
+ const installedInode = lstatSync(hooks).ino;
357
+ race.beforeOpen = (path) => {
358
+ if (!path.includes('hooks.json.mx-tmp-'))
359
+ return;
360
+ race.beforeOpen = null;
361
+ race.onLstat = (p, _real, bigint) => {
362
+ if (p !== worktreeCodexDir() || !bigint)
363
+ return undefined;
364
+ const err = new Error(`EACCES: permission denied, lstat '${p}'`);
365
+ err.code = 'EACCES';
366
+ throw err;
367
+ };
368
+ };
369
+ const outcome = deploy();
370
+ race.onLstat = null;
371
+ // Fail-CLOSED: a refusal, and the artifact on disk is the one the previous deploy
372
+ // installed — same inode, so nothing was renamed over it. Under the mutant this
373
+ // deploy completes, reports ok, and the inode changes.
374
+ expect(outcome.ok).toBe(false);
375
+ const refusal = outcome.writeRefusals.join('\n');
376
+ expect(refusal).toContain('unexaminable');
377
+ expect(refusal).toContain('EACCES');
378
+ expect(refusal).toContain('Nothing was installed.');
379
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
380
+ expect(lstatSync(hooks).ino).toBe(installedInode);
381
+ });
382
+ /**
383
+ * ── RV-4 (round 9 SF-A): THE TYPE CLAUSE IN `assertSameDirectory` ────────────
384
+ * `st.isDirectory()` in `assertSameDirectory` was unpinned — removing it left all 38
385
+ * tests green. RV-3 pins the equivalent clause in `directoryIdentity`, at CAPTURE time;
386
+ * this is the clause that runs at every RE-CHECK, and it is the last thing standing in
387
+ * the same inode-reuse class the round-9 MUST FIX turns on: an inode NUMBER is not a
388
+ * durable identity, so a directory that is removed and replaced by a non-directory
389
+ * taking its number compares EQUAL on `{dev, ino}`.
390
+ *
391
+ * That state cannot be built with real syscalls inside one deploy — the same reason RV-1
392
+ * and RV-2 use the instrument — so the parent's re-check `lstat` answers with its own
393
+ * real device and inode number and `isDirectory() → false`, which is exactly what the
394
+ * reused number would produce.
395
+ */
396
+ it('RV-4: a parent with a MATCHING dev/ino that is no longer a DIRECTORY is refused', () => {
397
+ expect(deploy().ok).toBe(true);
398
+ let fired = false;
399
+ race.beforeOpen = (path) => {
400
+ if (!path.includes('hooks.json.mx-tmp-'))
401
+ return;
402
+ race.beforeOpen = null;
403
+ race.onLstat = (p, real, bigint) => {
404
+ if (fired || p !== worktreeCodexDir() || !bigint)
405
+ return undefined;
406
+ fired = true;
407
+ return notADirectory(real);
408
+ };
409
+ };
410
+ const outcome = deploy();
411
+ race.onLstat = null;
412
+ expect(fired).toBe(true);
413
+ expect(outcome.ok).toBe(false);
414
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
415
+ const refusal = outcome.writeRefusals.join('\n');
416
+ expect(refusal).toContain('was REPLACED');
417
+ // The pin: dev and ino are UNCHANGED, so a comparison that stops at `{dev, ino}` calls
418
+ // this the same directory and writes into it. Only the type clause refuses it.
419
+ expect(refusal).toContain('not a directory at all');
420
+ const identities = /device (\d+)\/inode (\d+) when containment passed, and is now not a directory at all/.exec(refusal);
421
+ expect(identities).not.toBeNull();
422
+ const [, expectedDev, expectedIno] = identities;
423
+ const real = lstatSync(worktreeCodexDir(), { bigint: true });
424
+ expect(expectedDev).toBe(String(real.dev));
425
+ expect(expectedIno).toBe(String(real.ino));
426
+ });
427
+ it('RV-3: a parent that became a SYMLINK before its identity was captured opens nothing inside it', () => {
428
+ expect(deploy().ok).toBe(true);
429
+ let swapped = false;
430
+ race.onLstat = (p, _real, bigint) => {
431
+ if (swapped || p !== worktreeCodexDir() || !bigint)
432
+ return undefined;
433
+ // The first bigint `lstat` of the parent IS the identity capture — the containment
434
+ // walk takes non-bigint stats. Swap underneath it, so what it identifies is a
435
+ // symlink to the main repo's `.codex`, and let it take its own stat of the result.
436
+ swapped = true;
437
+ race.opened = [];
438
+ swapCodexDirForASymlinkToMainRepo();
439
+ return lstatSync(p, { bigint: true });
440
+ };
441
+ const outcome = deploy();
442
+ race.onLstat = null;
443
+ restoreCodexDir();
444
+ expect(swapped).toBe(true);
445
+ expect(outcome.ok).toBe(false);
446
+ expect(outcome.writeRefusals.join('\n')).toContain('it is not a real directory');
447
+ // The pin: capture refuses BEFORE the open, so not one temp file is created inside the
448
+ // link's destination. Accept the symlink at capture and the identity describes the
449
+ // LINK, both later checks agree with it, and the bytes — and the install — land in the
450
+ // main repo.
451
+ expect(race.opened.filter((path) => path.includes('.mx-tmp-') && path.startsWith(`${worktreeCodexDir()}/`))).toEqual([]);
452
+ expect(mainRepoTemps()).toEqual([]);
453
+ expect(readFileSync(join(mainCodex, 'hooks.json'), 'utf-8')).toBe(MAIN_HOOKS_SENTINEL);
454
+ });
455
+ /**
456
+ * ── ROUND 11 MAJOR D: THE TYPE CLAUSE AT CAPTURE, WHICH RV-3 DOES NOT PIN ────
457
+ * `directoryIdentity` refuses on two clauses — `!st.isDirectory()` and
458
+ * `st.isSymbolicLink()` — and only the second had a test. RV-3 above swaps in a SYMLINK,
459
+ * which the symlink clause catches on its own, so removing `!st.isDirectory()` left the
460
+ * whole suite green. RV-4 pins the same question at RE-CHECK time; this is CAPTURE time,
461
+ * where the consequence is worse: the identity the whole write path is then anchored to
462
+ * is the identity of an object that is not a directory, and every later check agrees with
463
+ * it, so the deploy runs to completion and reports success.
464
+ *
465
+ * The object is a non-directory that is ALSO not a symlink — a FIFO, a regular file or a
466
+ * socket swapped in at capture time — because anything a symlink can do is already
467
+ * refused. Reachable with real syscalls by the same rmdir-and-fast-recreate race RP14
468
+ * demonstrates against a file; built here with the instrument, so the pin is
469
+ * deterministic and does not depend on winning an allocator race.
470
+ *
471
+ * Removing `st.isSymbolicLink()` INSTEAD also leaves the suite green, and that one is an
472
+ * EQUIVALENT mutant, not a gap: `lstat` on a symlink never reports `isDirectory() === true`,
473
+ * so the type clause already covers every case the symlink clause covers. It is listed
474
+ * here so it is not miscounted as a survivor next round.
475
+ */
476
+ it('RV-5: a parent that is NOT A DIRECTORY and not a symlink is refused at CAPTURE, before anything is opened', () => {
477
+ expect(deploy().ok).toBe(true);
478
+ let fired = false;
479
+ race.opened = [];
480
+ race.onLstat = (p, real, bigint) => {
481
+ // The first bigint `lstat` of the parent IS the identity capture — the containment
482
+ // walk takes non-bigint stats.
483
+ if (fired || p !== worktreeCodexDir() || !bigint)
484
+ return undefined;
485
+ fired = true;
486
+ return notADirectory(real);
487
+ };
488
+ const outcome = deploy();
489
+ race.onLstat = null;
490
+ expect(fired).toBe(true);
491
+ expect(outcome.ok).toBe(false);
492
+ const refusal = outcome.writeRefusals.join('\n');
493
+ // The poisoned capture is the first one of this deploy, which is `config.toml`; the two
494
+ // later artifacts take their own captures and are unaffected.
495
+ expect(refusal).toContain('it is not a real directory');
496
+ expect(outcome.written).not.toContain(CODEX_CONFIG_FILENAME);
497
+ // The pin, in two halves. First: the object is not a SYMLINK, so the symlink clause
498
+ // cannot be what refused it — only the type clause can.
499
+ expect(lstatSync(worktreeCodexDir()).isSymbolicLink()).toBe(false);
500
+ // Second: capture refuses BEFORE the open, so that artifact's temp file is never
501
+ // created at all. Accept a non-directory here and the identity is captured from it,
502
+ // both later re-checks compare equal to it, and the deploy writes and reports success
503
+ // against a parent it never validated.
504
+ expect(race.opened.filter((path) => path.includes(`${CODEX_CONFIG_FILENAME}.mx-tmp-`))).toEqual([]);
505
+ });
506
+ });
507
+ /**
508
+ * ── ROUND 11 MAJOR D: THE TEMP FILE'S OWN LINK COUNT ─────────────────────────
509
+ * Immediately after creating the temp file with `O_EXCL`, the write path `fstat`s its own
510
+ * descriptor and refuses if the link count is anything but 1. The code calls this defence
511
+ * in depth and its comment says it "should be unreachable", which is very likely right —
512
+ * `O_EXCL` creates a name that did not exist, so nothing can already be pointing at it.
513
+ *
514
+ * It was not counted either way in round 10's "19 mutants, 1 survivor" tally, and it does
515
+ * survive removal. It is pinned here rather than disclosed as an exception, because it is
516
+ * cheap to pin and "should be unreachable" is precisely the reasoning this file has had to
517
+ * retract three times: the round-8 disclosure said `!open.isFile()` could not be the sole
518
+ * cause of a rejection, and RP14 disproved it.
519
+ *
520
+ * A second name is created against the temp file in the window between the `open` and the
521
+ * `fstat` — real `link(2)`, no forged stat — so the descriptor genuinely reports 2. What
522
+ * the check is protecting is real: with it removed the deploy writes the content, renames,
523
+ * and reports success, while a second name to that inode is held outside the artifact path.
524
+ */
525
+ describe('write path — the temp file this deploy created has exactly ONE name', () => {
526
+ it('a second name created against the temp file between the open and the fstat is refused', () => {
527
+ expect(deploy().ok).toBe(true);
528
+ const secondName = join(worktree, 'temp-second-name.md');
529
+ let tmpPath = '';
530
+ let linked = false;
531
+ let nlinkAtFstat = 0n;
532
+ race.beforeOpen = (path) => {
533
+ if (!path.includes('hooks.json.mx-tmp-'))
534
+ return;
535
+ race.beforeOpen = null;
536
+ tmpPath = path;
537
+ // Fires at the identity re-check that runs immediately after the open and before the
538
+ // `fstat` — the one window in which the temp file exists and has not yet been
539
+ // measured. The stat itself is left untouched.
540
+ race.onLstat = (p, _real, bigint) => {
541
+ if (linked || p !== join(worktree, '.codex') || !bigint)
542
+ return undefined;
543
+ linked = true;
544
+ linkSync(tmpPath, secondName);
545
+ // Measured HERE, not at the end of the test: the refusal path unlinks the temp
546
+ // file, which drops the count back to 1 before any assertion could see it.
547
+ nlinkAtFstat = lstatSync(tmpPath, { bigint: true }).nlink;
548
+ return undefined;
549
+ };
550
+ };
551
+ const outcome = deploy();
552
+ race.onLstat = null;
553
+ expect(linked).toBe(true);
554
+ // The precondition, measured: the second name really is a second name for the very
555
+ // inode the deploy just created, so the descriptor's link count is genuinely 2 — no
556
+ // forged stat is involved, this is what `fstat` on the deploy's own fd returns.
557
+ expect(nlinkAtFstat).toBe(2n);
558
+ expect(outcome.ok).toBe(false);
559
+ const refusal = outcome.writeRefusals.join('\n');
560
+ expect(refusal).toContain('the temporary file this deploy just created');
561
+ expect(refusal).toContain('already has 2 names');
562
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
563
+ unlinkSync(secondName);
564
+ });
565
+ });
199
566
  /**
200
567
  * ─────────────────────────── SF-I (round 5) ───────────────────────────────────
201
568
  * The other way to lose this race has nothing to do with the parent directory: the TEMP
@@ -258,6 +625,1099 @@ describe('write path — the install is verified, so a substituted artifact is n
258
625
  expect(text).toMatch(/AGENTS\.override\.md: a SYMLINK, not a file/);
259
626
  });
260
627
  });
628
+ /**
629
+ * ────────────── SF-L (round 7): THE ONE BENIGN CAUSE OF A DIFFERENT INODE ─────
630
+ * The install check above compares inodes, and there is exactly one way for that to fail
631
+ * with nothing wrong: a second LEGITIMATE deploy renames its own byte-identical artifact
632
+ * into the same path between this deploy's `renameSync` and its verifying `lstat`. The
633
+ * file on disk is correct and the deploy called it a failed write — and since #4896 made
634
+ * a failed write refuse the launch, `mx-agent start` then exits 1. Concurrent deploys are
635
+ * the scenario the rename design exists to make safe, so a false alarm there is the one
636
+ * worth removing.
637
+ *
638
+ * A different inode is now accepted only when what landed is indistinguishable from this
639
+ * deploy's own output: a regular file, ONE name, identical bytes. The two malicious
640
+ * substitutions are unchanged, and the last two tests here are the proof — a symlink fails
641
+ * `isFile()` and a hardlink fails `nlink === 1` even when its content matches exactly.
642
+ *
643
+ * The instrument is the same one the rest of the file uses: `renameSync` calls a test hook
644
+ * with the destination immediately after the real rename, which is precisely the window
645
+ * the race occupies.
646
+ */
647
+ describe('write path — a concurrent IDENTICAL redeploy is not reported as a failure (SF-L)', () => {
648
+ const override = () => join(worktree, AGENTS_OVERRIDE_FILENAME);
649
+ /**
650
+ * What a second honest deploy does: land its own copy of the same bytes, atomically, at
651
+ * the mode `modeForInstalledArtifact` computes. The `chmod` is not decoration — a real
652
+ * deploy `fchmod`s the temp file before the rename, and the acceptance compares the mode
653
+ * (SF-2), so a helper that left it to the ambient umask would be testing the umask.
654
+ */
655
+ const landAnotherFileAt = (destination, bytes, mode = 0o644) => {
656
+ const staged = `${destination}.another-deploy`;
657
+ writeFileSync(staged, bytes);
658
+ chmodSync(staged, mode);
659
+ renameSync(staged, destination);
660
+ };
661
+ it('a second deploy landing IDENTICAL bytes between the rename and the check is a SUCCESS', () => {
662
+ let concurrentInode = 0n;
663
+ race.afterRename = (destination) => {
664
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
665
+ return;
666
+ race.afterRename = null;
667
+ landAnotherFileAt(destination, readFileSync(destination));
668
+ concurrentInode = lstatSync(destination, { bigint: true }).ino;
669
+ };
670
+ const outcome = deploy();
671
+ // The inode at the path is NOT the one this deploy installed — and the deploy still
672
+ // reports the artifact as written, because the bytes are its own output.
673
+ expect(lstatSync(override(), { bigint: true }).ino).toBe(concurrentInode);
674
+ expect(outcome.ok).toBe(true);
675
+ expect(outcome.written).toContain(AGENTS_OVERRIDE_FILENAME);
676
+ expect(outcome.writeFailures).toEqual([]);
677
+ expect(outcome.writeRefusals).toEqual([]);
678
+ });
679
+ it('the launch is not aborted by that race', async () => {
680
+ race.afterRename = (destination) => {
681
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
682
+ return;
683
+ race.afterRename = null;
684
+ landAnotherFileAt(destination, readFileSync(destination));
685
+ };
686
+ const { CodexAdapter } = await import('../lib/runtime/codex-adapter.js');
687
+ const codex = new CodexAdapter({ projectRoot: root });
688
+ expect(() => codex.deployConfig({
689
+ worktreePath: worktree,
690
+ worktreeName: `${TEAM}-20260101`,
691
+ branch: 'demo-branch',
692
+ slot: 0,
693
+ teamName: TEAM,
694
+ baseBranch: 'main',
695
+ initialPrompt: 'x',
696
+ })).not.toThrow();
697
+ });
698
+ it('a file with DIFFERENT bytes landing in that window is still a failed write', () => {
699
+ race.afterRename = (destination) => {
700
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
701
+ return;
702
+ race.afterRename = null;
703
+ landAnotherFileAt(destination, '# not what this deploy generated\n');
704
+ };
705
+ const outcome = deploy();
706
+ expect(outcome.ok).toBe(false);
707
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
708
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
709
+ });
710
+ /**
711
+ * ── SF-4 (round 8): A FILE OF THE WRONG SIZE IS NEVER READ ──────────────────
712
+ * The acceptance ends in `readFileSync(fd)`, which allocates the WHOLE landed file, and
713
+ * the landed file is attacker-influenced by construction. A size pre-check makes the
714
+ * wrong-sized case cost one `lstat` field instead of a full read. The outcome is
715
+ * identical either way, so the assertion is on the READ, not on the verdict.
716
+ */
717
+ it('a file of the wrong SIZE is rejected without being read into memory', () => {
718
+ race.afterRename = (destination) => {
719
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
720
+ return;
721
+ race.afterRename = null;
722
+ landAnotherFileAt(destination, '# not what this deploy generated\n');
723
+ };
724
+ race.fdReads = [];
725
+ const outcome = deploy();
726
+ expect(outcome.ok).toBe(false);
727
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
728
+ expect(race.fdReads.filter((p) => p.endsWith(AGENTS_OVERRIDE_FILENAME))).toEqual([]);
729
+ });
730
+ it('a file of the RIGHT size is still read and compared, so the pre-check is not the verdict', () => {
731
+ race.afterRename = (destination) => {
732
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
733
+ return;
734
+ race.afterRename = null;
735
+ landAnotherFileAt(destination, readFileSync(destination));
736
+ };
737
+ race.fdReads = [];
738
+ expect(deploy().ok).toBe(true);
739
+ expect(race.fdReads.filter((p) => p.endsWith(AGENTS_OVERRIDE_FILENAME))).toEqual([override()]);
740
+ });
741
+ /**
742
+ * ── ROUND 11 MUST FIX A: THE BYTE COMPARISON ITSELF WAS UNPINNED ────────────
743
+ * `landedIsThisDeploysOwnContent` ends in `readFileSync(fd).equals(...)`, and that is the
744
+ * ONE check on this path an attacker cannot satisfy by construction. Size, mode 0644,
745
+ * uid, nlink 1, `{dev, ino}` and the containment walk are all trivially matched by a file
746
+ * the attacker builds; the deploy's own generated bytes are not.
747
+ *
748
+ * It was nevertheless unpinned, and three rounds of mutation testing did not notice,
749
+ * because the mutation was taken in the WRONG DIRECTION. `return false` — the check
750
+ * refusing everything — fails three tests, because it breaks the benign-race ACCEPTANCE
751
+ * this describe block exists for, and was recorded as killed. `return true` — the check
752
+ * ACCEPTING everything, which is the only direction that matters for a control — left all
753
+ * 1939 tests green.
754
+ *
755
+ * The gap in coverage was exact. The one different-bytes test above uses bytes of a
756
+ * DIFFERENT LENGTH, so it dies at the `landed.size` pre-check and never reaches the
757
+ * comparison; the one same-size test lands IDENTICAL bytes and asserts success. Nothing
758
+ * in the suite landed a same-size, different-bytes file. This does.
759
+ *
760
+ * The running code refuses it (confirmed by probe before this test was written), so this
761
+ * is a missing pin rather than a live hole — but an unpinned control is one refactor away
762
+ * from being a live hole, and this is the control that matters most.
763
+ */
764
+ it('MUST FIX: a file of the RIGHT size with DIFFERENT bytes is refused by the byte comparison alone', () => {
765
+ let landedBytes = Buffer.alloc(0);
766
+ let ownBytes = Buffer.alloc(0);
767
+ race.afterRename = (destination) => {
768
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
769
+ return;
770
+ race.afterRename = null;
771
+ ownBytes = readFileSync(destination);
772
+ // Same LENGTH, different CONTENT: a first line the attacker chose, padded out with
773
+ // `#` to exactly the byte count this deploy generated. Every size-shaped question
774
+ // about this file answers "correct", so the size pre-check cannot be what refuses it.
775
+ const head = Buffer.from('# SUBSTITUTED — NOT THIS DEPLOY\'S OUTPUT\n', 'utf-8');
776
+ landedBytes = Buffer.concat([head, Buffer.alloc(ownBytes.length - head.length, 0x23)]);
777
+ landAnotherFileAt(destination, landedBytes);
778
+ };
779
+ const outcome = deploy();
780
+ // The preconditions, stated as measurement: the entry at the artifact path is a regular
781
+ // file, one name, mode 0644, owned by this process, and EXACTLY the size of this
782
+ // deploy's own output — so every check in the acceptance except the byte comparison
783
+ // answers yes, and only `equals` can refuse it.
784
+ const landed = lstatSync(override(), { bigint: true });
785
+ expect(landed.isFile()).toBe(true);
786
+ expect(landed.nlink).toBe(1n);
787
+ expect(Number(landed.mode) & 0o777).toBe(0o644);
788
+ expect(landed.uid).toBe(BigInt(process.geteuid?.() ?? 0));
789
+ expect(landed.size).toBe(BigInt(ownBytes.length));
790
+ expect(readFileSync(override()).equals(ownBytes)).toBe(false);
791
+ // And the file really was read and compared — a size pre-check that had rejected it
792
+ // would leave no read of this path on the record.
793
+ expect(race.fdReads.filter((p) => p.endsWith(AGENTS_OVERRIDE_FILENAME))).toEqual([override()]);
794
+ expect(outcome.ok).toBe(false);
795
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
796
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
797
+ });
798
+ /**
799
+ * ── SF-2 (round 8): THE MODE IS PART OF THE ARTIFACT ────────────────────────
800
+ * The reviewer's probe P2: a distinct regular file with IDENTICAL bytes at mode 0666.
801
+ * The acceptance checked type, link count and bytes only, so it said yes — `ok=true`,
802
+ * the artifact reported as written, and `AGENTS.override.md` left world-writable, which
803
+ * Codex reads as a REPLACEMENT for `AGENTS.md`. A deploy must not certify an instruction
804
+ * file that anyone on the box can rewrite.
805
+ */
806
+ it('a WORLD-WRITABLE file with identical bytes is NOT accepted as this deploy own output', () => {
807
+ race.afterRename = (destination) => {
808
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
809
+ return;
810
+ race.afterRename = null;
811
+ landAnotherFileAt(destination, readFileSync(destination), 0o666);
812
+ };
813
+ const outcome = deploy();
814
+ expect(outcome.ok).toBe(false);
815
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
816
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
817
+ // The bad entry is left in place by design, and it is the world-writable one — which
818
+ // is exactly why reporting it as written was wrong.
819
+ expect(lstatSync(override()).mode & 0o777).toBe(0o666);
820
+ });
821
+ it('a SYMLINK with identical content substituted in that window still fails (SF-I preserved)', () => {
822
+ const decoy = join(root, 'decoy-identical.md');
823
+ race.afterRename = (destination) => {
824
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
825
+ return;
826
+ race.afterRename = null;
827
+ // Same bytes, reached through a link: content equality alone must not accept it.
828
+ writeFileSync(decoy, readFileSync(destination));
829
+ unlinkSync(destination);
830
+ symlinkSync(decoy, destination);
831
+ };
832
+ const outcome = deploy();
833
+ expect(outcome.ok).toBe(false);
834
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
835
+ expect(outcome.writeFailures.join('\n')).toContain('a SYMLINK');
836
+ expect(lstatSync(override()).isSymbolicLink()).toBe(true);
837
+ });
838
+ it('a HARDLINK to a main-repo file with identical content still fails (SF-I preserved)', () => {
839
+ const mainFile = join(root, 'main-repo-target.md');
840
+ race.afterRename = (destination) => {
841
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
842
+ return;
843
+ race.afterRename = null;
844
+ // The hard case for a content-equality rule: byte-identical AND a regular file. The
845
+ // second name is what disqualifies it — a later write through this path would reach
846
+ // the main repo's file.
847
+ writeFileSync(mainFile, readFileSync(destination));
848
+ unlinkSync(destination);
849
+ linkSync(mainFile, destination);
850
+ };
851
+ const outcome = deploy();
852
+ expect(outcome.ok).toBe(false);
853
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
854
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
855
+ expect(outcome.writeFailures.join('\n')).toContain('2 name(s)');
856
+ });
857
+ });
858
+ /**
859
+ * ───── ROUND 8: THE WINDOW BETWEEN THE VERIFYING lstat AND THE ACCEPTANCE ─────
860
+ * SF-L (above) added a second, narrower window to this write path and nothing tested it.
861
+ * The acceptance takes an `lstat` of the artifact path and then RE-OPENS THAT NAME, so
862
+ * everything the acceptance decides can be decided against a different object than the one
863
+ * that was `lstat`ed — if an attacker moves in between.
864
+ *
865
+ * Every SF-I test substitutes BEFORE the `lstat`, which means `landed.isFile()` is already
866
+ * false and the code short-circuits: not one existing test reaches the re-open with a
867
+ * hostile object present. That is why four mutants survived a green suite (round 8 SF-3),
868
+ * and why the FIFO hang below (round 8 MUST FIX) went unnoticed.
869
+ *
870
+ * Reaching the re-open at all takes two steps, so these tests do both: a second HONEST
871
+ * deploy lands its own byte-identical artifact between this deploy's `renameSync` and its
872
+ * verifying `lstat` (the benign race SF-L exists for — it is what makes the inode differ
873
+ * and the acceptance run), and only then does the attacker substitute, timed off that
874
+ * `lstat` via the `onLstat` instrument.
875
+ */
876
+ describe('write path — the acceptance re-open decides on ONE object (round 8)', () => {
877
+ const override = () => join(worktree, AGENTS_OVERRIDE_FILENAME);
878
+ /**
879
+ * What a second honest deploy leaves at the path: a different inode, the same bytes, and
880
+ * the same mode — `modeForInstalledArtifact` is deterministic, so two honest deploys of
881
+ * the same artifact compute the same 0644 and `fchmod` to it.
882
+ */
883
+ const landAnotherHonestDeployAt = (destination) => {
884
+ const staged = `${destination}.another-deploy`;
885
+ writeFileSync(staged, readFileSync(destination));
886
+ chmodSync(staged, 0o644);
887
+ renameSync(staged, destination);
888
+ };
889
+ /**
890
+ * Put the deploy into the one state that reaches the acceptance re-open, then run
891
+ * `substitute` inside the `lstat` → `open` window. The hook returns `undefined`, so the
892
+ * deploy keeps the stat taken BEFORE the substitution — which is exactly the attacker's
893
+ * position: the code has already decided what it believes is at the path.
894
+ */
895
+ const honestRaceThenSubstitute = (artifactRel, substitute) => {
896
+ race.afterRename = (destination) => {
897
+ if (!destination.endsWith(artifactRel))
898
+ return;
899
+ race.afterRename = null;
900
+ landAnotherHonestDeployAt(destination);
901
+ race.onLstat = (p, _real, bigint) => {
902
+ if (p !== destination || !bigint)
903
+ return undefined;
904
+ race.onLstat = null;
905
+ substitute(p);
906
+ return undefined;
907
+ };
908
+ };
909
+ };
910
+ /**
911
+ * ── THE MUST FIX: A FIFO IN THAT WINDOW USED TO HANG THE PROCESS FOREVER ────
912
+ * `open(O_RDONLY)` on a FIFO blocks in the kernel until a writer arrives, and no writer
913
+ * ever arrives here. `openSync` is synchronous, so `mx-agent start` hung indefinitely —
914
+ * no timeout, no log line, nothing written. The reviewer's repro could not even be
915
+ * stopped by vitest's own 20-second test timeout; the run had to be killed from outside.
916
+ * `O_NONBLOCK` makes the open return immediately and the `!open.isFile()` check rejects
917
+ * the FIFO, so the deploy fails closed the way it did before SF-L existed.
918
+ */
919
+ it('a FIFO substituted in that window is refused, and does NOT hang the deploy', () => {
920
+ const startedAt = Date.now();
921
+ honestRaceThenSubstitute(AGENTS_OVERRIDE_FILENAME, (path) => {
922
+ unlinkSync(path);
923
+ execFileSync('mkfifo', [path]);
924
+ });
925
+ const outcome = deploy();
926
+ // The pin. Without `O_NONBLOCK` this line is never reached: the deploy is still inside
927
+ // `openSync` when the test runner is killed.
928
+ expect(Date.now() - startedAt).toBeLessThan(10_000);
929
+ expect(lstatSync(override()).isFIFO()).toBe(true);
930
+ expect(outcome.ok).toBe(false);
931
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
932
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
933
+ });
934
+ /**
935
+ * The narrower window INSIDE the acceptance: between its containment walk (which
936
+ * `lstat`s each path component without `bigint`) and the `open` that resolves the same
937
+ * name again. This is the window `O_NOFOLLOW` exists for, and the only one in which the
938
+ * walk cannot see what the open will get.
939
+ */
940
+ const afterTheContainmentWalkSubstitute = (artifactRel, substitute) => {
941
+ race.afterRename = (destination) => {
942
+ if (!destination.endsWith(artifactRel))
943
+ return;
944
+ race.afterRename = null;
945
+ landAnotherHonestDeployAt(destination);
946
+ race.onLstat = (p, _real, bigint) => {
947
+ // The acceptance's walk is the first NON-bigint lstat of the artifact path after
948
+ // the rename; the verifying lstat before it takes bigint stats.
949
+ if (bigint || p !== destination)
950
+ return undefined;
951
+ race.onLstat = null;
952
+ substitute(p);
953
+ return undefined;
954
+ };
955
+ };
956
+ };
957
+ /**
958
+ * ── SF-3: THE RE-OPEN MUST NOT FOLLOW A LINK ────────────────────────────────
959
+ * A symlink planted after the walk and before the open, pointing at the very file the
960
+ * walk approved. Every check the acceptance makes on the OBJECT then passes — same
961
+ * inode, one name, right mode, right bytes — so `O_NOFOLLOW` on the open is the only
962
+ * thing that refuses it. Without `O_NOFOLLOW` the deploy certifies an artifact path that
963
+ * is a symlink, which is the SF-I property this file exists to protect.
964
+ */
965
+ it('SF-3: a SYMLINK substituted after the containment walk is refused by the open itself', () => {
966
+ const decoy = join(root, 'decoy-same-inode.md');
967
+ afterTheContainmentWalkSubstitute(AGENTS_OVERRIDE_FILENAME, (path) => {
968
+ // Move the approved file aside and leave a link to it: the open, if it follows, gets
969
+ // back the identical inode the acceptance is looking for.
970
+ renameSync(path, decoy);
971
+ symlinkSync(decoy, path);
972
+ });
973
+ const outcome = deploy();
974
+ expect(lstatSync(override()).isSymbolicLink()).toBe(true);
975
+ expect(outcome.ok).toBe(false);
976
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
977
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
978
+ });
979
+ /**
980
+ * ── SF-3: THE fstat IS BOUND TO THE ENTRY THAT WAS lstatED ──────────────────
981
+ * A DIFFERENT regular file with identical bytes, the same mode and one name. Type, link
982
+ * count, mode, owner and bytes all agree; only `{dev, ino}` says it is not the object the
983
+ * acceptance decided about. That comparison is the "decided on one object, not on a name
984
+ * examined twice" claim, and nothing tested it.
985
+ */
986
+ it('SF-3: a DIFFERENT file with identical bytes in that window fails the dev/ino binding', () => {
987
+ let approvedBytes = Buffer.alloc(0);
988
+ let approvedInode = 0n;
989
+ afterTheContainmentWalkSubstitute(AGENTS_OVERRIDE_FILENAME, (path) => {
990
+ approvedBytes = readFileSync(path);
991
+ approvedInode = lstatSync(path, { bigint: true }).ino;
992
+ const other = `${path}.attacker`;
993
+ writeFileSync(other, approvedBytes);
994
+ chmodSync(other, 0o644);
995
+ renameSync(other, path);
996
+ });
997
+ const outcome = deploy();
998
+ expect(outcome.ok).toBe(false);
999
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1000
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1001
+ // The substitute really is byte-identical and correctly moded — the only thing wrong
1002
+ // with it is that it is a different inode.
1003
+ expect(readFileSync(override()).equals(approvedBytes)).toBe(true);
1004
+ expect(lstatSync(override(), { bigint: true }).ino).not.toBe(approvedInode);
1005
+ expect(lstatSync(override()).mode & 0o777).toBe(0o644);
1006
+ });
1007
+ /**
1008
+ * ── SF-3 + QA: EXACTLY ONE nlink CHECK REMOVED IS DETECTED ──────────────────
1009
+ * There are two link-count checks — one on the `lstat`ed entry, one on the `fstat` of the
1010
+ * open descriptor — and each backstops the other, so removing either one alone left the
1011
+ * suite green. These two tests separate them: the first is a second name that exists at
1012
+ * `lstat` time and is gone by the open (only the lstat-side check sees it), the second is
1013
+ * a second name created after the containment walk (only the fstat-side check sees it).
1014
+ */
1015
+ it('SF-3: a second name present at the lstat and gone by the open is refused (lstat-side nlink)', () => {
1016
+ const secondName = join(worktree, 'second-name.md');
1017
+ race.afterRename = (destination) => {
1018
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1019
+ return;
1020
+ race.afterRename = null;
1021
+ landAnotherHonestDeployAt(destination);
1022
+ linkSync(destination, secondName);
1023
+ race.onLstat = (p, _real, bigint) => {
1024
+ if (p !== destination || !bigint)
1025
+ return undefined;
1026
+ race.onLstat = null;
1027
+ // The verifying lstat has already recorded nlink = 2. Dropping the extra name now
1028
+ // means every later look — the containment walk, the fstat — sees nlink = 1.
1029
+ unlinkSync(secondName);
1030
+ return undefined;
1031
+ };
1032
+ };
1033
+ const outcome = deploy();
1034
+ expect(outcome.ok).toBe(false);
1035
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1036
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1037
+ });
1038
+ it('SF-3: a second name created after the containment walk is refused (fstat-side nlink)', () => {
1039
+ const secondName = join(worktree, 'second-name.md');
1040
+ afterTheContainmentWalkSubstitute(AGENTS_OVERRIDE_FILENAME, (path) => {
1041
+ // After the walk, so the walk's own nlink check saw one name. Only the fstat on the
1042
+ // open descriptor can still notice.
1043
+ linkSync(path, secondName);
1044
+ });
1045
+ const outcome = deploy();
1046
+ expect(outcome.ok).toBe(false);
1047
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1048
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1049
+ expect(lstatSync(override()).nlink).toBe(2);
1050
+ });
1051
+ /**
1052
+ * ── ROUND 9 SF-C, COMPLETENESS PASS: THE PARENT CHECK INSIDE THE ACCEPTANCE ─
1053
+ * Round 9 MUST FIX 2 turned the acceptance's parent-identity check from a throw into a
1054
+ * predicate. That is the right report, and it cost a pin: the only test that reached the
1055
+ * check used a SYMLINKED parent, which the acceptance's containment walk refuses too, so
1056
+ * with the check deleted outright the suite stayed green. A survivor introduced by a
1057
+ * remediation is exactly the failure mode round 9 exists to stop, so it is pinned here.
1058
+ *
1059
+ * The state the walk cannot see, built with real syscalls: the artifact's own inode is
1060
+ * MOVED into a fresh real directory, and that directory is renamed over `.codex`. Nothing
1061
+ * along the path is a symlink and nothing has a second name, so containment passes; the
1062
+ * descriptor carries the same `{dev, ino}`, one name, mode 0644, the right owner and
1063
+ * byte-identical content, so every check on the OBJECT passes. Only the parent's identity
1064
+ * says this artifact is sitting in a directory the deploy never validated.
1065
+ */
1066
+ it('SF-C: an artifact MOVED into a fresh directory renamed over the parent is refused', () => {
1067
+ const codexDir = join(worktree, '.codex');
1068
+ let swapped = false;
1069
+ // ── ROUND 11 MAJOR C: THE PRECONDITION IS MEASURED, NOT ASSUMED ───────────
1070
+ // QA saw this test fail once in ten full-suite runs, on `outcome.ok === true`, and it
1071
+ // could not be reproduced afterwards: 45 full-suite runs (25 of them under eight-way
1072
+ // CPU contention), 100 runs of this file alone, and 40 of those under a process
1073
+ // churning directory creation and removal in `/tmp` to stress the inode allocator —
1074
+ // zero failures. No mechanism was found in the test or in the code, so nothing here is
1075
+ // a fix and no retry, timeout or `sequential` has been added to hide it.
1076
+ //
1077
+ // What IS added is the measurement that makes a recurrence conclusive instead of
1078
+ // ambiguous. The refusal this test asserts depends on exactly one property: the entry
1079
+ // at `.codex` after the swap must be a DIFFERENT directory from the one whose identity
1080
+ // the deploy captured. The fresh directory is created while the original is still
1081
+ // live, so on any filesystem that gives live objects distinct identities the two must
1082
+ // differ — measured directly on this container's overlayfs `/tmp`, 20,000 fresh
1083
+ // directories against one live directory produced 0 collisions, though a number is
1084
+ // handed straight back once its object is freed.
1085
+ //
1086
+ // Recording both identities splits the next failure in two. Identities EQUAL: the
1087
+ // filesystem reused a live directory's number, the precondition never held, and the
1088
+ // fault is here. Identities DIFFERENT and `ok` still true: the parent-identity check
1089
+ // accepted a parent it had never validated, which is a real defect in the write path
1090
+ // and a far bigger finding than a flaky test.
1091
+ let parentBefore = { dev: 0n, ino: 0n };
1092
+ let parentAfter = { dev: 0n, ino: 0n };
1093
+ honestRaceThenSubstitute(CODEX_HOOKS_FILENAME, (path) => {
1094
+ const before = lstatSync(codexDir, { bigint: true });
1095
+ parentBefore = { dev: before.dev, ino: before.ino };
1096
+ const fresh = join(worktree, '.codex-fresh');
1097
+ mkdirSync(fresh);
1098
+ // The inode survives a rename, so the object the acceptance is about is unchanged —
1099
+ // only the directory holding it is a different one.
1100
+ renameSync(path, join(fresh, 'hooks.json'));
1101
+ renameSync(codexDir, join(worktree, '.codex-old'));
1102
+ renameSync(fresh, codexDir);
1103
+ const after = lstatSync(codexDir, { bigint: true });
1104
+ parentAfter = { dev: after.dev, ino: after.ino };
1105
+ swapped = true;
1106
+ });
1107
+ const outcome = deploy();
1108
+ expect(swapped).toBe(true);
1109
+ // Containment is intact — a real directory, a real file, no symlink, one name — which
1110
+ // is why the walk cannot refuse this and the parent-identity check must.
1111
+ expect(lstatSync(codexDir).isDirectory()).toBe(true);
1112
+ expect(lstatSync(join(worktree, CODEX_HOOKS_FILENAME)).nlink).toBe(1);
1113
+ // The precondition, asserted BEFORE the outcome so a failure names the right cause.
1114
+ expect(parentAfter).not.toEqual(parentBefore);
1115
+ expect(outcome.ok).toBe(false);
1116
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
1117
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1118
+ });
1119
+ /**
1120
+ * The same check's FAIL-CLOSED half: a parent that cannot be examined at all. RV-2 pins
1121
+ * this for the two pre-install call sites, where it throws; this is the acceptance's
1122
+ * copy, where it returns false. A `catch` that answered "yes, same directory" would
1123
+ * certify an artifact whose parent the deploy could not look at.
1124
+ */
1125
+ it('SF-C: a parent that cannot be EXAMINED during the acceptance is refused', () => {
1126
+ const codexDir = join(worktree, '.codex');
1127
+ let refused = false;
1128
+ race.afterRename = (destination) => {
1129
+ if (!destination.endsWith(CODEX_HOOKS_FILENAME))
1130
+ return;
1131
+ race.afterRename = null;
1132
+ landAnotherHonestDeployAt(destination);
1133
+ race.onLstat = (p, _real, bigint) => {
1134
+ if (p !== codexDir || !bigint)
1135
+ return undefined;
1136
+ race.onLstat = null;
1137
+ refused = true;
1138
+ const err = new Error(`EACCES: permission denied, lstat '${p}'`);
1139
+ err.code = 'EACCES';
1140
+ throw err;
1141
+ };
1142
+ };
1143
+ const outcome = deploy();
1144
+ race.onLstat = null;
1145
+ expect(refused).toBe(true);
1146
+ expect(outcome.ok).toBe(false);
1147
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
1148
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1149
+ });
1150
+ /**
1151
+ * The acceptance's own `catch`, around the `fstat` and the content read. It is the last
1152
+ * fail-closed branch on this path and nothing reached it: the read only happens once
1153
+ * every other check has passed, so making it FAIL needs an instrument. A `catch` that
1154
+ * returned true would certify an artifact this deploy could not read.
1155
+ */
1156
+ it('SF-C: a content read that FAILS is a refusal, not an acceptance', () => {
1157
+ let threw = false;
1158
+ race.afterRename = (destination) => {
1159
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1160
+ return;
1161
+ race.afterRename = null;
1162
+ landAnotherHonestDeployAt(destination);
1163
+ race.onFdRead = (path) => {
1164
+ if (!path.endsWith(AGENTS_OVERRIDE_FILENAME))
1165
+ return;
1166
+ race.onFdRead = null;
1167
+ threw = true;
1168
+ const err = new Error('EIO: i/o error, read');
1169
+ err.code = 'EIO';
1170
+ throw err;
1171
+ };
1172
+ };
1173
+ const outcome = deploy();
1174
+ race.onFdRead = null;
1175
+ expect(threw).toBe(true);
1176
+ expect(outcome.ok).toBe(false);
1177
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1178
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1179
+ });
1180
+ /**
1181
+ * ── ROUND 11 SHOULD FIX E: THE VERIFYING lstat'S OWN CATCH ──────────────────
1182
+ * The acceptance path starts one level up from everything else in this describe block:
1183
+ * after `renameSync` returns, the caller takes `landed = lstatSync(absPath)`, and THAT
1184
+ * call has its own `catch`, which throws "was renamed into place but could not then be
1185
+ * examined … Treating the write as FAILED."
1186
+ *
1187
+ * Nothing asserted that string anywhere in `src/`, and mutating the throw to a silent
1188
+ * `return` left the file green — the deploy would then report an artifact as WRITTEN on
1189
+ * the strength of a `rename` that returned, having been unable to look at what is now at
1190
+ * the path. That is the same class as the SF-C "parent that cannot be EXAMINED" pin one
1191
+ * level down, and it is reachable with the same instrument.
1192
+ */
1193
+ it('SF-E: an artifact that cannot be EXAMINED after the rename is a FAILED write, not a written one', () => {
1194
+ let threw = false;
1195
+ race.afterRename = (destination) => {
1196
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1197
+ return;
1198
+ race.afterRename = null;
1199
+ race.onLstat = (p, _real, bigint) => {
1200
+ if (p !== destination || !bigint)
1201
+ return undefined;
1202
+ race.onLstat = null;
1203
+ threw = true;
1204
+ const err = new Error(`EACCES: permission denied, lstat '${p}'`);
1205
+ err.code = 'EACCES';
1206
+ throw err;
1207
+ };
1208
+ };
1209
+ const outcome = deploy();
1210
+ race.onLstat = null;
1211
+ expect(threw).toBe(true);
1212
+ expect(outcome.ok).toBe(false);
1213
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1214
+ const failure = outcome.writeFailures.join('\n');
1215
+ // The message is the pin: it must say the rename SUCCEEDED and the check did not, which
1216
+ // is a different operator instruction from "nothing was installed".
1217
+ expect(failure).toContain('was renamed into place but could not then be examined');
1218
+ expect(failure).toContain('EACCES');
1219
+ expect(failure).toContain('Treating the write as FAILED');
1220
+ });
1221
+ /**
1222
+ * ── ROUND 9 MUST FIX: AN INODE NUMBER IS NOT A DURABLE IDENTITY (RP14) ──────
1223
+ * Round 8 reported `!open.isFile()` as an unkillable mutant, on the reasoning that it
1224
+ * "cannot be the sole cause of a rejection once the `{dev, ino}` binding is present,
1225
+ * because an identical inode has an identical type". THAT REASONING IS WRONG, and this
1226
+ * test is the disproof. An inode NUMBER is not a durable identity: unlink the object that
1227
+ * holds it and the number is free, and the next object created on that filesystem can
1228
+ * take it and be of ANY TYPE.
1229
+ *
1230
+ * The reviewer's RP14, reproduced here with real syscalls only — no forged stats, unlike
1231
+ * the two SF-C pins below:
1232
+ * 1. An honest concurrent redeploy lands a byte-identical artifact between this
1233
+ * deploy's `renameSync` and its verifying `lstat` (SF-L), which is what makes the
1234
+ * inode differ and the acceptance run at all.
1235
+ * 2. At the verifying `lstat`, the attacker reads the bytes, records the inode number,
1236
+ * UNLINKS the artifact, and creates FIFOs until one takes that same number — the
1237
+ * reviewer measured 322 of 400 trials on this filesystem.
1238
+ * 3. It pre-buffers this deploy's exact bytes into the FIFO (open the read end, open
1239
+ * the write end, write, close the write end), so `readFileSync` on the acceptance's
1240
+ * non-blocking descriptor drains the buffer and then sees a clean EOF.
1241
+ *
1242
+ * Every other check agrees: nlink 1, mode 0644, uid, size, the containment walk (which
1243
+ * refuses symlinks and second names, not FIFOs), and both halves of the `{dev, ino}`
1244
+ * binding. With `!open.isFile()` removed the deploy certifies a FIFO as
1245
+ * `AGENTS.override.md` — `ok=true`, artifact listed as written — and Codex reads that
1246
+ * file as a REPLACEMENT for `AGENTS.md`.
1247
+ *
1248
+ * The reuse is a race with the filesystem's own allocator, so it is a PRECONDITION, not
1249
+ * an assertion: the whole deploy is retried while it is not achieved, and the test skips
1250
+ * rather than fails if the allocator never hands the number back.
1251
+ */
1252
+ it('MUST FIX: a FIFO that REUSES the artifact inode number is refused by the fstat type check (RP14)', (ctx) => {
1253
+ const ATTEMPTS = 8;
1254
+ const PROBES = 150;
1255
+ let reused = false;
1256
+ let targetIno = 0n;
1257
+ let readFd = -1;
1258
+ let outcome = null;
1259
+ for (let attempt = 0; attempt < ATTEMPTS && !reused; attempt++) {
1260
+ // A previous attempt that failed to win the inode leaves the artifact path empty or
1261
+ // holding a FIFO; either way the next deploy must start from a plain state.
1262
+ if (existsSync(override()) && !lstatSync(override()).isFile())
1263
+ unlinkSync(override());
1264
+ race.afterRename = (destination) => {
1265
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1266
+ return;
1267
+ race.afterRename = null;
1268
+ landAnotherHonestDeployAt(destination);
1269
+ race.onLstat = (p, _real, bigint) => {
1270
+ if (p !== destination || !bigint)
1271
+ return undefined;
1272
+ race.onLstat = null;
1273
+ const bytes = readFileSync(destination);
1274
+ targetIno = lstatSync(destination, { bigint: true }).ino;
1275
+ unlinkSync(destination);
1276
+ // The losing probes are KEPT, not unlinked: unlinking each one returns its
1277
+ // number to the head of the allocator's free list and hands it straight back on
1278
+ // the next call, so the target number never surfaces. Holding them drains the
1279
+ // list down to it — in practice within two or three probes, since the number
1280
+ // freed just before the target is this deploy's own replaced artifact.
1281
+ const probes = [];
1282
+ let winner = null;
1283
+ for (let i = 0; i < PROBES && winner === null; i++) {
1284
+ const probe = `${destination}.fifo-probe-${i}`;
1285
+ execFileSync('mkfifo', [probe]);
1286
+ probes.push(probe);
1287
+ if (lstatSync(probe, { bigint: true }).ino === targetIno)
1288
+ winner = probe;
1289
+ }
1290
+ if (winner !== null) {
1291
+ chmodSync(winner, 0o644);
1292
+ renameSync(winner, destination);
1293
+ reused = true;
1294
+ }
1295
+ for (const probe of probes)
1296
+ if (probe !== winner)
1297
+ unlinkSync(probe);
1298
+ // Lost the allocator race: the path is left empty, this deploy fails closed on
1299
+ // the open, and the outer loop tries the whole thing again.
1300
+ if (!reused)
1301
+ return undefined;
1302
+ // Pre-buffer the bytes. The read end is held open for the rest of the deploy so
1303
+ // the data survives; the write end is closed so the acceptance's read sees EOF.
1304
+ readFd = openSync(destination, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
1305
+ const writeFd = openSync(destination, fsConstants.O_WRONLY);
1306
+ writeSync(writeFd, bytes);
1307
+ closeSync(writeFd);
1308
+ return undefined;
1309
+ };
1310
+ };
1311
+ outcome = deploy();
1312
+ race.afterRename = null;
1313
+ race.onLstat = null;
1314
+ if (readFd >= 0) {
1315
+ closeSync(readFd);
1316
+ readFd = -1;
1317
+ }
1318
+ }
1319
+ if (!reused) {
1320
+ console.warn(`RP14 SKIPPED: the filesystem never returned inode ${targetIno} to a new FIFO in ` +
1321
+ `${ATTEMPTS} deploys of ${PROBES} probes — the mutant this test kills is unreachable ` +
1322
+ 'on this filesystem, not absent from the code');
1323
+ ctx.skip();
1324
+ return;
1325
+ }
1326
+ const landed = lstatSync(override(), { bigint: true });
1327
+ // The precondition, stated as measurement: the entry at the artifact path is a FIFO
1328
+ // wearing the inode number of the regular file the acceptance had just `lstat`ed. Every
1329
+ // check but the descriptor type check therefore answers yes.
1330
+ expect(landed.isFIFO()).toBe(true);
1331
+ expect(landed.ino).toBe(targetIno);
1332
+ expect(landed.nlink).toBe(1n);
1333
+ expect(Number(landed.mode) & 0o777).toBe(0o644);
1334
+ expect(outcome?.ok).toBe(false);
1335
+ expect(outcome?.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1336
+ expect(outcome?.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1337
+ });
1338
+ /**
1339
+ * ── ROUND 11 MUST FIX B: RP14 IS REAL, AND IT IS FILESYSTEM-CONDITIONAL ─────
1340
+ * RP14 above is the SOLE killer of `!open.isFile()`, and it treats inode reuse as a
1341
+ * PRECONDITION — if the allocator never hands the number back it calls `ctx.skip()`. That
1342
+ * makes the strength of a MUST FIX pin depend on what backs the temp directory, and the
1343
+ * two reviewers measured different filesystems and both were right:
1344
+ *
1345
+ * overlayfs (`/tmp` in this container) 25 of 25 runs reuse achieved, never skipped
1346
+ * ext4 (`/workspace`) 13 of 13 runs reuse achieved, never skipped
1347
+ * tmpfs (`/dev/shm`) 0 of 3 runs SKIPPED every time
1348
+ *
1349
+ * and decisively: with `!open.isFile()` DELETED and `TMPDIR=/dev/shm`, the file reports
1350
+ * `44 passed | 1 skipped`, rc=0. On tmpfs the round-8 MUST FIX regresses silently.
1351
+ *
1352
+ * The fix is not to find out what CI's `/tmp` is backed by — that is a fact about the
1353
+ * runner, and it can change without anyone touching this repo. It is to remove the
1354
+ * dependency. RP14 STAYS, because a real-syscall demonstration that the attack is
1355
+ * reachable is worth having; this test sits beside it and pins the same check
1356
+ * deterministically, on any filesystem, using the `statReporting` instrument the SF-C
1357
+ * pins below already use.
1358
+ *
1359
+ * The object at the path is a REAL `mkfifo` FIFO, pre-buffered with this deploy's exact
1360
+ * bytes. Only the verifying `lstat` is forged, and only in the two fields a real inode
1361
+ * reuse would have supplied for free: it reports a regular file of the artifact's size,
1362
+ * carrying the FIFO's own `{dev, ino}`, `nlink` 1 and mode 0644. Every check downstream
1363
+ * then agrees — the containment walk (which refuses symlinks and second names, not
1364
+ * FIFOs), both halves of the `{dev, ino}` binding against the open descriptor, the link
1365
+ * count, the mode, the owner, and the byte comparison, which reads the pre-buffered bytes
1366
+ * and finds them equal. `open.isFile()` on the descriptor is the only thing left that can
1367
+ * refuse it.
1368
+ *
1369
+ * WHAT THE FORGERY MODELS, AND WHAT IT DOES NOT CLAIM (#4897 INFO-1). "Only the verifying
1370
+ * `lstat` is forged" is true, but do not read it as saying the composite state above is
1371
+ * one a single kernel call could hand back. It is not: an inode's type lives in its mode
1372
+ * bits, so a REAL `lstat` of a FIFO always reports a FIFO. What this pins is a faithful
1373
+ * MODEL of RP14's two-instant sequence — a regular file at `lstat` time, a FIFO by `open`
1374
+ * time, the same inode number across both — collapsed into one stat so the pin lands on
1375
+ * any filesystem. The STATE is reachable, which is what makes the check worth pinning; it
1376
+ * is the single-call RENDERING of it that is synthetic. The pin is valid either way.
1377
+ */
1378
+ it('MUST FIX: a FIFO reported by lstat as a regular file is refused by the fstat type check (deterministic RP14)', () => {
1379
+ let fired = false;
1380
+ let readFd = -1;
1381
+ let fifoIno = 0n;
1382
+ let installedIno = 0n;
1383
+ race.afterRename = (destination) => {
1384
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1385
+ return;
1386
+ race.afterRename = null;
1387
+ const bytes = readFileSync(destination);
1388
+ installedIno = lstatSync(destination, { bigint: true }).ino;
1389
+ // The FIFO is created ASIDE and renamed over the artifact, not created at the
1390
+ // artifact's own name after unlinking it. Unlinking first frees this deploy's inode
1391
+ // number and the allocator hands it straight back to the FIFO — which is #4908,
1392
+ // inode reuse at the PRIMARY install check, a separate finding with its own PR. This
1393
+ // test is about the acceptance, so it must not land on that: allocating the FIFO
1394
+ // while the artifact still holds its number guarantees the two differ, which is what
1395
+ // makes the call site's `{dev, ino}` comparison fail and the acceptance run at all.
1396
+ const aside = `${destination}.fifo-aside`;
1397
+ execFileSync('mkfifo', [aside]);
1398
+ chmodSync(aside, 0o644);
1399
+ // Pre-buffer this deploy's own bytes. The read end is held open for the rest of the
1400
+ // deploy so the data survives; the write end is closed so the acceptance's own
1401
+ // non-blocking read drains the buffer and then sees a clean EOF. Without this the
1402
+ // content comparison, not the type check, would be doing the refusing.
1403
+ readFd = openSync(aside, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
1404
+ const writeFd = openSync(aside, fsConstants.O_WRONLY);
1405
+ writeSync(writeFd, bytes);
1406
+ closeSync(writeFd);
1407
+ // A FIFO keeps its inode across a rename, so what arrives at the artifact path is the
1408
+ // object already holding this deploy's bytes.
1409
+ renameSync(aside, destination);
1410
+ fifoIno = lstatSync(destination, { bigint: true }).ino;
1411
+ race.onLstat = (p, real, bigint) => {
1412
+ if (fired || p !== destination || !bigint)
1413
+ return undefined;
1414
+ fired = true;
1415
+ // What a real inode-number reuse would have handed the deploy: an entry that
1416
+ // answers "regular file" and carries the right size. Everything else — including
1417
+ // `{dev, ino}` — is the FIFO's own, unforged.
1418
+ return statReporting(real, {
1419
+ isFile: () => true,
1420
+ isFIFO: () => false,
1421
+ size: BigInt(bytes.length),
1422
+ });
1423
+ };
1424
+ };
1425
+ const outcome = deploy();
1426
+ race.onLstat = null;
1427
+ if (readFd >= 0)
1428
+ closeSync(readFd);
1429
+ expect(fired).toBe(true);
1430
+ // The precondition, measured against the REAL filesystem, not the forged stat: what is
1431
+ // at the artifact path is a FIFO, with one name, mode 0644, and the inode the deploy's
1432
+ // `lstat` reported — so the `{dev, ino}` binding to the open descriptor agrees.
1433
+ const real = lstatSync(override(), { bigint: true });
1434
+ expect(real.isFIFO()).toBe(true);
1435
+ expect(real.ino).toBe(fifoIno);
1436
+ expect(real.nlink).toBe(1n);
1437
+ expect(Number(real.mode) & 0o777).toBe(0o644);
1438
+ // And it is NOT the inode this deploy installed — so the acceptance really ran, and
1439
+ // this test is not quietly re-testing #4908.
1440
+ expect(fifoIno).not.toBe(installedIno);
1441
+ expect(outcome.ok).toBe(false);
1442
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1443
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1444
+ });
1445
+ /**
1446
+ * ── ROUND 9 SF-C: THE TWO CHECKS THE ROUND-8 DISCLOSURE MISSED ──────────────
1447
+ * QA re-derived the mutation matrix by hand and found FOUR survivors where round 8
1448
+ * reported two. The two undisclosed ones are pinned here.
1449
+ *
1450
+ * `landed.isFile()` — the LSTAT-side type check at the top of the acceptance, a separate
1451
+ * and earlier check from the `open.isFile()` one on the descriptor. Every currently
1452
+ * reachable non-regular object is also caught by the size pre-check below it (a FIFO and
1453
+ * a socket both `lstat` as size 0, and no generated artifact is empty), which is what
1454
+ * masked it. That masking is incidental: the artifacts' sizes are not a security
1455
+ * property, and the check that says "this acceptance is about a REGULAR FILE" is this
1456
+ * one. So it is pinned against the state the size check cannot mask — a stat that agrees
1457
+ * on every field and reports the entry is not a regular file.
1458
+ */
1459
+ it('SF-C: a landed entry that is not a REGULAR FILE is refused (lstat-side type check)', () => {
1460
+ let fired = false;
1461
+ race.afterRename = (destination) => {
1462
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1463
+ return;
1464
+ race.afterRename = null;
1465
+ race.onLstat = (p, real, bigint) => {
1466
+ if (fired || p !== destination || !bigint)
1467
+ return undefined;
1468
+ fired = true;
1469
+ return statReporting(real, { isFile: () => false });
1470
+ };
1471
+ };
1472
+ const outcome = deploy();
1473
+ race.onLstat = null;
1474
+ expect(fired).toBe(true);
1475
+ expect(outcome.ok).toBe(false);
1476
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1477
+ const failure = outcome.writeFailures.join('\n');
1478
+ expect(failure).toContain('NOT the file this deploy wrote');
1479
+ expect(failure).toContain('a non-regular file');
1480
+ });
1481
+ /**
1482
+ * `open.dev` ALONE. Round 8 reported `dev` and `ino` killed as a pair, which is true when
1483
+ * both are cut together — but cutting `dev` on its own left the suite green, because
1484
+ * every substitution the suite performs also produces a DIFFERENT INODE NUMBER, and the
1485
+ * `ino` half then does all the work. A same-number-different-device object is the one
1486
+ * case `ino` cannot answer, and it is the same class as RV-1 one level down: this is the
1487
+ * comparison that binds the OPEN DESCRIPTOR to the entry that was `lstat`ed, and half of
1488
+ * a two-field identity is not an identity.
1489
+ */
1490
+ it('SF-C: an open descriptor on another DEVICE with the same inode number is refused', () => {
1491
+ let fired = false;
1492
+ let realDev = 0n;
1493
+ let realIno = 0n;
1494
+ race.afterRename = (destination) => {
1495
+ if (!destination.endsWith(AGENTS_OVERRIDE_FILENAME))
1496
+ return;
1497
+ race.afterRename = null;
1498
+ race.onLstat = (p, real, bigint) => {
1499
+ if (fired || p !== destination || !bigint)
1500
+ return undefined;
1501
+ fired = true;
1502
+ realDev = real.dev;
1503
+ realIno = real.ino;
1504
+ return statReporting(real, { dev: realDev + 1n });
1505
+ };
1506
+ };
1507
+ const outcome = deploy();
1508
+ race.onLstat = null;
1509
+ expect(fired).toBe(true);
1510
+ expect(outcome.ok).toBe(false);
1511
+ expect(outcome.written).not.toContain(AGENTS_OVERRIDE_FILENAME);
1512
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1513
+ // The pin: nothing moved the file, so the descriptor the acceptance opened and the
1514
+ // entry it `lstat`ed carry the SAME inode number — the `ino` half of the comparison
1515
+ // agrees, and only the `dev` half can refuse this.
1516
+ const now = lstatSync(override(), { bigint: true });
1517
+ expect(now.ino).toBe(realIno);
1518
+ expect(now.dev).toBe(realDev);
1519
+ });
1520
+ /**
1521
+ * ── SF-1: A BYTE-IDENTICAL FILE SOMEWHERE ELSE IS NOT THIS DEPLOY'S ARTIFACT ─
1522
+ * The reviewer's probe P3, reproduced: a byte-identical copy of the artifact in the main
1523
+ * repo, and `<worktree>/.codex` swapped for a symlink to it AFTER the rename, so the
1524
+ * verifying `lstat` resolves into the main repo. Content equality alone said yes and the
1525
+ * deploy reported the artifact as WRITTEN; the pre-SF-L code refused.
1526
+ *
1527
+ * ── AND IT IS REPORTED AS WHAT IT IS (round 9 MUST FIX 2) ───────────────────
1528
+ * This test used to assert the refusal text `assertSameDirectory` produces — including
1529
+ * "Nothing was installed." — for a state in which the rename had ALREADY SUCCEEDED and a
1530
+ * 4983-byte artifact was on disk. Both halves of that message are false here ("the bytes
1531
+ * would land outside this worktree": they already landed, inside it), and a
1532
+ * `ContainedWriteRefusal` filed it under `writeRefusals`, telling the operator a
1533
+ * containment refusal had happened when what happened was a post-install directory swap.
1534
+ * The security property is unchanged and still asserted — refused, not written, main repo
1535
+ * untouched. What changed is that the report now says the true thing: the acceptance
1536
+ * returns false, the caller's own "NOT the file this deploy wrote" error fires, and it
1537
+ * classifies as a write FAILURE.
1538
+ */
1539
+ it('SF-1: a byte-identical file reached through a SWAPPED parent is a failed write, not a containment refusal', () => {
1540
+ expect(deploy().ok).toBe(true);
1541
+ race.afterRename = (destination) => {
1542
+ if (!destination.endsWith(CODEX_HOOKS_FILENAME))
1543
+ return;
1544
+ race.afterRename = null;
1545
+ // The install itself succeeded into the real directory. The attacker then makes the
1546
+ // NAME point at the main repo and puts this deploy's own bytes there, so every
1547
+ // content-shaped question about the path answers "correct".
1548
+ const bytes = readFileSync(destination);
1549
+ swapCodexDirForASymlinkToMainRepo();
1550
+ writeFileSync(destination, bytes);
1551
+ chmodSync(destination, 0o644);
1552
+ };
1553
+ const outcome = deploy();
1554
+ restoreCodexDir();
1555
+ // The artifact this deploy installed is on disk, in the real directory, holding this
1556
+ // deploy's own bytes — which is why "Nothing was installed" was the wrong thing to say.
1557
+ const installed = readFileSync(join(worktree, CODEX_HOOKS_FILENAME), 'utf-8');
1558
+ expect(installed.length).toBeGreaterThan(0);
1559
+ writeFileSync(join(mainCodex, 'hooks.json'), MAIN_HOOKS_SENTINEL);
1560
+ expect(outcome.ok).toBe(false);
1561
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
1562
+ // CLASSIFICATION: a write failure, not a containment refusal. Nothing about this
1563
+ // artifact belongs in `writeRefusals` — the write was not refused, it happened.
1564
+ expect(outcome.writeRefusals).toEqual([]);
1565
+ const failure = outcome.writeFailures.join('\n');
1566
+ expect(failure).toContain('NOT the file this deploy wrote');
1567
+ // MESSAGE: no claim that nothing was installed, and no claim that bytes would land
1568
+ // outside the worktree — the bytes landed inside it, at the path this deploy chose.
1569
+ expect(failure).not.toContain('Nothing was installed');
1570
+ expect(failure).not.toContain('would land outside this worktree');
1571
+ });
1572
+ /**
1573
+ * ── SF-1, THE SECOND ANCHOR: THE WHOLE PATH, NOT JUST THE PARENT ─────────────
1574
+ * The parent-identity check cannot see anything ABOVE the parent. Here the worktree
1575
+ * directory is MOVED — so `.codex` keeps its inode and the parent check agrees — and a
1576
+ * symlink is left in its place. The artifact path now names a file outside the worktree
1577
+ * this deploy was told to write, and only the containment walk can tell.
1578
+ */
1579
+ it('SF-1: a worktree root replaced by a SYMLINK is refused even when the parent inode is unchanged', () => {
1580
+ const moved = join(root, 'moved-worktree');
1581
+ honestRaceThenSubstitute(CODEX_HOOKS_FILENAME, () => {
1582
+ renameSync(worktree, moved);
1583
+ symlinkSync(moved, worktree);
1584
+ });
1585
+ const outcome = deploy();
1586
+ unlinkSync(worktree);
1587
+ renameSync(moved, worktree);
1588
+ expect(outcome.ok).toBe(false);
1589
+ expect(outcome.written).not.toContain(CODEX_HOOKS_FILENAME);
1590
+ expect(outcome.writeFailures.join('\n')).toContain('NOT the file this deploy wrote');
1591
+ });
1592
+ });
1593
+ /**
1594
+ * ─────── SF-K (round 7): THE RESIDUAL IS DECLARED, SO IT MUST BE FINDABLE ─────
1595
+ * The residual this write path cannot close: `<worktree>/.codex` is swapped for a symlink
1596
+ * to the main repo's `.codex` before the `open`, and RESTORED before the first identity
1597
+ * check. Both checks then pass — every `lstat` of the name sees the original directory —
1598
+ * but the temp file was created behind the swapped name, so its ~1301 bytes are in the
1599
+ * MAIN REPO, the `rename` resolves the temp name in the restored directory and fails
1600
+ * ENOENT, and the cleanup `unlink` misses for the same reason. Measured 1 in 6,000 deploys
1601
+ * at a 5-microsecond swapper hold.
1602
+ *
1603
+ * The deploy already fails closed and reports nothing as written; what it did not do was
1604
+ * say WHERE the litter is, so an operator had no way to find it. These tests pin the
1605
+ * reporting. They do not claim the residual is closed — closing it needs `openat`, which
1606
+ * Node does not expose.
1607
+ *
1608
+ * The restore is timed off the first identity check's `lstat`, which is the moment the
1609
+ * measured attack has to hit.
1610
+ */
1611
+ describe('write path — a temp file that outlives the deploy is NAMED (SF-K)', () => {
1612
+ it('the swap-and-restore residual reports the temp path it left in the main repo', () => {
1613
+ expect(deploy().ok).toBe(true);
1614
+ let restored = false;
1615
+ race.beforeOpen = (path) => {
1616
+ if (!path.includes('hooks.json.mx-tmp-'))
1617
+ return;
1618
+ race.beforeOpen = null;
1619
+ // Swapped: this `openSync` creates the temp inside the MAIN repo's .codex.
1620
+ swapCodexDirForASymlinkToMainRepo();
1621
+ race.onLstat = (p, _real, bigint) => {
1622
+ if (restored || p !== join(worktree, '.codex') || !bigint)
1623
+ return undefined;
1624
+ // Restored before the first identity check looks — so the check sees the original
1625
+ // directory, agrees, and the deploy proceeds with a temp file it can no longer name.
1626
+ restored = true;
1627
+ restoreCodexDir();
1628
+ return lstatSync(p, { bigint: true });
1629
+ };
1630
+ };
1631
+ const outcome = deploy();
1632
+ race.onLstat = null;
1633
+ expect(restored).toBe(true);
1634
+ const temps = mainRepoTemps();
1635
+ expect(temps).toHaveLength(1);
1636
+ expect(outcome.ok).toBe(false);
1637
+ const report = [...outcome.writeFailures, ...outcome.writeRefusals].join('\n');
1638
+ expect(report).toContain('LEFT BEHIND');
1639
+ // The whole point: the operator can find the file. The reported path is the name the
1640
+ // deploy used — the same basename, in the directory the operator must now look in.
1641
+ expect(report).toContain(join(worktree, '.codex', temps[0]));
1642
+ expect(report).toContain('the cleanup unlink found NOTHING at that name');
1643
+ // Stated as the residual it is, in the corrected wording: inert, not live.
1644
+ expect(report).toContain('no bytes reach a LIVE path outside the worktree');
1645
+ expect(report).toContain('bytes can reach an INERT one');
1646
+ // The main repo's own fleet-wide file is untouched — this is litter, not a write.
1647
+ expect(readFileSync(join(mainCodex, 'hooks.json'), 'utf-8')).toBe(MAIN_HOOKS_SENTINEL);
1648
+ unlinkSync(join(mainCodex, temps[0]));
1649
+ });
1650
+ /**
1651
+ * ── INFO-2 (round 8): NOT SAID WHEN THE FILE IS GONE ────────────────────────
1652
+ * The parent directory moved, so the note used to fire — but the cleanup `unlink`
1653
+ * SUCCEEDED (it followed the swapped name and removed the temp), so there is nothing
1654
+ * left behind and the operator was being sent to hunt for a file that does not exist.
1655
+ */
1656
+ it('a refusal whose cleanup unlink SUCCEEDED says nothing about a file left behind', () => {
1657
+ expect(deploy().ok).toBe(true);
1658
+ race.beforeOpen = (path) => {
1659
+ if (!path.includes('hooks.json.mx-tmp-'))
1660
+ return;
1661
+ race.beforeOpen = null;
1662
+ swapCodexDirForASymlinkToMainRepo();
1663
+ };
1664
+ const outcome = deploy();
1665
+ restoreCodexDir();
1666
+ expect(outcome.ok).toBe(false);
1667
+ const refusal = outcome.writeRefusals.join('\n');
1668
+ expect(refusal).toContain('was REPLACED');
1669
+ expect(refusal).not.toContain('LEFT BEHIND');
1670
+ // And the claim is true: the temp file really is gone from where it was created.
1671
+ expect(mainRepoTemps()).toEqual([]);
1672
+ });
1673
+ /**
1674
+ * The parent moved AND the cleanup missed — the note fires, and it says BOTH reasons.
1675
+ * `.codex` is swapped for a symlink to the main repo (so the temp is created there) and
1676
+ * then replaced with a fresh empty directory before the first identity check: the check
1677
+ * refuses, the unlink resolves into the new directory and finds nothing, and the temp is
1678
+ * still sitting in the main repo where only this note can point an operator at it.
1679
+ */
1680
+ it('a refusal whose cleanup MISSED names the temp path and both reasons', () => {
1681
+ expect(deploy().ok).toBe(true);
1682
+ const codexDir = join(worktree, '.codex');
1683
+ let replaced = false;
1684
+ race.beforeOpen = (path) => {
1685
+ if (!path.includes('hooks.json.mx-tmp-'))
1686
+ return;
1687
+ race.beforeOpen = null;
1688
+ swapCodexDirForASymlinkToMainRepo();
1689
+ race.onLstat = (p, _real, bigint) => {
1690
+ if (replaced || p !== codexDir || !bigint)
1691
+ return undefined;
1692
+ replaced = true;
1693
+ unlinkSync(codexDir);
1694
+ mkdirSync(codexDir);
1695
+ return undefined;
1696
+ };
1697
+ };
1698
+ const outcome = deploy();
1699
+ race.onLstat = null;
1700
+ expect(replaced).toBe(true);
1701
+ expect(outcome.ok).toBe(false);
1702
+ const refusal = outcome.writeRefusals.join('\n');
1703
+ expect(refusal).toContain('LEFT BEHIND');
1704
+ expect(refusal).toMatch(/hooks\.json\.mx-tmp-\d+-[0-9a-f]+/);
1705
+ expect(refusal).toContain('is no longer the one this deploy checked');
1706
+ expect(refusal).toContain('the cleanup unlink found NOTHING at that name');
1707
+ const temps = mainRepoTemps();
1708
+ expect(temps).toHaveLength(1);
1709
+ rmSync(codexDir, { recursive: true });
1710
+ renameSync(`${codexDir}.real`, codexDir);
1711
+ unlinkSync(join(mainCodex, temps[0]));
1712
+ });
1713
+ it('an ordinary deploy says nothing about temp files, because there are none', () => {
1714
+ const outcome = deploy();
1715
+ expect(outcome.ok).toBe(true);
1716
+ expect(outcome.lines.map((l) => l.text).join('\n')).not.toContain('LEFT BEHIND');
1717
+ expect(mainRepoTemps()).toEqual([]);
1718
+ expect(readdirSync(join(worktree, '.codex')).filter((e) => e.includes('.mx-tmp-'))).toEqual([]);
1719
+ });
1720
+ });
261
1721
  /**
262
1722
  * MUTANT M8, ASSERTED ON BEHAVIOUR RATHER THAN ON SOURCE TEXT (round 5 recommendation).
263
1723
  *