@memnexus-ai/mx-agent-cli 0.1.265 → 0.1.267

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.
Files changed (33) hide show
  1. package/dist/__tests__/runtime-codex-adapter.test.js +18 -5
  2. package/dist/__tests__/runtime-codex-adapter.test.js.map +1 -1
  3. package/dist/__tests__/runtime-codex-config.test.js +430 -15
  4. package/dist/__tests__/runtime-codex-config.test.js.map +1 -1
  5. package/dist/__tests__/runtime-codex-guard-proof.test.d.ts +2 -0
  6. package/dist/__tests__/runtime-codex-guard-proof.test.d.ts.map +1 -0
  7. package/dist/__tests__/runtime-codex-guard-proof.test.js +747 -0
  8. package/dist/__tests__/runtime-codex-guard-proof.test.js.map +1 -0
  9. package/dist/__tests__/start-runtime-wiring.test.js +91 -2
  10. package/dist/__tests__/start-runtime-wiring.test.js.map +1 -1
  11. package/dist/commands/codex-prove-guards.d.ts +62 -0
  12. package/dist/commands/codex-prove-guards.d.ts.map +1 -0
  13. package/dist/commands/codex-prove-guards.js +353 -0
  14. package/dist/commands/codex-prove-guards.js.map +1 -0
  15. package/dist/commands/start.d.ts.map +1 -1
  16. package/dist/commands/start.js +27 -1
  17. package/dist/commands/start.js.map +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +33 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/lib/runtime/codex-adapter.d.ts +42 -2
  22. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
  23. package/dist/lib/runtime/codex-adapter.js +81 -9
  24. package/dist/lib/runtime/codex-adapter.js.map +1 -1
  25. package/dist/lib/runtime/codex-config.d.ts +122 -4
  26. package/dist/lib/runtime/codex-config.d.ts.map +1 -1
  27. package/dist/lib/runtime/codex-config.js +292 -23
  28. package/dist/lib/runtime/codex-config.js.map +1 -1
  29. package/dist/lib/runtime/codex-guard-proof.d.ts +127 -0
  30. package/dist/lib/runtime/codex-guard-proof.d.ts.map +1 -0
  31. package/dist/lib/runtime/codex-guard-proof.js +372 -0
  32. package/dist/lib/runtime/codex-guard-proof.js.map +1 -0
  33. package/package.json +1 -1
@@ -13,7 +13,7 @@ import { spawnSync } from 'child_process';
13
13
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs';
14
14
  import { join, resolve } from 'path';
15
15
  import { tmpdir } from 'os';
16
- import { AGENTS_OVERRIDE_FILENAME, CODEX_AGENT_GATE_COMMAND, CODEX_APPROVAL_POLICY, CODEX_CANONICAL_FOLD_NOTICE, CODEX_CONFIG_FILENAME, CODEX_DEFAULT_MODEL, CODEX_HOOKS_FILENAME, CODEX_MARKER_DEGRADATION_NOTICE, CODEX_SANDBOX_MODE, PHASE1_PORTED_GUARDS, PROJECT_DOC_MAX_BYTES, VERIFIED_CODEX_VERSION, assertNoHooksGrant, buildAgentsOverride, buildCodexConfigToml, buildCodexHooksJson, codexAgentGateCommand, codexHookCommand, codexHookTrustPreconditions, deployCodexConfig, measureInstructionChain, phase1HookEntries, resolveGitWritableRoots, resolveMemnexusMcpServer, tomlString, } from '../lib/runtime/codex-config.js';
16
+ import { AGENTS_OVERRIDE_FILENAME, CODEX_AGENT_GATE_COMMAND, CODEX_APPROVAL_POLICY, CODEX_CANONICAL_FOLD_NOTICE, CODEX_CONFIG_FILENAME, CODEX_DEFAULT_MODEL, CODEX_HOOKS_FILENAME, CODEX_MARKER_DEGRADATION_NOTICE, CODEX_SANDBOX_MODE, PHASE1_PORTED_GUARDS, PROJECT_DOC_MAX_BYTES, VERIFIED_CODEX_VERSION, assertNoHooksGrant, buildAgentsOverride, buildCodexConfigToml, buildCodexHooksJson, codexAgentGateCommand, codexHookCommand, codexHookTrustKeysForDoc, codexHookTrustPreconditions, deployCodexConfig, measureInstructionChain, phase1HookEntries, resolveGitWritableRoots, resolveMemnexusMcpServer, readDeployedHooksDoc, tomlString, } from '../lib/runtime/codex-config.js';
17
17
  import { buildClaudeLocalContent } from '../lib/claude.js';
18
18
  let root;
19
19
  let worktree;
@@ -275,11 +275,24 @@ describe('codexHookCommand — resolution and fail direction (executed, not matc
275
275
  });
276
276
  return { status: r.status, stderr: r.stderr ?? '' };
277
277
  };
278
- /** A worktree-shaped tree whose guard script records that it ran, then blocks. */
279
- const makeTree = (script) => {
278
+ /**
279
+ * A worktree-shaped tree whose guard script records that it ran, then blocks.
280
+ *
281
+ * The `.git` entry is not decoration: since #4852 the upward walk accepts a
282
+ * `.claude/hooks/` directory only at a repository boundary, so a fixture without one
283
+ * is not a repository root and the walk correctly refuses to resolve there. `marker`
284
+ * picks which shape of boundary — a `.git` DIRECTORY is a main checkout, a `.git`
285
+ * FILE is a linked worktree, and linked worktrees are the normal case in this repo.
286
+ */
287
+ const makeTree = (script, opts = {}) => {
280
288
  const root = realpathSync(mkdtempSync(join(tmpdir(), 'codex-hook-')));
281
289
  mkdirSync(join(root, '.claude', 'hooks'), { recursive: true });
282
- writeFileSync(join(root, '.claude', 'hooks', script), '#!/bin/bash\necho "GUARD-RAN" >&2\nexit 2\n');
290
+ writeFileSync(join(root, '.claude', 'hooks', script), `#!/bin/bash\necho "${opts.tag ?? 'GUARD-RAN'}" >&2\nexit 2\n`);
291
+ const marker = opts.marker ?? 'dir';
292
+ if (marker === 'dir')
293
+ mkdirSync(join(root, '.git'));
294
+ else if (marker === 'file')
295
+ writeFileSync(join(root, '.git'), `gitdir: ${root}/../.git/worktrees/x\n`);
283
296
  mkdirSync(join(root, 'nested', 'deeper'), { recursive: true });
284
297
  return root;
285
298
  };
@@ -359,6 +372,287 @@ describe('codexHookCommand — resolution and fail direction (executed, not matc
359
372
  }
360
373
  });
361
374
  });
375
+ /**
376
+ * SF-27 (#4852): the upward walk resolved the NEAREST ancestor `.claude/hooks/`, so
377
+ * nested agent-worktree debris shadowed the canonical guard.
378
+ *
379
+ * Fail direction was already right for "found nothing" (exit 2). This is the other
380
+ * half: "found the WRONG one" executed it. The realistic payload is a STALE guard —
381
+ * a copy predating the bypass closures in #4811/#4812/#4814/#4829 — which runs,
382
+ * allows, and reports nothing.
383
+ *
384
+ * Every test EXECUTES the generated command through real bash against a fixture tree.
385
+ * The two guard bodies print DIFFERENT tags, so which one ran is observable rather
386
+ * than inferred.
387
+ *
388
+ * MUTATION CHECK: delete the `[ -e "$d/.git" ]` boundary test, or the case-glob skip
389
+ * for the `.claude/worktrees/` segment, from codexHookCommand and `the canonical guard
390
+ * runs, not the nested shadow` fails with SHADOW-RAN. Verified 2026-08-02.
391
+ */
392
+ describe('codexHookCommand — the walk stops at a repository boundary (#4852 / SF-27)', () => {
393
+ const GUARD = 'git-mutation-guard.sh';
394
+ const trees = [];
395
+ /**
396
+ * `env` is built from scratch, so PWD is ABSENT unless a test passes it. That is not
397
+ * a detail: with PWD unset bash sets it from getcwd, i.e. to the physical path, and
398
+ * the SF-1 symlink bypass is then unreachable and untestable. Tests that care about
399
+ * the logical-vs-physical distinction pass PWD explicitly, exactly as a real shell
400
+ * would export it to the hook process.
401
+ */
402
+ const runHook = (cwd, env = {}) => {
403
+ const r = spawnSync('bash', ['-c', codexHookCommand(GUARD)], {
404
+ cwd,
405
+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', ...env },
406
+ encoding: 'utf-8',
407
+ input: '{}',
408
+ });
409
+ return { status: r.status, stderr: r.stderr ?? '' };
410
+ };
411
+ /** A checkout root: `.git` marker (`dir` = main repo, `file` = linked worktree). */
412
+ const makeRepo = (marker, tag) => {
413
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'codex-sf27-')));
414
+ trees.push(root);
415
+ if (marker === 'dir')
416
+ mkdirSync(join(root, '.git'));
417
+ else if (marker === 'file')
418
+ writeFileSync(join(root, '.git'), 'gitdir: /elsewhere/.git/worktrees/x\n');
419
+ if (tag) {
420
+ mkdirSync(join(root, '.claude', 'hooks'), { recursive: true });
421
+ writeFileSync(join(root, '.claude', 'hooks', GUARD), `#!/bin/bash\necho "${tag}" >&2\nexit 2\n`);
422
+ }
423
+ return root;
424
+ };
425
+ /** Plant `.claude/worktrees/<name>/` debris — a linked worktree with its own guard. */
426
+ const plantDebris = (root, name, tag) => {
427
+ const nested = join(root, '.claude', 'worktrees', name);
428
+ mkdirSync(join(nested, '.claude', 'hooks'), { recursive: true });
429
+ writeFileSync(join(nested, '.git'), `gitdir: ${root}/.git/worktrees/${name}\n`);
430
+ writeFileSync(join(nested, '.claude', 'hooks', GUARD), `#!/bin/bash\necho "${tag}" >&2\nexit 2\n`);
431
+ mkdirSync(join(nested, 'src'), { recursive: true });
432
+ return nested;
433
+ };
434
+ afterEach(() => {
435
+ while (trees.length) {
436
+ const d = trees.pop();
437
+ if (d && existsSync(d))
438
+ rmSync(d, { recursive: true, force: true });
439
+ }
440
+ });
441
+ it('the canonical guard runs, not the nested shadow (the SF-27 defect)', () => {
442
+ // 16 such nested checkouts were measured in the main repo on 2026-08-01.
443
+ const repo = makeRepo('dir', 'CANONICAL-RAN');
444
+ const nested = plantDebris(repo, 'agent-X', 'SHADOW-RAN');
445
+ const { status, stderr } = runHook(join(nested, 'src'));
446
+ expect(stderr).toContain('CANONICAL-RAN');
447
+ expect(stderr).not.toContain('SHADOW-RAN');
448
+ expect(status).toBe(2);
449
+ });
450
+ it('skips the debris even when it is the only .claude/hooks in the chain — refuses', () => {
451
+ // Nothing canonical above it: the shadow must not become the fallback. A stale
452
+ // guard is not a safe substitute for no guard; refusing is.
453
+ const repo = makeRepo('dir', null);
454
+ const nested = plantDebris(repo, 'agent-Y', 'SHADOW-RAN');
455
+ const { status, stderr } = runHook(join(nested, 'src'));
456
+ expect(status).toBe(2);
457
+ expect(stderr).toContain('BLOCKED');
458
+ expect(stderr).not.toContain('SHADOW-RAN');
459
+ });
460
+ it('resolves in a legitimate linked worktree, where .git is a FILE not a directory', () => {
461
+ // `-d` instead of `-e` would break every linked worktree in this repo.
462
+ const repo = makeRepo('file', 'LINKED-RAN');
463
+ mkdirSync(join(repo, 'a', 'b'), { recursive: true });
464
+ const { stderr } = runHook(join(repo, 'a', 'b'));
465
+ expect(stderr).toContain('LINKED-RAN');
466
+ });
467
+ it('resolves in a main checkout, where .git is a directory', () => {
468
+ const repo = makeRepo('dir', 'MAIN-RAN');
469
+ mkdirSync(join(repo, 'a', 'b'), { recursive: true });
470
+ expect(runHook(join(repo, 'a', 'b')).stderr).toContain('MAIN-RAN');
471
+ });
472
+ it('refuses in a directory tree that is not a repository at all', () => {
473
+ // `.claude/hooks/` present but no `.git`: not a checkout root, so not a boundary.
474
+ const loose = makeRepo('none', 'LOOSE-RAN');
475
+ mkdirSync(join(loose, 'a'), { recursive: true });
476
+ const { status, stderr } = runHook(join(loose, 'a'));
477
+ expect(status).toBe(2);
478
+ expect(stderr).not.toContain('LOOSE-RAN');
479
+ });
480
+ it('does not escape upward past a checkout that has no guard deployed (the quiet widening)', () => {
481
+ // Issue (b) in #4852: an inner checkout with hooks undeployed borrowed the parent
482
+ // repository's guard. The boundary ends the walk at the inner root, guard or not.
483
+ const outer = makeRepo('dir', 'PARENT-RAN');
484
+ const inner = join(outer, 'sub');
485
+ mkdirSync(join(inner, 'work'), { recursive: true });
486
+ writeFileSync(join(inner, '.git'), 'gitdir: /elsewhere/.git/worktrees/sub\n');
487
+ const { status, stderr } = runHook(join(inner, 'work'));
488
+ expect(status).toBe(2);
489
+ expect(stderr).toContain('BLOCKED');
490
+ expect(stderr).not.toContain('PARENT-RAN');
491
+ });
492
+ it('starts the walk at the PHYSICAL cwd, so a symlinked PWD cannot hide the debris (SF-1)', () => {
493
+ // The segment skip is a lexical test on the path string. `$PWD` is inherited and
494
+ // holds the LOGICAL path — bash keeps it across a symlinked cwd — so a cwd reached
495
+ // through an alias whose logical path omits `.claude/worktrees/` passed the skip
496
+ // and the debris guard ran. `pwd -P` resolves via getcwd instead.
497
+ //
498
+ // MUTATION: revert `d="$(pwd -P)"` to `d="$PWD"` and this test fails with
499
+ // SHADOW-RAN. It is the only test in this file that pins the physical resolution.
500
+ const repo = makeRepo('dir', 'CANONICAL-RAN');
501
+ const nested = plantDebris(repo, 'agent-S', 'SHADOW-RAN');
502
+ const aliasRoot = realpathSync(mkdtempSync(join(tmpdir(), 'codex-alias-')));
503
+ trees.push(aliasRoot);
504
+ const alias = join(aliasRoot, 'link');
505
+ symlinkSync(nested, alias);
506
+ // The logical path holds no `.claude/worktrees/` segment; the physical one does.
507
+ expect(alias).not.toContain('.claude/worktrees/');
508
+ expect(realpathSync(alias)).toContain(join('.claude', 'worktrees'));
509
+ const { stderr } = runHook(alias, { PWD: alias });
510
+ expect(stderr).toContain('CANONICAL-RAN');
511
+ expect(stderr).not.toContain('SHADOW-RAN');
512
+ });
513
+ it('refuses an anchor that points into debris, rather than trusting it (SF-4)', () => {
514
+ // Anchor trust is otherwise intact — see the two tests below. But an anchor
515
+ // pointing INTO `.claude/worktrees/` is never legitimate: that tree is another
516
+ // checkout's business. Trusting it ran the stale shadow guard directly, with no
517
+ // walk involved and so no segment skip to catch it.
518
+ const repo = makeRepo('dir', 'CANONICAL-RAN');
519
+ const nested = plantDebris(repo, 'agent-A', 'SHADOW-RAN');
520
+ for (const key of ['CLAUDE_PROJECT_DIR', 'CLAUDE_WORKTREE_PATH']) {
521
+ const { status, stderr } = runHook(repo, { [key]: nested });
522
+ expect(stderr).not.toContain('SHADOW-RAN');
523
+ expect(stderr).toContain('BLOCKED');
524
+ expect(status).toBe(2);
525
+ }
526
+ });
527
+ it('refuses a BARE-RELATIVE anchor naming debris, which needs no leading slash (SF-9)', () => {
528
+ // `*/.claude/worktrees/*` requires a literal slash before `.claude`, so the
529
+ // relative spelling — resolved by the shell against the cwd — slipped past the
530
+ // SF-4 test and ran the shadow guard. Anchors come from the environment, which
531
+ // this code does not constrain, so both spellings must be covered.
532
+ //
533
+ // MUTATION: drop the `|.claude/worktrees/*` alternative and this test fails with
534
+ // SHADOW-RAN.
535
+ const repo = makeRepo('dir', 'CANONICAL-RAN');
536
+ plantDebris(repo, 'agent-X', 'SHADOW-RAN');
537
+ const relative = join('.claude', 'worktrees', 'agent-X');
538
+ expect(relative.startsWith('/')).toBe(false);
539
+ for (const key of ['CLAUDE_PROJECT_DIR', 'CLAUDE_WORKTREE_PATH']) {
540
+ // cwd is the repo root, so the relative anchor resolves onto the debris.
541
+ const { status, stderr } = runHook(repo, { [key]: relative });
542
+ expect(stderr).not.toContain('SHADOW-RAN');
543
+ expect(stderr).toContain('BLOCKED');
544
+ expect(status).toBe(2);
545
+ }
546
+ });
547
+ it('refuses an anchor that is a SYMLINK to debris, not just one spelled as debris', () => {
548
+ // The segment test is lexical, so it was applied to whatever string the
549
+ // environment supplied. A symlink to a debris directory carries no
550
+ // `.claude/worktrees/` segment in its own path, so it passed the pattern, and the
551
+ // guard-presence test then followed the link and ran the shadow. Same
552
+ // logical-vs-physical asymmetry SF-1 fixed for the walk, left behind on the anchor.
553
+ //
554
+ // MUTATION: drop `a="$(cd -P -- "$a" 2>/dev/null && pwd -P)"` and this fails with
555
+ // SHADOW-RAN.
556
+ const repo = makeRepo('dir', 'CANONICAL-RAN');
557
+ const nested = plantDebris(repo, 'agent-L', 'SHADOW-RAN');
558
+ const aliasRoot = realpathSync(mkdtempSync(join(tmpdir(), 'codex-anchor-')));
559
+ trees.push(aliasRoot);
560
+ const alias = join(aliasRoot, 'link');
561
+ symlinkSync(nested, alias);
562
+ expect(alias).not.toContain('.claude/worktrees/');
563
+ for (const key of ['CLAUDE_PROJECT_DIR', 'CLAUDE_WORKTREE_PATH']) {
564
+ const { status, stderr } = runHook(repo, { [key]: alias });
565
+ expect(stderr).not.toContain('SHADOW-RAN');
566
+ expect(stderr).toContain('BLOCKED');
567
+ expect(status).toBe(2);
568
+ }
569
+ });
570
+ it('an anchor naming a nonexistent directory REFUSES, and does not fall through to the walk', () => {
571
+ // Pins the ordering, not just the outcome. `[ -n "$a" ]` runs on the RAW anchor,
572
+ // before normalisation. Normalising first would turn an unresolvable anchor into
573
+ // the empty string, fail that test, and start the walk — converting a fail-closed
574
+ // refusal into a search. The canonical guard sits at the cwd here, so a
575
+ // fall-through would be visible as CANONICAL-RAN.
576
+ const repo = makeRepo('dir', 'CANONICAL-RAN');
577
+ for (const key of ['CLAUDE_PROJECT_DIR', 'CLAUDE_WORKTREE_PATH']) {
578
+ const { status, stderr } = runHook(repo, { [key]: join(repo, 'no-such-dir') });
579
+ expect(stderr).toContain('BLOCKED');
580
+ expect(stderr).not.toContain('CANONICAL-RAN');
581
+ expect(status).toBe(2);
582
+ }
583
+ });
584
+ it('a trusted anchor short-circuits the walk entirely, boundary or not', () => {
585
+ // CLAUDE_PROJECT_DIR / CLAUDE_WORKTREE_PATH are set by code that already knows the
586
+ // answer. They are checked once, with no `.git` requirement and no walk.
587
+ const anchor = makeRepo('none', 'ANCHOR-RAN');
588
+ const other = makeRepo('dir', 'CANONICAL-RAN');
589
+ mkdirSync(join(other, 'deep'), { recursive: true });
590
+ expect(runHook(join(other, 'deep'), { CLAUDE_PROJECT_DIR: anchor }).stderr).toContain('ANCHOR-RAN');
591
+ expect(runHook(join(other, 'deep'), { CLAUDE_WORKTREE_PATH: anchor }).stderr).toContain('ANCHOR-RAN');
592
+ });
593
+ it('an anchor without the guard refuses instead of falling back to the walk', () => {
594
+ // The anchor is an assertion about where the guard lives. If it is wrong, the
595
+ // right answer is to say so, not to search for a guard somewhere else.
596
+ const anchor = makeRepo('dir', null);
597
+ const other = makeRepo('dir', 'CANONICAL-RAN');
598
+ mkdirSync(join(other, 'deep'), { recursive: true });
599
+ const { status, stderr } = runHook(join(other, 'deep'), { CLAUDE_PROJECT_DIR: anchor });
600
+ expect(status).toBe(2);
601
+ expect(stderr).toContain('BLOCKED');
602
+ expect(stderr).not.toContain('CANONICAL-RAN');
603
+ });
604
+ it('still terminates at / rather than looping, with no anchor and no repository', () => {
605
+ const { status } = runHook('/');
606
+ expect(status).toBe(2);
607
+ });
608
+ it('the refusal explains the boundary, so the failure is diagnosable', () => {
609
+ const repo = makeRepo('dir', null);
610
+ const nested = plantDebris(repo, 'agent-Z', 'SHADOW-RAN');
611
+ const { stderr } = runHook(join(nested, 'src'));
612
+ expect(stderr).toContain('.claude/worktrees/');
613
+ expect(stderr).toMatch(/repository root/);
614
+ expect(stderr).toMatch(/fail closed|Refusing the command/);
615
+ });
616
+ it('the debris segment matches DEST_DEBRIS_DIR in generate-claude.mjs, so a rename breaks a test (SF-3)', () => {
617
+ // Two files now encode the same fact about Claude Code: agent worktrees are parked
618
+ // at `.claude/worktrees/`. generate-claude.mjs skips that subtree when scanning,
619
+ // this wrapper refuses to resolve a guard inside it. If Claude Code renames the
620
+ // directory and only the generator is updated, SF-27 reopens silently — the walk
621
+ // would resolve into debris again with every test here still green.
622
+ //
623
+ // DEST_DEBRIS_DIR is a module-private const, so it is read as text rather than
624
+ // imported. A read that finds nothing fails loudly instead of asserting vacuously.
625
+ const generator = join(import.meta.dirname, '..', '..', 'scripts', 'generate-claude.mjs');
626
+ const source = readFileSync(generator, 'utf-8');
627
+ const match = /^const DEST_DEBRIS_DIR = '([^']+)';$/m.exec(source);
628
+ expect(match, `DEST_DEBRIS_DIR not found in ${generator}`).not.toBeNull();
629
+ const debrisDir = match[1];
630
+ expect(debrisDir).toBe('worktrees');
631
+ for (const guard of PHASE1_PORTED_GUARDS) {
632
+ expect(codexHookCommand(guard)).toContain(`.claude/${debrisDir}/`);
633
+ }
634
+ });
635
+ // ── S4 invariants: the bound must not have cost the path-free, byte-identical body ──
636
+ it('keeps exactly one single-quoted region and no apostrophes (S4)', () => {
637
+ for (const guard of PHASE1_PORTED_GUARDS) {
638
+ const cmd = codexHookCommand(guard);
639
+ // Two apostrophes total: the ones opening and closing `bash -c '…'`.
640
+ expect(cmd.split("'").length - 1).toBe(2);
641
+ const body = cmd.slice(cmd.indexOf("'") + 1, cmd.lastIndexOf("'"));
642
+ expect(body).not.toContain("'");
643
+ }
644
+ });
645
+ it('embeds no filesystem path, so the body is byte-identical in every worktree (S4)', () => {
646
+ // Hook trust is keyed on sha256(hooks.json). One interpolated path would give each
647
+ // worktree its own hash and therefore its own human trust grant.
648
+ const a = buildCodexHooksJson({ worktreePath: '/workspace' });
649
+ const b = buildCodexHooksJson({ worktreePath: "/tmp/harry's-repo/.claude/worktrees/agent-1" });
650
+ expect(a).toBe(b);
651
+ for (const guard of PHASE1_PORTED_GUARDS) {
652
+ expect(codexHookCommand(guard)).not.toMatch(/\/tmp|\/workspace|harry/);
653
+ }
654
+ });
655
+ });
362
656
  /**
363
657
  * #4859 security review SF-1: the spawn gate must fail closed when ITS OWN binary
364
658
  * cannot be resolved.
@@ -455,12 +749,104 @@ describe('codexHookTrustPreconditions — the guards are inert until trust exist
455
749
  expect(results.map((r) => r.id).sort()).toEqual(['hook-trust', 'project-trust']);
456
750
  expect(results.every((r) => !r.satisfied)).toBe(true);
457
751
  });
458
- it('detects a persisted hook-trust record', () => {
459
- const codexHome = join(worktree, 'fake-codex-home');
460
- mkdirSync(codexHome, { recursive: true });
461
- writeFileSync(join(codexHome, 'config.toml'), '[hooks.state."abc"]\nenabled = true\ntrusted_hash = "deadbeef"\n');
462
- const trust = codexHookTrustPreconditions({ worktreePath: worktree, codexHome }).find((r) => r.id === 'hook-trust');
463
- expect(trust?.satisfied).toBe(true);
752
+ /**
753
+ * ─── #4864 / SF-2 (KI-CODEX-TRUST-PRECONDITION-ANY-NOT-ALL) ──────────────────
754
+ *
755
+ * The predicate used to be `sections.some(record has enabled + hash)` — path-agnostic
756
+ * and entry-agnostic. So a grant for `/workspace/.codex/hooks.json` reported hook
757
+ * trust SATISFIED for a team worktree whose own hooks.json had ZERO records and whose
758
+ * hooks were therefore silently inert. That is the same false green as #4849: the
759
+ * banner said the guards were live while nothing was enforcing.
760
+ *
761
+ * These tests pin the replacement: the required keys are derived from the DEPLOYED
762
+ * document, prefixed with THIS worktree's hooks path, and EVERY one of them needs a
763
+ * usable record.
764
+ *
765
+ * MUTATION CHECK: replacing the per-key `every` with the old `sections.some(...)`
766
+ * makes 'a grant for another path is not a grant for this worktree' and
767
+ * 'one ungranted entry is enough to fail' both fail.
768
+ */
769
+ describe('hook trust is PER ENTRY and PATH-AWARE (#4864, SF-2)', () => {
770
+ const codexHomeFor = (body) => {
771
+ const codexHome = join(worktree, 'fake-codex-home');
772
+ mkdirSync(codexHome, { recursive: true });
773
+ writeFileSync(join(codexHome, 'config.toml'), body);
774
+ return codexHome;
775
+ };
776
+ const deployHooks = () => {
777
+ mkdirSync(join(worktree, '.codex'), { recursive: true });
778
+ writeFileSync(join(worktree, CODEX_HOOKS_FILENAME), buildCodexHooksJson({ worktreePath: worktree }));
779
+ };
780
+ const keys = () => codexHookTrustKeysForDoc(join(worktree, CODEX_HOOKS_FILENAME), readDeployedHooksDoc(worktree));
781
+ const grantAll = () => keys().map((k) => `[hooks.state."${k}"]\nenabled = true\ntrusted_hash = "sha256:aa"\n`).join('\n');
782
+ const satisfied = (codexHome) => codexHookTrustPreconditions({ worktreePath: worktree, codexHome }).find((r) => r.id === 'hook-trust')
783
+ ?.satisfied ?? false;
784
+ it('derives one key per hook entry, in the generator\'s own group order', () => {
785
+ deployHooks();
786
+ const hooksPath = join(worktree, CODEX_HOOKS_FILENAME);
787
+ // Three PreToolUse entries (two guards, then the appended spawn gate) and one
788
+ // SubagentStart entry. The key format is Codex's own, read off a real
789
+ // ~/.codex/config.toml: <path>:<snake_case event>:<group>:<hook>.
790
+ expect(keys()).toEqual([
791
+ `${hooksPath}:pre_tool_use:0:0`,
792
+ `${hooksPath}:pre_tool_use:1:0`,
793
+ `${hooksPath}:pre_tool_use:2:0`,
794
+ `${hooksPath}:subagent_start:0:0`,
795
+ ]);
796
+ });
797
+ it('is SATISFIED only when every entry has an enabled record with a hash', () => {
798
+ deployHooks();
799
+ expect(satisfied(codexHomeFor(grantAll()))).toBe(true);
800
+ });
801
+ it('a grant for another path is not a grant for this worktree (the false green)', () => {
802
+ deployHooks();
803
+ const foreign = grantAll().replaceAll(join(worktree, CODEX_HOOKS_FILENAME), '/workspace/.codex/hooks.json');
804
+ const codexHome = codexHomeFor(foreign);
805
+ expect(satisfied(codexHome)).toBe(false);
806
+ const detail = codexHookTrustPreconditions({ worktreePath: worktree, codexHome }).find((r) => r.id === 'hook-trust')?.detail;
807
+ // It names the ungranted ENTRIES, not a vague "hooks are untrusted".
808
+ expect(detail).toContain('4 of 4 entries have NO usable trust record');
809
+ expect(detail).toContain(`${join(worktree, CODEX_HOOKS_FILENAME)}:pre_tool_use:0:0`);
810
+ });
811
+ it('one ungranted entry is enough to fail — ANY is not ALL', () => {
812
+ deployHooks();
813
+ const all = keys();
814
+ const partial = all
815
+ .slice(0, all.length - 1)
816
+ .map((k) => `[hooks.state."${k}"]\nenabled = true\ntrusted_hash = "sha256:aa"\n`)
817
+ .join('\n');
818
+ const codexHome = codexHomeFor(partial);
819
+ expect(satisfied(codexHome)).toBe(false);
820
+ expect(codexHookTrustPreconditions({ worktreePath: worktree, codexHome }).find((r) => r.id === 'hook-trust')?.detail).toContain('1 of 4 entries');
821
+ });
822
+ it.each([
823
+ ['a disabled record', 'enabled = false\ntrusted_hash = "sha256:aa"'],
824
+ ['a record with an empty hash', 'enabled = true\ntrusted_hash = ""'],
825
+ ['a record with no hash at all', 'enabled = true'],
826
+ ])('%s does not count as granted', (_label, body) => {
827
+ deployHooks();
828
+ const all = keys();
829
+ const text = all
830
+ .map((k, i) => i === 0
831
+ ? `[hooks.state."${k}"]\n${body}\n`
832
+ : `[hooks.state."${k}"]\nenabled = true\ntrusted_hash = "sha256:aa"\n`)
833
+ .join('\n');
834
+ expect(satisfied(codexHomeFor(text))).toBe(false);
835
+ });
836
+ it('NO deployed hooks.json is unmet, not vacuously satisfied', () => {
837
+ // An empty required-key set must never read as "all keys granted".
838
+ expect(satisfied(codexHomeFor('model = "gpt-5.5"\n'))).toBe(false);
839
+ mkdirSync(join(worktree, '.codex'), { recursive: true });
840
+ writeFileSync(join(worktree, CODEX_HOOKS_FILENAME), '{"hooks":{}}');
841
+ expect(satisfied(codexHomeFor(''))).toBe(false);
842
+ });
843
+ it('an unparseable hooks.json is unmet, and says so', () => {
844
+ mkdirSync(join(worktree, '.codex'), { recursive: true });
845
+ writeFileSync(join(worktree, CODEX_HOOKS_FILENAME), 'not json');
846
+ const codexHome = codexHomeFor('');
847
+ expect(satisfied(codexHome)).toBe(false);
848
+ expect(codexHookTrustPreconditions({ worktreePath: worktree, codexHome }).find((r) => r.id === 'hook-trust')?.detail).toContain('No readable');
849
+ });
464
850
  });
465
851
  // ── NEW-12: the predicate reads the VALUE, not the presence of a header ──────
466
852
  describe('project trust reads trust_level, not the section header (NEW-12)', () => {
@@ -506,10 +892,22 @@ describe('codexHookTrustPreconditions — the guards are inert until trust exist
506
892
  });
507
893
  // ── NEW-13: same defect, same fix, on the hook-trust predicate ───────────────
508
894
  describe('hook trust reads the record, not a mention of it (NEW-13)', () => {
895
+ // KEY is substituted for the placeholder `abc` (#4864): records are now looked up
896
+ // by the entry keys of THIS worktree's deployed hooks.json, so the value semantics
897
+ // this table pins have to be exercised on a key that is actually required. Every
898
+ // OTHER required entry gets a full grant, so the table still varies exactly one
899
+ // record and the result still turns on that record alone.
509
900
  function hookTrust(configBody) {
901
+ mkdirSync(join(worktree, '.codex'), { recursive: true });
902
+ writeFileSync(join(worktree, CODEX_HOOKS_FILENAME), buildCodexHooksJson({ worktreePath: worktree }));
903
+ const allKeys = codexHookTrustKeysForDoc(join(worktree, CODEX_HOOKS_FILENAME), readDeployedHooksDoc(worktree));
904
+ const [key, ...rest] = allKeys;
905
+ const others = rest
906
+ .map((k) => `[hooks.state."${k}"]\nenabled = true\ntrusted_hash = "sha256:aa"\n`)
907
+ .join('\n');
510
908
  const codexHome = join(worktree, 'fake-codex-home');
511
909
  mkdirSync(codexHome, { recursive: true });
512
- writeFileSync(join(codexHome, 'config.toml'), configBody);
910
+ writeFileSync(join(codexHome, 'config.toml'), `${configBody.replaceAll('abc', key)}\n${others}`);
513
911
  return (codexHookTrustPreconditions({ worktreePath: worktree, codexHome }).find((r) => r.id === 'hook-trust')?.satisfied ?? false);
514
912
  }
515
913
  it.each([
@@ -727,10 +1125,27 @@ describe('deployCodexConfig — idempotent artifact deployment', () => {
727
1125
  it('warns when there is no canonical AGENTS.md to fold into the override', () => {
728
1126
  expect(deployCodexConfig(opts()).warnings.join('\n')).toMatch(/this session gets isolation context and behavioral markers but NO canonical instructions/);
729
1127
  });
730
- it('threads provenGuards through to the SubagentStart gate', () => {
731
- deployCodexConfig({ ...opts(), provenGuards: ['git-mutation-guard'] });
732
- const doc = JSON.parse(readFileSync(join(worktree, CODEX_HOOKS_FILENAME), 'utf-8'));
733
- expect(doc.hooks.SubagentStart[0].hooks[0].command).toContain('--proven-guards git-mutation-guard');
1128
+ /**
1129
+ * REPLACES 'threads provenGuards through to the SubagentStart gate' (#4864).
1130
+ *
1131
+ * That behaviour is now a defect, not a feature. Hook trust is keyed per entry and
1132
+ * bound to the entry's bytes, and the G-7 proof artifact is bound to the sha256 of
1133
+ * the whole file. If the deployed hooks.json carried the proven-guard list, then the
1134
+ * first launch after the guards were proven would write DIFFERENT bytes than the
1135
+ * human granted trust for — every entry untrusted, every guard inert, which is the
1136
+ * #4849 state reached by succeeding at G-7 — and the proof would be stale against
1137
+ * its own consequence, oscillating forever.
1138
+ *
1139
+ * MUTATION CHECK: restoring the `provenGuards` forwarding in deployCodexConfig makes
1140
+ * this fail.
1141
+ */
1142
+ it('NEVER writes a proven-guard list into the deployed hooks.json — the bytes are fixed', () => {
1143
+ deployCodexConfig(opts());
1144
+ const text = readFileSync(join(worktree, CODEX_HOOKS_FILENAME), 'utf-8');
1145
+ expect(text).not.toContain('--proven-guards');
1146
+ // Byte-identical to the no-argument generator: the file is the same in every
1147
+ // worktree, so one human trust grant covers the fleet.
1148
+ expect(text).toBe(buildCodexHooksJson({ worktreePath: worktree }));
734
1149
  });
735
1150
  });
736
1151
  /**