@holmes-lab/holmes-kit 0.40.0 → 0.41.0

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 (119) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/README.md +79 -5
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-context.js +4 -3
  5. package/dist/holmes/cli/approve.js +22 -12
  6. package/dist/holmes/cli/autonomy.d.ts +21 -0
  7. package/dist/holmes/cli/autonomy.js +35 -5
  8. package/dist/holmes/cli/doctor.js +58 -6
  9. package/dist/holmes/cli/index.js +394 -267
  10. package/dist/holmes/cli/init.js +17 -6
  11. package/dist/holmes/cli/interactive-prompt.d.ts +39 -2
  12. package/dist/holmes/cli/interactive-prompt.js +98 -16
  13. package/dist/holmes/cli/ledger-witness.d.ts +61 -0
  14. package/dist/holmes/cli/ledger-witness.js +212 -0
  15. package/dist/holmes/cli/playbook-skills.d.ts +3 -56
  16. package/dist/holmes/cli/playbook-skills.js +26 -349
  17. package/dist/holmes/config/config.d.ts +21 -0
  18. package/dist/holmes/config/config.js +22 -3
  19. package/dist/holmes/governance/approval-queue.d.ts +65 -1
  20. package/dist/holmes/governance/approval-queue.js +279 -9
  21. package/dist/holmes/governance/autonomous-shell.d.ts +13 -1
  22. package/dist/holmes/governance/autonomous-shell.js +157 -4
  23. package/dist/holmes/governance/autonomy.d.ts +216 -0
  24. package/dist/holmes/governance/autonomy.js +1162 -10
  25. package/dist/holmes/governance/install-manifest.d.ts +7 -4
  26. package/dist/holmes/governance/install-manifest.js +144 -14
  27. package/dist/holmes/governance/ledger-witness.d.ts +63 -0
  28. package/dist/holmes/governance/ledger-witness.js +296 -0
  29. package/dist/holmes/governance/provenance-chain.d.ts +8 -1
  30. package/dist/holmes/governance/provenance-chain.js +23 -4
  31. package/dist/holmes/governance/push-gate-runner.d.ts +2 -0
  32. package/dist/holmes/governance/push-gate-runner.js +40 -3
  33. package/dist/holmes/governance/push-gate.d.ts +13 -2
  34. package/dist/holmes/governance/push-gate.js +106 -14
  35. package/dist/holmes/governance/recorded-pairs.d.ts +4 -0
  36. package/dist/holmes/governance/recorded-pairs.js +25 -1
  37. package/dist/holmes/governance/session-context.d.ts +7 -0
  38. package/dist/holmes/governance/session-context.js +34 -6
  39. package/dist/holmes/guardrail/advisory-line.d.ts +102 -0
  40. package/dist/holmes/guardrail/advisory-line.js +718 -0
  41. package/dist/holmes/guardrail/anchor-scope-text.d.ts +9 -0
  42. package/dist/holmes/guardrail/anchor-scope-text.js +7 -0
  43. package/dist/holmes/guardrail/command-traits.d.ts +102 -0
  44. package/dist/holmes/guardrail/command-traits.js +379 -0
  45. package/dist/holmes/guardrail/fixtures/manager-builtins.json +23 -0
  46. package/dist/holmes/guardrail/fixtures/npm-commands.json +7 -0
  47. package/dist/holmes/guardrail/impact-gate.d.ts +6 -0
  48. package/dist/holmes/guardrail/impact-gate.js +32 -5
  49. package/dist/holmes/guardrail/outward-acts.d.ts +47 -0
  50. package/dist/holmes/guardrail/outward-acts.js +1102 -0
  51. package/dist/holmes/guardrail/refusal-codes.js +8 -1
  52. package/dist/holmes/guardrail/refusal-templates.d.ts +15 -0
  53. package/dist/holmes/guardrail/refusal-templates.js +71 -0
  54. package/dist/holmes/guardrail/risk-classifier.d.ts +22 -6
  55. package/dist/holmes/guardrail/risk-classifier.js +12 -118
  56. package/dist/holmes/guardrail/shell-lexer.d.ts +69 -0
  57. package/dist/holmes/guardrail/shell-lexer.js +567 -0
  58. package/dist/holmes/guardrail/write-target.js +7 -1
  59. package/dist/holmes/hooks/pre-tool-use.d.ts +71 -0
  60. package/dist/holmes/hooks/pre-tool-use.js +1466 -14
  61. package/dist/holmes/hooks/session-start.js +27 -1
  62. package/dist/holmes/hooks/stop.d.ts +7 -0
  63. package/dist/holmes/hooks/stop.js +39 -2
  64. package/dist/holmes/mcp/elicit-approval.d.ts +0 -21
  65. package/dist/holmes/mcp/elicit-approval.js +5 -2
  66. package/dist/holmes/mcp/handlers/approval-ask.js +3 -2
  67. package/dist/holmes/mcp/handlers/entity-integration.d.ts +1 -1
  68. package/dist/holmes/mcp/handlers/entity-integration.js +9 -6
  69. package/dist/holmes/mcp/handlers/entity-renumber.js +2 -1
  70. package/dist/holmes/mcp/handlers/entity-store.js +7 -2
  71. package/dist/holmes/mcp/handlers/maintenance-analysis.d.ts +13 -0
  72. package/dist/holmes/mcp/handlers/maintenance-analysis.js +59 -2
  73. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -0
  74. package/dist/holmes/mcp/handlers/operator-inspection.js +25 -4
  75. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -1
  76. package/dist/holmes/mcp/handlers/spec-approval.js +28 -10
  77. package/dist/holmes/mcp/handlers/spec-lifecycle.js +10 -7
  78. package/dist/holmes/mcp/handlers/test-execution.d.ts +470 -3
  79. package/dist/holmes/mcp/handlers/test-execution.js +201 -21
  80. package/dist/holmes/mcp/handlers.d.ts +473 -8
  81. package/dist/holmes/mcp/handlers.js +6 -1
  82. package/dist/holmes/mcp/maintenance-analyze.d.ts +5 -0
  83. package/dist/holmes/mcp/maintenance-analyze.js +4 -2
  84. package/dist/holmes/mcp/maintenance-evidence.d.ts +9 -0
  85. package/dist/holmes/mcp/maintenance-evidence.js +4 -1
  86. package/dist/holmes/mcp/tool-schemas.js +16 -10
  87. package/dist/holmes/project/baseline.d.ts +15 -2
  88. package/dist/holmes/project/baseline.js +11 -6
  89. package/dist/holmes/project/bounded-io.d.ts +1 -0
  90. package/dist/holmes/project/bounded-io.js +4 -2
  91. package/dist/holmes/project/change-source.d.ts +4 -0
  92. package/dist/holmes/project/change-source.js +13 -5
  93. package/dist/holmes/project/playbook-reference.d.ts +50 -0
  94. package/dist/holmes/project/playbook-reference.js +259 -0
  95. package/dist/holmes/project/playbook-skill-states.d.ts +94 -0
  96. package/dist/holmes/project/playbook-skill-states.js +396 -0
  97. package/dist/holmes/project/root.d.ts +9 -1
  98. package/dist/holmes/project/root.js +26 -3
  99. package/dist/holmes/project/running-package.d.ts +15 -0
  100. package/dist/holmes/project/running-package.js +87 -0
  101. package/dist/holmes/review/evidence-mode.d.ts +21 -0
  102. package/dist/holmes/review/evidence-mode.js +33 -0
  103. package/dist/holmes/review/head-worktree.d.ts +55 -0
  104. package/dist/holmes/review/head-worktree.js +329 -0
  105. package/dist/holmes/review/mrp.js +13 -3
  106. package/dist/holmes/review/run-provenance.d.ts +45 -0
  107. package/dist/holmes/review/run-provenance.js +314 -0
  108. package/dist/holmes/review/test-evidence.d.ts +174 -0
  109. package/dist/holmes/review/test-evidence.js +330 -2
  110. package/dist/holmes/review/test-reports.d.ts +94 -0
  111. package/dist/holmes/review/test-reports.js +382 -0
  112. package/dist/holmes/review/test-runner.d.ts +178 -65
  113. package/dist/holmes/review/test-runner.js +551 -319
  114. package/dist/holmes/review/test-units.d.ts +159 -0
  115. package/dist/holmes/review/test-units.js +814 -0
  116. package/dist/holmes/spec/entity-integration-transaction.d.ts +19 -2
  117. package/dist/holmes/spec/entity-integration-transaction.js +68 -7
  118. package/package.json +5 -2
  119. package/playbooks/publish/PLAYBOOK.md +2 -1
@@ -38,6 +38,13 @@ exports.resolveRmSignals = resolveRmSignals;
38
38
  exports.resolveStagedStore = resolveStagedStore;
39
39
  exports.readApprovalFromEnv = readApprovalFromEnv;
40
40
  exports.sedInPlaceFiles = sedInPlaceFiles;
41
+ exports.gitStoreWrites = gitStoreWrites;
42
+ exports.referenceInputWrite = referenceInputWrite;
43
+ exports.referenceInputJudge = referenceInputJudge;
44
+ exports.governedCliAct = governedCliAct;
45
+ exports.commitOrBuildOf = commitOrBuildOf;
46
+ exports.gitHiddenWriteOf = gitHiddenWriteOf;
47
+ exports.runsAutonomyWidening = runsAutonomyWidening;
41
48
  exports.lockRecoverAct = lockRecoverAct;
42
49
  exports.lockRecoverAdvisory = lockRecoverAdvisory;
43
50
  exports.hookOutputFor = hookOutputFor;
@@ -62,7 +69,7 @@ exports.settleOnMainThread = settleOnMainThread;
62
69
  exports.auditApprovalFor = auditApprovalFor;
63
70
  exports.evaluateHook = evaluateHook;
64
71
  exports.readSpecsSync = readSpecsSync;
65
- // @implements A-SPEC-794.57, A-SPEC-794.55, A-SPEC-794.54, A-SPEC-794.53, A-SPEC-794.52, A-SPEC-794.49, A-SPEC-222.12, A-SPEC-222.13, A-SPEC-476.7, A-SPEC-226.3, A-SPEC-774.28, A-SPEC-747.4, A-SPEC-747.7, A-SPEC-774.23, A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1, A-SPEC-747.3, A-SPEC-774.26, A-SPEC-163.8, A-SPEC-790, A-SPEC-790.2, A-SPEC-790.7, A-SPEC-790.8, A-SPEC-792.5, A-SPEC-245.9, A-SPEC-245.15, A-SPEC-245.17
72
+ // @implements A-SPEC-794.113, A-SPEC-794.97, A-SPEC-794.96, A-SPEC-794.95, A-SPEC-794.91, A-SPEC-794.89, A-SPEC-794.87, A-SPEC-794.86, A-SPEC-794.83, A-SPEC-794.82, A-SPEC-794.72, A-SPEC-794.71, A-SPEC-794.70,A-SPEC-794.69, A-SPEC-578.16, A-SPEC-794.68,A-SPEC-578.15, A-SPEC-333.9, A-SPEC-794.57, A-SPEC-794.55, A-SPEC-794.54, A-SPEC-794.53, A-SPEC-794.52, A-SPEC-794.49, A-SPEC-222.12, A-SPEC-222.13, A-SPEC-476.7, A-SPEC-226.3, A-SPEC-774.28, A-SPEC-747.4, A-SPEC-747.7, A-SPEC-774.23, A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1, A-SPEC-747.3, A-SPEC-774.26, A-SPEC-163.8, A-SPEC-790, A-SPEC-790.2, A-SPEC-790.7, A-SPEC-790.8, A-SPEC-792.5, A-SPEC-245.9, A-SPEC-245.15, A-SPEC-245.17
66
73
  const powershell_shell_1 = require("../guardrail/powershell-shell");
67
74
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
68
75
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
@@ -94,7 +101,10 @@ const agent_launch_policy_1 = require("../guardrail/agent-launch-policy");
94
101
  const line_continuation_1 = require("../guardrail/line-continuation");
95
102
  const unresolved_write_1 = require("../guardrail/unresolved-write");
96
103
  const risk_classifier_1 = require("../guardrail/risk-classifier");
104
+ const outward_acts_1 = require("../guardrail/outward-acts");
97
105
  const refusal_codes_1 = require("../guardrail/refusal-codes");
106
+ const anchor_scope_text_1 = require("../guardrail/anchor-scope-text");
107
+ const refusal_templates_1 = require("../guardrail/refusal-templates");
98
108
  const run_refusals_1 = require("../guardrail/run-refusals");
99
109
  const run_plan_scope_1 = require("../guardrail/run-plan-scope");
100
110
  const run_stages_1 = require("../guardrail/run-stages");
@@ -122,6 +132,8 @@ const linear_match_1 = require("../guardrail/linear-match");
122
132
  const approval_grants_1 = require("../governance/approval-grants");
123
133
  const approval_blockers_1 = require("../spec/approval-blockers");
124
134
  const impact_gate_1 = require("../guardrail/impact-gate");
135
+ const advisory_line_1 = require("../guardrail/advisory-line");
136
+ const heartbeat_1 = require("./heartbeat");
125
137
  const bounded_io_1 = require("../project/bounded-io");
126
138
  const flags_1 = require("../cli/flags"); // @implements A-SPEC-245.18 — the CLI's own flag reading, one source
127
139
  // Resolve per-rm-target git facts (H1 git-aware guardrail): is each recursive-rm target a
@@ -672,6 +684,1100 @@ function wrappedServerWord(normalized) {
672
684
  }
673
685
  return false;
674
686
  }
687
+ /**
688
+ * @implements A-SPEC-794.95 (A-M1) — the paths a git command writes from git's own store: `checkout [<tree>] [--] <paths>`
689
+ * and `restore [--source X] <paths>` (their path arguments), `apply <patch>` (the patch's `+++ b/` and `diff --git`
690
+ * targets), `stash pop|apply [<ref>]` (git's own list of the stash's files). Null when the command runs none of them;
691
+ * `unreadable` when a patch or a stash cannot be listed (the caller refuses in a repository with principle 7 paths).
692
+ */
693
+ function gitStoreWrites(command, root) {
694
+ if (!/\b(?:git|patch)\b/.test(command))
695
+ return null;
696
+ let lexed;
697
+ try {
698
+ lexed = require('../guardrail/shell-lexer').lexShell(command);
699
+ }
700
+ catch {
701
+ return 'unreadable';
702
+ }
703
+ const out = [];
704
+ let hit = false;
705
+ // A-SPEC-794.96 — fast feedback only (the working tree is judged at Stop, commit and build): git as the command word
706
+ // (not an argument of echo), no -C and no cd in the command (it may run outside the project), a checkout or restore
707
+ // from another tree (restoring from HEAD or the index is how an unopened change is undone), an apply that writes
708
+ // the working tree (not --check, --stat, --cached, --index)
709
+ if (lexed.clauses.some((c) => c.words[0]?.value === 'cd'))
710
+ return null;
711
+ const patchTargets = (file) => {
712
+ try {
713
+ const text = fs.readFileSync(path.resolve(root, file), 'utf8');
714
+ return [...text.matchAll(/^(?:\+\+\+ (?:b\/)?(\S+)|diff --git a\/\S+ b\/(\S+))/gm)].map((m) => m[1] ?? m[2]).filter((t) => t !== '/dev/null');
715
+ }
716
+ catch {
717
+ return null;
718
+ }
719
+ };
720
+ for (const c of lexed.clauses) {
721
+ const w = c.words.map((x) => x.value);
722
+ // A-SPEC-794.97 (M4) — `patch` writes what its patch names, as git apply does: read from -i or from stdin's file
723
+ if ((w[0] ?? '').split('/').pop() === 'patch') {
724
+ hit = true;
725
+ const k = w.findIndex((a) => a === '-i' || a === '--input');
726
+ const src = k >= 0 ? w[k + 1] : w.find((a) => a.startsWith('--input='))?.slice('--input='.length)
727
+ ?? c.redirects.find((r) => r.op === '<')?.target?.value;
728
+ if (!src)
729
+ return 'unreadable';
730
+ const t = patchTargets(src);
731
+ if (t === null)
732
+ return 'unreadable';
733
+ out.push(...t);
734
+ continue;
735
+ }
736
+ if (!(w[0] === 'git' || (w[0] ?? '').endsWith('/git')))
737
+ continue;
738
+ let i = 1;
739
+ let elsewhere = false;
740
+ while (i < w.length && w[i].startsWith('-')) {
741
+ if (w[i] === '-C' || w[i].startsWith('--git-dir') || w[i].startsWith('--work-tree'))
742
+ elsewhere = true;
743
+ i += (w[i] === '-C' || w[i] === '-c') ? 2 : 1;
744
+ }
745
+ if (elsewhere)
746
+ continue;
747
+ const sub = w[i];
748
+ const rest = w.slice(i + 1);
749
+ if (sub === 'checkout' || sub === 'restore') {
750
+ const dd = rest.indexOf('--');
751
+ // A-SPEC-794.97 (B-H1) — restoring from HEAD or from a commit (the baseline the Stop text names) is a way out, not a
752
+ // write to judge; its result is judged at Stop, commit and build like any other
753
+ const restoring = (t) => t === 'HEAD' || /^[0-9a-f]{7,64}$/.test(t);
754
+ if (sub === 'checkout') {
755
+ const tree = (dd >= 0 ? rest.slice(0, dd) : []).filter((a) => !a.startsWith('-'));
756
+ if (dd < 0 || tree.length === 0 || tree.every(restoring))
757
+ continue; // a branch switch, or restoring from the index or HEAD
758
+ hit = true;
759
+ out.push(...rest.slice(dd + 1));
760
+ }
761
+ else {
762
+ const si = rest.findIndex((a) => a === '--source' || a === '-s' || a.startsWith('--source='));
763
+ if (si < 0)
764
+ continue; // restoring from the index or HEAD (--staged)
765
+ const source = rest[si].startsWith('--source=') ? rest[si].slice('--source='.length) : rest[si + 1] ?? '';
766
+ if (restoring(source))
767
+ continue;
768
+ hit = true;
769
+ const args = [];
770
+ for (let k = 0; k < rest.length; k++) {
771
+ if (rest[k] === '--source' || rest[k] === '-s') {
772
+ k++;
773
+ continue;
774
+ }
775
+ if (rest[k] !== '--' && !rest[k].startsWith('-'))
776
+ args.push(rest[k]);
777
+ }
778
+ out.push(...args);
779
+ }
780
+ }
781
+ else if (sub === 'apply') {
782
+ if (rest.some((a) => /^--(?:check|stat|numstat|summary|cached|index)$/.test(a)))
783
+ continue;
784
+ hit = true;
785
+ const files = rest.filter((a) => !a.startsWith('-'));
786
+ if (files.length === 0) {
787
+ const r = c.redirects.find((x) => x.op === '<')?.target?.value;
788
+ if (r)
789
+ files.push(r);
790
+ else
791
+ return 'unreadable';
792
+ }
793
+ for (const f of files) {
794
+ const t = patchTargets(f);
795
+ if (t === null)
796
+ return 'unreadable';
797
+ out.push(...t);
798
+ }
799
+ }
800
+ // A-SPEC-794.97 (L2) — stash pop|apply is left to the working-tree judgement (a push && pop round trip was read
801
+ // against the old stash@{0})
802
+ }
803
+ return hit ? out : null;
804
+ }
805
+ /**
806
+ * @implements A-SPEC-794.95 — the A-SPECs whose open person-seal window names `rel` (one judgement for the file tools
807
+ * and the git forms).
808
+ */
809
+ function principle7Openers(projectRoot, specs, nowTs, rel) {
810
+ // A-SPEC-794.96 — the one judgement lives in autonomy.ts (Stop, commit and build read it too)
811
+ return require('../governance/autonomy').principle7OpenersFor(projectRoot, specs, Date.parse(nowTs), rel);
812
+ }
813
+ /**
814
+ * @implements A-SPEC-794.95, A-SPEC-794.96 (M-3) — the write a window opened is recorded once per (file, spec, seal), by
815
+ * the file tools and the git forms alike; the gate judges before the act, so this records what a window opened.
816
+ */
817
+ function recordWindowWrite(projectRoot, nowTs, rel, opened) {
818
+ const opener = [...opened.openers].sort((a, b) => (a.ts < b.ts ? 1 : -1))[0];
819
+ if (!opener)
820
+ return;
821
+ const already = opened.events.some((e) => e.kind === 'principle7-window-write' && Array.isArray(e.inputs)
822
+ && e.inputs.includes(rel) && e.inputs.includes(opener.id) && e.inputs.includes(`seal:${opener.ts}`));
823
+ if (already)
824
+ return;
825
+ try {
826
+ new ledger_store_1.FileLedgerStore(path.join(projectRoot, '.ax', 'ledger')).append({ ts: nowTs, actor: 'holmes-kit', kind: 'principle7-window-write',
827
+ summary: `${rel} opened for writing by ${opener.id}'s window, sealed by ${opener.actor} at ${opener.ts}`,
828
+ inputs: [rel, opener.id, `seal:${opener.ts}`, `sealed-by:${opener.actor}`], rationale: 'principle 7 seal window' });
829
+ }
830
+ catch { /* the record is audit; the window judgement already stood */ }
831
+ }
832
+ /**
833
+ * @implements A-SPEC-794.113 — what the reference judgements read and the session has no business writing:
834
+ * - the repository's object store (`objects`, with `info/alternates` and the packs) and the `.git` entry itself — git's
835
+ * comparison of tree objects is what principle 7's working-tree judgement trusts, and nothing but git writes them
836
+ * (measured 2026-11-12: a copy, a move, an interpreter write and the Write tool there, `mv .git …` and `.git` replaced by
837
+ * a file were all allowed);
838
+ * - the files of the running package when it is deployed — its playbooks are the recovery skills' reference and its dist
839
+ * is the gate (review A, H-C: the playbooks were writable; measured while building this: a shell write to the dist was
840
+ * too, and so was the Write tool for a package outside the project).
841
+ * Judged where the write lands — the written path and its real path, so a link, `..`, a doubled slash and another case on
842
+ * a file system that folds case do not change the answer. Null when the path is none of these. The repository is the one
843
+ * the root is in (the nearest `.git` at or above it); for a linked worktree, the store of the repository it belongs to.
844
+ */
845
+ function referenceInputWrite(projectRoot, written) {
846
+ return referenceInputJudge(projectRoot)(written);
847
+ }
848
+ /**
849
+ * The judgement for one hook call: what is protected is found once, and a real path is looked up once per directory —
850
+ * a command naming one destination 20,000 times, or thousands of files of one directory, must not cost a file-system
851
+ * walk each (the hook's 2-second bound on a 120 KB command; measured 7.4 s before this).
852
+ */
853
+ function referenceInputJudge(projectRoot, home = os.homedir()) {
854
+ const reals = new Map();
855
+ /** The real path, or for a path that does not exist the real path of its directory with the name joined on. */
856
+ const realOrSelf = (p) => {
857
+ const known = reals.get(p);
858
+ if (known !== undefined)
859
+ return known;
860
+ let out = p;
861
+ try {
862
+ if (fs.existsSync(p))
863
+ out = fs.realpathSync.native(p);
864
+ else {
865
+ const up = path.dirname(p);
866
+ out = up === p ? p : path.join(realOrSelf(up), path.basename(p));
867
+ }
868
+ }
869
+ catch {
870
+ out = p;
871
+ } // [no-substitution: no real path can be had → the written path alone is judged, and it still is]
872
+ reals.set(p, out);
873
+ return out;
874
+ };
875
+ const within = (p, dir) => p === dir || p.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
876
+ const forms = (p) => [...new Set([p, realOrSelf(p)])];
877
+ let found = null;
878
+ const protectedPaths = () => {
879
+ if (found !== null)
880
+ return found;
881
+ // the runtime directory the launchers live in (runtime/dispatch.ts reads its registry there): the directory itself
882
+ // and everything under it. Another directory under ~/.holmes (scratch, models, the update check) is not this.
883
+ const out = { entries: [], stores: [], packageDirs: [], runtime: forms(path.join(home, '.holmes', 'runtime')) };
884
+ // the repository the root is in
885
+ for (let dir = path.resolve(projectRoot);;) {
886
+ const entry = path.join(dir, '.git');
887
+ let st = null;
888
+ try {
889
+ st = fs.lstatSync(entry);
890
+ }
891
+ catch {
892
+ st = null;
893
+ } // [no-substitution: no .git here → the parent is asked]
894
+ if (st !== null) {
895
+ // the entry itself: as written, and under the real path of the directory it sits in (the entry is compared as an
896
+ // entry — a linked worktree's `.git` is a file)
897
+ out.entries = [...new Set([entry, path.join(realOrSelf(dir), '.git')])];
898
+ let common = entry;
899
+ let own = entry; // this checkout's own git directory (a linked worktree's is under the common one)
900
+ if (st.isFile()) {
901
+ try {
902
+ const m = /^gitdir: (.+)$/m.exec(fs.readFileSync(entry, 'utf8'));
903
+ if (m) {
904
+ const gitDir = path.resolve(dir, m[1].trim());
905
+ common = gitDir;
906
+ own = gitDir;
907
+ try {
908
+ common = path.resolve(gitDir, fs.readFileSync(path.join(gitDir, 'commondir'), 'utf8').trim());
909
+ }
910
+ catch { /* not a linked worktree: the directory named is the repository's */ }
911
+ }
912
+ }
913
+ catch { /* [no-substitution: an entry that cannot be read names no store — git cannot read it either, and the judgement that asks git closes; the entry itself is still refused] */ }
914
+ }
915
+ // A-SPEC-794.114 — and the ledger witness, in this checkout's own git directory (governance/ledger-witness.ts)
916
+ out.stores = [...forms(path.join(common, 'objects')), ...forms(path.join(own, 'holmes-kit'))];
917
+ break;
918
+ }
919
+ const up = path.dirname(dir);
920
+ if (up === dir)
921
+ break;
922
+ dir = up;
923
+ }
924
+ // the deployed package that governs this session. In Holmes-Kit's own repository the package is the checkout, never
925
+ // deployed, and its files are principle 7's.
926
+ const running = require('../project/running-package');
927
+ const p7 = require('../governance/autonomy');
928
+ if (running.RUNNING_PACKAGE_ROOT !== '' && running.isDeployedPackage(running.RUNNING_PACKAGE_ROOT) && !p7.isHolmesKitOwnRepo(projectRoot)) {
929
+ // the whole package root: its launchers (bin) and its manifest decide what runs as the gate as its dist does —
930
+ // the invariant is "what a judgement reads or runs is not written from the session" (supervisor decision 11-12;
931
+ // the sealed text of A-SPEC-794.113 names the playbooks and the dist, and this is wider)
932
+ out.packageDirs = forms(running.realPathOf(running.RUNNING_PACKAGE_ROOT));
933
+ }
934
+ found = out;
935
+ return out;
936
+ };
937
+ const answers = new Map();
938
+ // a file system that folds case reaches ~/.holmes/runtime by another case too (the home directory is the user's,
939
+ // usually on the system volume): compared folded where the platform folds case
940
+ const folds = process.platform === 'darwin' || process.platform === 'win32';
941
+ const same = (a, b) => (folds ? a.toLowerCase() === b.toLowerCase() : a === b);
942
+ const under = (p, dir) => same(p, dir) || (folds ? p.toLowerCase() : p).startsWith((folds ? dir.toLowerCase() : dir).replace(/[\\/]*$/, path.sep));
943
+ // a drive path where the platform has no drives (the gate judges Windows spellings on POSIX too): path.resolve would read
944
+ // it as relative and land it under the working directory — nothing here can be written through such a spelling
945
+ const drive = (p) => process.platform !== 'win32' && /^[A-Za-z]:[\\/]/.test(p);
946
+ return (written) => {
947
+ if (drive(written) || drive(projectRoot))
948
+ return null;
949
+ const abs = path.resolve(projectRoot, written);
950
+ if (abs.length > 4096)
951
+ return null; // longer than any path the system resolves: nothing exists there
952
+ if (answers.has(abs))
953
+ return answers.get(abs) ?? null;
954
+ const p = protectedPaths();
955
+ const lands = [...new Set([abs, realOrSelf(abs)])];
956
+ const answer = lands.some((l) => p.entries.includes(l)) || lands.some((l) => p.stores.some((s) => within(l, s))) ? 'git'
957
+ : lands.some((l) => p.packageDirs.some((d) => within(l, d))) ? 'package'
958
+ : lands.some((l) => p.runtime.some((d) => under(l, d))) ? 'runtime' : null;
959
+ answers.set(abs, answer);
960
+ return answer;
961
+ };
962
+ }
963
+ const REFERENCE_INPUT_REFUSAL = {
964
+ git: 'the repository\'s own store is written by git alone — its objects, the .git entry itself and the ledger witness under it (.git/holmes-kit) are what the gate\'s judgements read (A-SPEC-794.113, 794.114). '
965
+ + 'Use a git command for this; the witness moves with the ledger\'s own appends and a person\'s vouch (`holmes-kit ledger witness`); what git cannot do here, a person does in their own terminal',
966
+ package: 'this is a file of the installed holmes-kit package that governs this session — its gate code, its launchers and its reference playbooks — and it is not written, moved or removed from the session (A-SPEC-794.113). '
967
+ + 'Upgrade or reinstall the package with npm; to change holmes-kit itself, work in a checkout of it',
968
+ runtime: 'this is the holmes-kit runtime (~/.holmes/runtime): its registry says which build governs each workspace and its launchers are what the harness runs as the gate, so it is not written, moved or removed from the session (A-SPEC-794.113). '
969
+ + 'Change a binding with `holmes-kit runtime-binding` (a person approves it), refresh the launchers with `holmes-kit upgrade`, or do it in your own terminal',
970
+ };
971
+ const referenceInputDeny = (shown, what) => ({ permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${shown}: ${REFERENCE_INPUT_REFUSAL[what]}.` });
972
+ /**
973
+ * @implements A-SPEC-794.113 — the holmes-kit subcommands that change what governs a workspace or rewrite its ledger are
974
+ * the operator's, wherever the CLI word sits. The installer rule (A-SPEC-753.3) reads the CLI as the command's first word,
975
+ * so a runner before it (`npx`, `npm exec`, `pnpm dlx`, `yarn dlx`, `bunx`, `env`, `nohup`) went unjudged (measured 11-12:
976
+ * `npx holmes-kit runtime-binding setup` and `npx holmes-kit ledger rechain` passed the hook; the CLI itself asks a person
977
+ * for `runtime-binding setup` but rewrote a forked chain for `ledger rechain` from inside a session). Runners are not
978
+ * listed here: any word that IS the CLI — its bin under any spelling, its entry script, its package name — opens a window
979
+ * of the words after it, as the outward judgement reads an unknown program's independent tokens (A-SPEC-794.72). A
980
+ * program string after `-c` (a shell, `npm exec -c`) is read as a command. A command that names the CLI and a governed
981
+ * word but cannot be read (a substitution, a word the lexer does not know) is unjudged, and refused.
982
+ */
983
+ const GOVERNED_CLI = [
984
+ { head: 'runtime-binding', ops: new Set(['setup', 'remove']), act: 'runtime-binding setup/remove changes which Holmes build governs a workspace (governance wiring)', preview: '--dry-run' },
985
+ { head: 'ledger', ops: new Set(['rechain']), act: 'ledger rechain rewrites the provenance chain wholesale (it re-chains and records the result)', preview: '--dry-run' },
986
+ ];
987
+ const isCliWord = (text) => {
988
+ const base = (text.replace(/\\/g, '/').split('/').pop() ?? '').replace(/\.(?:js|cjs|mjs|cmd|exe|ps1)$/i, '');
989
+ return base === 'holmes-kit' || /^@holmes-lab\/holmes-kit(?:@[^\s]*)?$/.test(text);
990
+ };
991
+ function governedCliAct(command, depth = 0) {
992
+ // the cheap look first, over the text with quoting removed (`holmes-k''it` is the CLI word to the shell — measured)
993
+ const bare = command.replace(/['"\\]/g, '');
994
+ if (depth > 4 || !/holmes-kit/.test(bare) || !GOVERNED_CLI.some((g) => bare.includes(g.head)))
995
+ return null;
996
+ const parsed = (0, shell_syntax_1.shellWords)(command, process.env, undefined, null, true);
997
+ if (parsed.overflow || parsed.subs.length > 0)
998
+ return { unjudged: 'it names holmes-kit and a governed subcommand, and holds a substitution or more than the gate reads' };
999
+ for (const one of parsed.commands) {
1000
+ let at = 0;
1001
+ while (at < one.words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(one.words[at].text))
1002
+ at++;
1003
+ // a program that only prints or searches runs nothing it names (`echo holmes-kit runtime-binding setup` was refused
1004
+ // by the first build of this rule — measured by the installer suite); what it pipes into a shell is the CLI's guard
1005
+ if (/^(?:echo|printf|grep|egrep|fgrep|rg|ag|cat|head|tail|less|more|wc|man|which|type|whatis)$/.test((one.words[at]?.text ?? '').replace(/^.*\//, '')))
1006
+ continue;
1007
+ const words = one.words.slice(at);
1008
+ const shellish = /^(?:sh|bash|zsh|dash|ksh|eval)$/.test((words[0]?.text ?? '').replace(/^.*\//, ''));
1009
+ for (let i = 0; i < words.length; i++) {
1010
+ const w = words[i];
1011
+ // a program string: after a `-c`-like option, or any word of a shell or eval
1012
+ if (/\s/.test(w.text) && (shellish || /^-\w*c$|^--call(?:=|$)/.test(words[i - 1]?.text ?? ''))) {
1013
+ const inner = governedCliAct(w.text, depth + 1);
1014
+ if (inner !== null)
1015
+ return inner;
1016
+ continue;
1017
+ }
1018
+ if (!isCliWord(w.text))
1019
+ continue;
1020
+ const window = words.slice(i + 1, i + 65);
1021
+ for (const g of GOVERNED_CLI) {
1022
+ const h = window.findIndex((x) => x.text === g.head);
1023
+ if (h < 0)
1024
+ continue;
1025
+ const rest = window.slice(h + 1);
1026
+ if (rest.some((x) => !x.known || x.glob))
1027
+ return { unjudged: `a word after \`holmes-kit ${g.head}\` is computed at run time` };
1028
+ if (!rest.some((x) => g.ops.has(x.text)))
1029
+ continue;
1030
+ if (g.preview !== undefined && rest.some((x) => x.text === g.preview))
1031
+ continue;
1032
+ return { act: g.act };
1033
+ }
1034
+ }
1035
+ }
1036
+ return null;
1037
+ }
1038
+ /**
1039
+ * @implements A-SPEC-794.91 (N2), 794.95, 794.96 — the principle 7 write rule for the file tools: judged where the write
1040
+ * lands (the path as written, posix-normalized, and its real path; the most restrictive verdict stands; a second hard
1041
+ * link is refused in Holmes-Kit's own repository); dist/holmes is the build's; a gate file is written only within an open
1042
+ * person-seal window naming it, and the opening is recorded. Whatever the file's extension (B-H2: the gate's JSON tables),
1043
+ * so it is read before the classifier lets a non-code write go. Null when the rule allows or does not apply.
1044
+ */
1045
+ function principle7WriteVerdict(projectRoot, relPath, p, specsOf, nowTs) {
1046
+ // the specs are read only once the path reaches the category (a documentation write must not scale with the corpus)
1047
+ const p7 = require('../governance/autonomy');
1048
+ const ownRepo = p7.isHolmesKitOwnRepo(projectRoot); // A-SPEC-794.97 r4b (L5)
1049
+ const candidates = (() => {
1050
+ const out = [path.posix.normalize(relPath.replace(/\\/g, '/'))];
1051
+ try {
1052
+ const abs = path.resolve(projectRoot, p);
1053
+ // longer than any path the system resolves: nothing exists there to link elsewhere (a 100,000-segment path walked
1054
+ // up one level at a time took 102 s); the tail is joined once
1055
+ if (abs.length <= 4096) {
1056
+ let probe = abs;
1057
+ const tail = [];
1058
+ while (!fs.existsSync(probe) && path.dirname(probe) !== probe) {
1059
+ tail.unshift(path.basename(probe));
1060
+ probe = path.dirname(probe);
1061
+ }
1062
+ const real = path.join(fs.realpathSync.native(probe), ...tail);
1063
+ const rel = path.relative(fs.realpathSync.native(projectRoot), real);
1064
+ if (!rel.startsWith('..') && !path.isAbsolute(rel))
1065
+ out.push(rel.split(path.sep).join('/'));
1066
+ }
1067
+ }
1068
+ catch { /* an unreadable path keeps the written one */ }
1069
+ return out;
1070
+ })();
1071
+ const verdicts = candidates.map((c) => p7.principle7WriteTarget(c, { ownRepo }));
1072
+ const target = verdicts.includes('dist') ? 'dist' : verdicts.includes('source') ? 'source' : null;
1073
+ let p7Rel = relPath;
1074
+ for (let k = 0; k < candidates.length; k++)
1075
+ if (verdicts[k] === target) {
1076
+ p7Rel = candidates[k];
1077
+ break;
1078
+ }
1079
+ if (target === null && ownRepo) {
1080
+ try {
1081
+ const st = fs.lstatSync(path.resolve(projectRoot, p));
1082
+ if (st.isFile() && st.nlink > 1) {
1083
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${relPath} has ${st.nlink} hard links, so a write here may land in a gate or approval-processing file this path does not name (principle 7). Write the file it links to by its own path.` };
1084
+ }
1085
+ }
1086
+ catch { /* a new file has no links */ }
1087
+ }
1088
+ if (target === 'dist')
1089
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${p7Rel}: ${p7.PRINCIPLE7_DIST_REFUSAL}.` };
1090
+ if (target !== 'source')
1091
+ return null;
1092
+ const opened = principle7Openers(projectRoot, specsOf(), nowTs, p7Rel);
1093
+ if (opened.openers.length === 0) {
1094
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${p7Rel}: ${p7.PRINCIPLE7_WRITE_REFUSAL}, within ${opened.hours} hours of that seal (principle 7). An anchor already on the file, or an older seal, does not open it. `
1095
+ + `Next: name ${p7Rel} in the Files to Touch of an A-SPEC and have a person seal it again (spec_approve asks in the session form; a sealed spec is sealed again with one answer).` };
1096
+ }
1097
+ recordWindowWrite(projectRoot, nowTs, p7Rel, opened); // A-SPEC-794.95, 794.96 (M-3)
1098
+ return null;
1099
+ }
1100
+ /**
1101
+ * @implements A-SPEC-794.96 (S2, S3) — a `git commit` (its staged principle 7 changes; with -a, its tracked ones too) and a
1102
+ * build command from one table (npm, pnpm, yarn `run build` or `build`; tsc; npx tsc) are judged against the working
1103
+ * tree; null when the command is neither. An unfamiliar build spelling is a named limit.
1104
+ */
1105
+ function commitOrBuildOf(command, root) {
1106
+ // A-SPEC-794.97 (M3) — a package script that reaches the build is a build: the scripts are read from package.json and
1107
+ // (r4) read as commands through the same walk, five levels deep; past them, a build
1108
+ const scripts = (() => {
1109
+ if (!root)
1110
+ return {};
1111
+ try {
1112
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
1113
+ return Object.fromEntries(Object.entries(pkg.scripts ?? {}).filter(([, v]) => typeof v === 'string'));
1114
+ }
1115
+ catch {
1116
+ return {};
1117
+ }
1118
+ })();
1119
+ // A-SPEC-794.97 r4b (L1) — tsc's informational flags write nothing (--version, --help, --all, --showConfig, --listFilesOnly)
1120
+ const noEmit = (w) => {
1121
+ if (w.some((a) => /^(?:-v|--version|-h|--help|-\?|--all|--showConfig|--listFilesOnly)$/.test(a)))
1122
+ return true;
1123
+ const k = w.findIndex((a) => a === '--noEmit' || a.startsWith('--noEmit='));
1124
+ return k >= 0 && w[k] !== '--noEmit=false' && w[k + 1] !== 'false';
1125
+ };
1126
+ const rank = { commit: 1, 'commit-all': 2, build: 3, 'build-after-move': 4 };
1127
+ const judge = (text, depth) => {
1128
+ let found = null;
1129
+ // A-SPEC-794.97 r5 (H1) — a git clause that moves HEAD, the index or the working tree before the build in the same
1130
+ // command: the judgement read the tree before the command ran, so the build would make unjudged code live
1131
+ let moved = false;
1132
+ const take = (f) => {
1133
+ const g = f === 'build' && moved ? 'build-after-move' : f;
1134
+ if (found === null || rank[g] > rank[found])
1135
+ found = g;
1136
+ };
1137
+ const scriptBuilds = (name) => {
1138
+ if (name === undefined)
1139
+ return false;
1140
+ if (name === 'build')
1141
+ return true;
1142
+ const body = scripts[name];
1143
+ if (body === undefined)
1144
+ return false;
1145
+ const inner = depth >= 5 ? 'build' : judge(body, depth + 1);
1146
+ if (inner === 'build-after-move')
1147
+ moved = true;
1148
+ return inner === 'build' || inner === 'build-after-move';
1149
+ };
1150
+ walkRootPrograms(text, root, (p) => {
1151
+ if (p.name === TOO_DEEP) {
1152
+ take('build');
1153
+ return;
1154
+ }
1155
+ if (p.name === 'git') {
1156
+ const g = gitTarget(p);
1157
+ if (g.judged && g.sub === 'commit')
1158
+ take(p.args.slice(g.at + 1).some((a) => a === '-a' || a === '--all' || /^-[a-zA-Z]*a[a-zA-Z]*$/.test(a)) ? 'commit-all' : 'commit');
1159
+ if (g.judged && g.sub !== undefined && treeMoving(g.sub, p.args.slice(g.at + 1)))
1160
+ moved = true;
1161
+ }
1162
+ else if (p.name === 'gh') {
1163
+ // r6 (A-M2) — gh checks a pull request out or syncs the repository: the working tree moves
1164
+ const pos = p.args.filter((a) => !a.startsWith('-'));
1165
+ if (p.here && ((pos[0] === 'pr' && pos[1] === 'checkout') || (pos[0] === 'repo' && pos[1] === 'sync') || pos[0] === 'co'))
1166
+ moved = true;
1167
+ }
1168
+ else if (p.name === 'npm' || p.name === 'pnpm' || p.name === 'yarn' || p.name === 'yarnpkg') {
1169
+ // A-SPEC-794.97 r4 (high-3) — the manager's options are skipped (-s, --silent, --prefix ., pnpm -C ., yarn --cwd .)
1170
+ let i = 0;
1171
+ let dir;
1172
+ while (i < p.args.length && p.args[i].startsWith('-')) {
1173
+ const o = p.args[i];
1174
+ const eq = /^(--prefix|--cwd|--dir)=(.*)$/.exec(o);
1175
+ if (eq) {
1176
+ dir = eq[2];
1177
+ i++;
1178
+ continue;
1179
+ }
1180
+ if (o === '--prefix' || o === '-C' || o === '--cwd' || o === '--dir') {
1181
+ dir = p.args[i + 1];
1182
+ i += 2;
1183
+ continue;
1184
+ }
1185
+ i += NPM_VALUED_FOR_BUILD.has(o) ? 2 : 1;
1186
+ }
1187
+ if (dir !== undefined ? p.place(dir) !== 'root' : !p.here)
1188
+ return; // r5 (B-H1): an unresolved --prefix is not the root
1189
+ const sub = p.args[i];
1190
+ let name = sub;
1191
+ if (sub === 'run' || sub === 'run-script' || sub === 'rum' || sub === 'urn') {
1192
+ let k = i + 1;
1193
+ while (k < p.args.length && p.args[k].startsWith('-'))
1194
+ k += NPM_VALUED_FOR_BUILD.has(p.args[k]) ? 2 : 1;
1195
+ name = p.args[k];
1196
+ }
1197
+ else if (p.name === 'npm' && !['test', 't', 'tst', 'start', 'stop', 'restart', 'build'].includes(sub ?? ''))
1198
+ return;
1199
+ // pnpm and yarn run a package binary by its name when no script has it (`yarn tsc`)
1200
+ if (p.name !== 'npm' && name === 'tsc' && scripts.tsc === undefined) {
1201
+ if (!noEmit(p.args))
1202
+ take('build');
1203
+ return;
1204
+ }
1205
+ if (scriptBuilds(name))
1206
+ take('build');
1207
+ }
1208
+ else if (p.name === UNREAD) {
1209
+ // a program word the gate cannot read: judged by its arguments
1210
+ if (p.args.includes('commit'))
1211
+ take(p.args.some((a) => a === '-a' || a === '--all' || /^-[a-zA-Z]*a[a-zA-Z]*$/.test(a)) ? 'commit-all' : 'commit');
1212
+ if (p.args.some((a) => a === 'build' || a === 'tsc' || scripts[a] !== undefined && scriptBuilds(a)) && !noEmit(p.args))
1213
+ take('build');
1214
+ if (p.args.some((a) => TREE_MOVERS.has(a)))
1215
+ moved = true;
1216
+ }
1217
+ else if ((p.name === 'tsc' || (p.name === 'node' && /(?:^|\/)(?:typescript\/bin\/tsc|\.bin\/tsc)$/.test(p.args[0] ?? '')))
1218
+ && p.here && !noEmit(p.args) && !emitsElsewhere(p) && projectEmitsLive(p, root)) {
1219
+ take('build'); // a type check writes nothing (`--noEmit false` emits); an --outDir outside the project is not the build
1220
+ }
1221
+ }, depth);
1222
+ return found;
1223
+ };
1224
+ return judge(command, 0);
1225
+ }
1226
+ /**
1227
+ * @implements A-SPEC-794.97 r5 (B-H1 ②) — `tsc -p X` builds the live gate only when X's outDir (through `extends`, five
1228
+ * levels) is the project's dist or under it; a config the gate cannot read is not judged (Stop judges what it changed).
1229
+ * Without -p the project's own tsconfig is the build's.
1230
+ */
1231
+ function projectEmitsLive(p, root) {
1232
+ const k = p.args.findIndex((a) => a === '-p' || a === '--project' || a.startsWith('--project='));
1233
+ if (k < 0 || root === undefined)
1234
+ return true;
1235
+ const arg = p.args[k].startsWith('--project=') ? p.args[k].slice(10) : p.args[k + 1];
1236
+ if (arg === undefined)
1237
+ return false;
1238
+ let file = p.resolve(arg);
1239
+ if (file === null)
1240
+ return false;
1241
+ try {
1242
+ if (fs.statSync(file).isDirectory())
1243
+ file = path.join(file, 'tsconfig.json');
1244
+ }
1245
+ catch {
1246
+ return false;
1247
+ }
1248
+ // the nearest config that sets each option wins (r6 B-L2: a noEmit anywhere in the chain before a child resets it)
1249
+ let outAbs;
1250
+ let noEmitSet;
1251
+ for (let hop = 0; hop < 5 && file !== null; hop++) {
1252
+ let cfg;
1253
+ try {
1254
+ cfg = JSON.parse(fs.readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\/|(^|[^:"])\/\/.*$/gm, '$1').replace(/,(\s*[}\]])/g, '$1'));
1255
+ }
1256
+ catch {
1257
+ return false;
1258
+ }
1259
+ const out = cfg.compilerOptions?.outDir;
1260
+ if (outAbs === undefined && typeof out === 'string')
1261
+ outAbs = path.resolve(path.dirname(file), out);
1262
+ if (noEmitSet === undefined && typeof cfg.compilerOptions?.noEmit === 'boolean')
1263
+ noEmitSet = cfg.compilerOptions.noEmit;
1264
+ if ((outAbs !== undefined && noEmitSet !== undefined) || typeof cfg.extends !== 'string' || !/^\.{1,2}\//.test(cfg.extends))
1265
+ break;
1266
+ file = path.resolve(path.dirname(file), cfg.extends.endsWith('.json') ? cfg.extends : `${cfg.extends}.json`);
1267
+ }
1268
+ if (outAbs === undefined || noEmitSet === true)
1269
+ return false;
1270
+ let rootReal;
1271
+ try {
1272
+ rootReal = fs.realpathSync.native(root);
1273
+ }
1274
+ catch {
1275
+ rootReal = path.resolve(root);
1276
+ }
1277
+ const dist = path.join(rootReal, 'dist');
1278
+ return outAbs === dist || outAbs.startsWith(dist + path.sep);
1279
+ }
1280
+ /** A tsc whose --outDir or --outFile resolves outside the project root writes no file the live gate loads. */
1281
+ function emitsElsewhere(p) {
1282
+ const k = p.args.findIndex((a) => a === '--outDir' || a === '--outFile' || a.startsWith('--outDir=') || a.startsWith('--outFile='));
1283
+ if (k < 0)
1284
+ return false;
1285
+ const v = p.args[k].includes('=') ? p.args[k].slice(p.args[k].indexOf('=') + 1) : p.args[k + 1];
1286
+ return v !== undefined && p.within(v) === false;
1287
+ }
1288
+ /**
1289
+ * A-SPEC-794.97 r5 (H1) — git subcommands that can change the working tree the build compiles. `commit` is not one: it
1290
+ * records the index and leaves the working tree as judged (the corpus holds about 180 `git commit … && npm run build`
1291
+ * commands of this repository's own flow).
1292
+ */
1293
+ const TREE_MOVERS = new Set(['pull', 'merge', 'checkout', 'switch', 'rebase', 'cherry-pick', 'am', 'revert', 'reset', 'stash', 'restore', 'apply']);
1294
+ function treeMoving(sub, rest) {
1295
+ if (!TREE_MOVERS.has(sub))
1296
+ return false;
1297
+ if (rest.some((a) => a === '-h' || a === '--help' || a === '--dry-run'))
1298
+ return false;
1299
+ if (sub === 'stash' && /^(?:list|show)$/.test(rest.find((a) => !a.startsWith('-')) ?? ''))
1300
+ return false;
1301
+ if (sub === 'apply' && rest.some((a) => /^--(?:check|stat|numstat|summary)$/.test(a)) && !rest.includes('--apply'))
1302
+ return false;
1303
+ // r6 (B-L1) — steps that leave the working tree as it is: a new branch at HEAD, a soft reset, unstaging, an index-only apply
1304
+ const pos = rest.filter((a) => !a.startsWith('-'));
1305
+ // (r6b L4: a start point of HEAD is the same tree)
1306
+ if ((sub === 'checkout' || sub === 'switch') && rest.some((a) => /^-(?:b|B|c|C)$/.test(a)) && (pos.length <= 1 || (pos.length === 2 && pos[1] === 'HEAD')) && !rest.includes('--'))
1307
+ return false;
1308
+ // a reset changes the working tree only with --hard, --keep or --merge (--soft and --mixed, the default, do not)
1309
+ if (sub === 'reset' && !rest.some((a) => a === '--hard' || a === '--keep' || a === '--merge'))
1310
+ return false;
1311
+ if (sub === 'restore' && rest.some((a) => a === '--staged' || a === '-S') && !rest.some((a) => a === '--worktree' || a === '-W'))
1312
+ return false;
1313
+ if (sub === 'apply' && rest.includes('--cached') && !rest.includes('--index'))
1314
+ return false;
1315
+ return true;
1316
+ }
1317
+ const TOO_DEEP = '\u0000too-deep';
1318
+ const UNREAD = '\u0000unread';
1319
+ const NPM_VALUED_FOR_BUILD = new Set(['-w', '--workspace', '--tag', '--registry', '--userconfig', '--globalconfig', '--cache', '--loglevel', '--filter', '-F', '--scope']);
1320
+ /**
1321
+ * @implements A-SPEC-794.97 r4 (high-3, medium-1) — the programs a command runs, read as the gate reads a program
1322
+ * elsewhere (`programOf`: NAME=value, env, command, time, nice, nohup, npx, npm exec … unwrapped), following cd and pushd
1323
+ * (a target the gate cannot resolve is judged as the root; a subshell's cd ends with it) and the body of `sh|bash|zsh -c`
1324
+ * and `eval`. Past five levels the walk reports TOO_DEEP.
1325
+ */
1326
+ function walkRootPrograms(command, root, visit, depth = 0, start, script) {
1327
+ if (depth > 5) {
1328
+ visit({ name: TOO_DEEP, args: [], env: [], here: true, place: () => 'unknown', within: () => null, resolve: () => null });
1329
+ return;
1330
+ }
1331
+ const { lexShell } = require('../guardrail/shell-lexer');
1332
+ const { programOf } = require('../guardrail/risk-classifier');
1333
+ const { SHELL_PROGRAMS } = require('../guardrail/command-traits');
1334
+ let lexed;
1335
+ try {
1336
+ lexed = lexShell(command);
1337
+ }
1338
+ catch {
1339
+ return;
1340
+ }
1341
+ const real = (p) => { try {
1342
+ return fs.realpathSync.native(p);
1343
+ }
1344
+ catch {
1345
+ return path.resolve(p);
1346
+ } };
1347
+ const rootReal = root === undefined ? undefined : real(root);
1348
+ let cwd = start === undefined ? (rootReal ?? null) : start;
1349
+ let oldpwd = null;
1350
+ // a variable given a value the gate can read by a clause of its own at the top level (`S=/x; cd $S`) is read; any other
1351
+ // is unknown
1352
+ const vars = new Map();
1353
+ const foreign = new Set();
1354
+ // A-SPEC-794.97 r4 (probe) — a directory under the root is the same repository (git and npm find the root above it)
1355
+ // (a nested work tree — a linked worktree or another clone under the root, which holds its own .git — is not)
1356
+ const inside = (r) => {
1357
+ if (rootReal === undefined || r === rootReal)
1358
+ return true;
1359
+ if (!r.startsWith(rootReal + path.sep))
1360
+ return false;
1361
+ // r5 (B-H1 ③) — a path this command makes a worktree or a clone in is another repository
1362
+ for (const f of foreign)
1363
+ if (r === f || r.startsWith(f + path.sep))
1364
+ return false;
1365
+ for (let d = r; d !== rootReal && d.length > rootReal.length; d = path.dirname(d))
1366
+ if (fs.existsSync(path.join(d, '.git')))
1367
+ return false;
1368
+ return true;
1369
+ };
1370
+ const expand = (dir) => {
1371
+ const out = dir.replace(/\$\{(\w+)\}|\$(\w+)/g, (_m, a, b) => vars.get((a ?? b)) ?? '\u0000');
1372
+ return out.includes('\u0000') ? null : out;
1373
+ };
1374
+ const resolveFrom = (from, raw) => {
1375
+ const dir = expand(raw);
1376
+ if (dir === null || /[$`\u0000]/.test(dir) || dir === '-' || /^[+-]\d+$/.test(dir))
1377
+ return null;
1378
+ const d = dir.startsWith('~') ? path.join(os.homedir(), dir.slice(1)) : dir;
1379
+ if (path.isAbsolute(d))
1380
+ return real(d);
1381
+ return from === null ? null : real(path.resolve(from, d));
1382
+ };
1383
+ /**
1384
+ * A-SPEC-794.97 r6 (A-H1 (a)) — a word's value where the shell would give a fixed one: quotes and escapes removed,
1385
+ * `$0` (the script being read), `$PWD`, `$OLDPWD`, `$HOME`, a known variable, and the substitutions `$(pwd)`,
1386
+ * `$(dirname X)`, `$(realpath X)`, `$(readlink -f X)`, `$(cd X && pwd)` and `$(git rev-parse --show-toplevel)`.
1387
+ * Null for anything else.
1388
+ */
1389
+ const evalRaw = (raw, depthE = 0) => {
1390
+ if (depthE > 8)
1391
+ return null;
1392
+ let out = '';
1393
+ for (let i = 0; i < raw.length;) {
1394
+ const ch = raw[i];
1395
+ if (ch === "'") {
1396
+ const j = raw.indexOf("'", i + 1);
1397
+ if (j < 0)
1398
+ return null;
1399
+ out += raw.slice(i + 1, j);
1400
+ i = j + 1;
1401
+ continue;
1402
+ }
1403
+ if (ch === '"') {
1404
+ i++;
1405
+ continue;
1406
+ }
1407
+ if (ch === '\\') {
1408
+ out += raw[i + 1] ?? '';
1409
+ i += 2;
1410
+ continue;
1411
+ }
1412
+ if (ch === '`')
1413
+ return null;
1414
+ if (raw.startsWith('$(', i) && !raw.startsWith('$((', i)) {
1415
+ let level = 0, j = i + 1, q = null;
1416
+ for (; j < raw.length; j++) {
1417
+ const c = raw[j];
1418
+ if (q !== null) {
1419
+ if (c === q)
1420
+ q = null;
1421
+ else if (c === '\\' && q === '"')
1422
+ j++;
1423
+ continue;
1424
+ }
1425
+ if (c === '"' || c === "'") {
1426
+ q = c;
1427
+ continue;
1428
+ }
1429
+ if (c === '(')
1430
+ level++;
1431
+ else if (c === ')') {
1432
+ level--;
1433
+ if (level === 0)
1434
+ break;
1435
+ }
1436
+ }
1437
+ if (j >= raw.length)
1438
+ return null;
1439
+ const v = evalSub(raw.slice(i + 2, j), depthE + 1);
1440
+ if (v === null)
1441
+ return null;
1442
+ out += v;
1443
+ i = j + 1;
1444
+ continue;
1445
+ }
1446
+ if (ch === '$') {
1447
+ // r6b (L2) — ${BASH_SOURCE[0]} and $BASH_SOURCE are the script being read, as $0 is
1448
+ const m = /^\$(?:\{(\w+)(?:\[0\])?\}|(\w+))/.exec(raw.slice(i));
1449
+ if (m === null)
1450
+ return null;
1451
+ const n = (m[1] ?? m[2]);
1452
+ const v = n === '0' || n === 'BASH_SOURCE' ? script ?? null : n === 'PWD' ? cwd : n === 'OLDPWD' ? oldpwd : n === 'HOME' ? os.homedir() : vars.get(n) ?? null;
1453
+ if (v === null || v === undefined)
1454
+ return null;
1455
+ out += v;
1456
+ i += m[0].length;
1457
+ continue;
1458
+ }
1459
+ out += ch;
1460
+ i++;
1461
+ }
1462
+ return out;
1463
+ };
1464
+ const evalSub = (body, depthE) => {
1465
+ let l;
1466
+ try {
1467
+ l = lexShell(body);
1468
+ }
1469
+ catch {
1470
+ return null;
1471
+ }
1472
+ if (!l.ok)
1473
+ return null;
1474
+ const cl = l.clauses.map((x) => x.words);
1475
+ const val = (x) => (x === undefined ? null : evalRaw(x.raw, depthE));
1476
+ const at = (from, x) => { const v = val(x); return v === null ? null : resolveFrom(from, v); };
1477
+ if (cl.length === 1) {
1478
+ const ws = cl[0];
1479
+ const n = ws[0]?.value;
1480
+ if (n === 'pwd' && ws.length <= 2)
1481
+ return cwd;
1482
+ if (n === 'dirname' && ws.length === 2) {
1483
+ const v = val(ws[1]);
1484
+ return v === null ? null : path.dirname(v);
1485
+ }
1486
+ if (n === 'realpath' && ws.length === 2)
1487
+ return at(cwd, ws[1]);
1488
+ if (n === 'readlink' && ws.length === 3 && ws[1].value === '-f')
1489
+ return at(cwd, ws[2]);
1490
+ if (n === 'git' && ws.length === 3 && ws[1].value === 'rev-parse' && ws[2].value === '--show-toplevel')
1491
+ return cwd !== null && inside(cwd) ? rootReal ?? null : null;
1492
+ return null;
1493
+ }
1494
+ if (cl.length === 2 && cl[0][0]?.value === 'cd' && cl[0].length === 2 && cl[1][0]?.value === 'pwd' && cl[1].length <= 2)
1495
+ return at(cwd, cl[0][1]);
1496
+ return null;
1497
+ };
1498
+ const saved = new Map();
1499
+ let groups = [];
1500
+ for (const c of lexed.clauses) {
1501
+ let k = 0;
1502
+ while (k < groups.length && k < c.groups.length && groups[k] === c.groups[k])
1503
+ k++;
1504
+ if (k < groups.length)
1505
+ cwd = saved.has(groups[k]) ? saved.get(groups[k]) ?? null : cwd;
1506
+ for (let j = k; j < c.groups.length; j++)
1507
+ saved.set(c.groups[j], cwd);
1508
+ groups = c.groups;
1509
+ // A-SPEC-794.97 r5 (M1) — a clause's leading brace, negation or case pattern is not its program
1510
+ let lead = 0;
1511
+ while (lead < c.words.length && (/^[{}!]$/.test(c.words[lead].value) || /^[^$`(]*\)$/.test(c.words[lead].value)))
1512
+ lead++;
1513
+ const words = c.words.slice(lead);
1514
+ // r6 (A-H1 (a)) — each word's value as the shell gives it where it is fixed; an unreadable one keeps a NUL
1515
+ const w = words.map((x) => (x.literal && !/[$`]/.test(x.raw) ? x.value : evalRaw(x.raw) ?? `${x.value}\u0000`));
1516
+ const p = programOf(w);
1517
+ if (p === null && w.length > 0 && words.every((x) => /^[A-Za-z_]\w*=/.test(x.value))) {
1518
+ for (const x of words) {
1519
+ const name = x.value.slice(0, x.value.indexOf('='));
1520
+ // r5 (B-H1 ①), r6 — a value the gate can read (`T=/tmp/x; C=$T/clone`, `ROOT="$(cd "$(dirname "$0")/.." && pwd)"`)
1521
+ const known = c.groups.length === 0 ? evalRaw(x.raw.slice(x.raw.indexOf('=') + 1)) : null;
1522
+ if (known !== null)
1523
+ vars.set(name, known);
1524
+ else
1525
+ vars.delete(name);
1526
+ }
1527
+ continue;
1528
+ }
1529
+ if (p === null || p.unknown)
1530
+ continue;
1531
+ const at = w.indexOf(p.word);
1532
+ const env = (at < 0 ? w : w.slice(0, at)).filter((x) => /^[A-Za-z_]\w*=/.test(x));
1533
+ const here = cwd !== null && inside(cwd); // r5 (B-H1): an unresolved directory is left to Stop
1534
+ const from = cwd;
1535
+ const place = (dir) => {
1536
+ const r = resolveFrom(from, dir);
1537
+ return r === null ? 'unknown' : inside(r) ? 'root' : 'other';
1538
+ };
1539
+ const within = (dir) => {
1540
+ const r = resolveFrom(from, dir);
1541
+ return r === null ? null : rootReal === undefined || r === rootReal || r.startsWith(rootReal + path.sep);
1542
+ };
1543
+ if (p.name === 'git') {
1544
+ // r5 (B-H1 ③) — `git worktree add <path>` and `git clone <url> [<dir>]` make another repository there
1545
+ const pos = [];
1546
+ for (let k = 0; k < p.args.length; k++) {
1547
+ const a = p.args[k];
1548
+ if (/^-(?:b|B|o|c|C|j|u)$|^--(?:branch|depth|origin|reference|config|template|separate-git-dir|jobs|upload-pack|git-dir|work-tree|reason)$/.test(a)) {
1549
+ k++;
1550
+ continue;
1551
+ }
1552
+ if (!a.startsWith('-'))
1553
+ pos.push(a);
1554
+ }
1555
+ const wt = pos.indexOf('worktree');
1556
+ const target = wt >= 0 && pos[wt + 1] === 'add' ? pos[wt + 2]
1557
+ : pos[0] === 'clone' || pos.includes('clone') ? (() => { const k = pos.indexOf('clone'); return pos[k + 2] ?? (pos[k + 1] ?? '').replace(/\/+$/, '').split(/[/:]/).pop()?.replace(/\.git$/, ''); })()
1558
+ : undefined;
1559
+ if (target) {
1560
+ const t = resolveFrom(cwd, target);
1561
+ if (t !== null)
1562
+ foreign.add(t);
1563
+ }
1564
+ }
1565
+ if (p.name === 'cd' || p.name === 'pushd') {
1566
+ const t = p.args.find((a) => !a.startsWith('-') || a === '-');
1567
+ const before = cwd;
1568
+ // r6 — `cd -` returns to $OLDPWD; r6 (A-H1 (b)) — inside a script under the root, a cd the gate cannot resolve is
1569
+ // taken as the root (a script of the repository: a false refusal costs little there)
1570
+ const next = t === undefined ? real(os.homedir()) : t === '-' ? oldpwd : resolveFrom(cwd, t);
1571
+ cwd = next === null && script !== undefined ? rootReal ?? null : next;
1572
+ oldpwd = before;
1573
+ continue;
1574
+ }
1575
+ // A-SPEC-794.97 r5 (M2) — a shell script under the root (bash f, sh f, ./f, . f, source f) is read as commands
1576
+ const runScript = (file) => {
1577
+ if (file === undefined)
1578
+ return false;
1579
+ const abs = resolveFrom(cwd, file);
1580
+ if (abs === null || !inside(abs))
1581
+ return false;
1582
+ let text;
1583
+ try {
1584
+ const st = fs.statSync(abs);
1585
+ if (!st.isFile() || st.size > 1024 * 1024)
1586
+ return false;
1587
+ text = fs.readFileSync(abs, 'utf8');
1588
+ }
1589
+ catch {
1590
+ return false;
1591
+ }
1592
+ walkRootPrograms(text, root, visit, depth + 1, cwd, abs);
1593
+ return true;
1594
+ };
1595
+ // r6 (A-L1) — an executable named by a path: a .sh/.bash file, or one whose first line runs sh, bash or zsh
1596
+ const shellFile = (file) => {
1597
+ if (/\.(?:sh|bash)$/.test(file))
1598
+ return true;
1599
+ const abs = resolveFrom(cwd, file);
1600
+ if (abs === null)
1601
+ return false;
1602
+ try {
1603
+ const fd = fs.openSync(abs, 'r');
1604
+ try {
1605
+ const b = Buffer.alloc(80);
1606
+ const n = fs.readSync(fd, b, 0, 80, 0);
1607
+ return /^#!\S*(?:\/env\s+)?\S*\b(?:ba|z|da|k)?sh\b/.test(b.subarray(0, n).toString('utf8'));
1608
+ }
1609
+ finally {
1610
+ fs.closeSync(fd);
1611
+ }
1612
+ }
1613
+ catch {
1614
+ return false;
1615
+ }
1616
+ };
1617
+ if (SHELL_PROGRAMS.test(p.name)) {
1618
+ const ci = p.args.findIndex((a) => /^-[A-Za-z]*c[A-Za-z]*$/.test(a));
1619
+ if (ci >= 0 && p.args[ci + 1] !== undefined)
1620
+ walkRootPrograms(p.args[ci + 1], root, visit, depth + 1, cwd);
1621
+ else {
1622
+ let k = 0;
1623
+ while (k < p.args.length && /^[-+]/.test(p.args[k]))
1624
+ k += /^[-+]o$/.test(p.args[k]) ? 2 : 1;
1625
+ runScript(p.args[k]);
1626
+ }
1627
+ continue;
1628
+ }
1629
+ if (p.name === '.' || p.name === 'source') {
1630
+ runScript(p.args[0]);
1631
+ continue;
1632
+ }
1633
+ if (p.word.includes('/') && !p.word.includes('\u0000') && shellFile(p.word) && runScript(p.word))
1634
+ continue;
1635
+ if (p.name === 'eval') {
1636
+ walkRootPrograms(p.args.join(' '), root, visit, depth + 1, cwd);
1637
+ continue;
1638
+ }
1639
+ // a program that assigns (read, export, a loop variable) leaves the names it touches unknown
1640
+ for (const a of p.args) {
1641
+ const m = /^([A-Za-z_]\w*)=/.exec(a);
1642
+ if (m)
1643
+ vars.delete(m[1]);
1644
+ }
1645
+ if (p.name === 'read' || p.name === 'for' || p.name === 'select')
1646
+ for (const a of p.args)
1647
+ vars.delete(a);
1648
+ // A-SPEC-794.97 r4 (probe) — a program word made at run time ($NPM, $(echo npm)) is read through the literal variables;
1649
+ // what stays unread is reported as UNREAD, judged by its arguments
1650
+ // (r6: the word's value was already read through evalRaw; what keeps a NUL stays unread)
1651
+ const name = p.word.includes('\u0000') ? UNREAD : p.name;
1652
+ visit({ name, args: [...p.args], env, here, place, within, resolve: (dir) => resolveFrom(from, dir) });
1653
+ }
1654
+ }
1655
+ /**
1656
+ * @implements A-SPEC-794.97 r4 (medium-1) — the repository a git command writes: judged when -C, --git-dir, --work-tree,
1657
+ * GIT_DIR or GIT_WORK_TREE resolve to the project root (or cannot be resolved), or none is given and it runs there.
1658
+ */
1659
+ function gitTarget(p) {
1660
+ let i = 0;
1661
+ let base;
1662
+ let gitDir = p.env.find((e) => e.startsWith('GIT_DIR='))?.slice(8);
1663
+ let workTree = p.env.find((e) => e.startsWith('GIT_WORK_TREE='))?.slice(14);
1664
+ while (i < p.args.length && p.args[i].startsWith('-')) {
1665
+ const o = p.args[i];
1666
+ if (o === '-C') {
1667
+ const d = p.args[i + 1] ?? '';
1668
+ base = base === undefined || path.isAbsolute(d) ? d : path.join(base, d);
1669
+ i += 2;
1670
+ continue;
1671
+ }
1672
+ if (o.startsWith('--git-dir=')) {
1673
+ gitDir = o.slice(10);
1674
+ i++;
1675
+ continue;
1676
+ }
1677
+ if (o.startsWith('--work-tree=')) {
1678
+ workTree = o.slice(12);
1679
+ i++;
1680
+ continue;
1681
+ }
1682
+ if (o === '--git-dir') {
1683
+ gitDir = p.args[i + 1];
1684
+ i += 2;
1685
+ continue;
1686
+ }
1687
+ if (o === '--work-tree') {
1688
+ workTree = p.args[i + 1];
1689
+ i += 2;
1690
+ continue;
1691
+ }
1692
+ i += o === '-c' || o === '--namespace' || o === '--config-env' || o === '--exec-path' ? 2 : 1;
1693
+ }
1694
+ const rel = (d) => (base === undefined || path.isAbsolute(d) || d.startsWith('~') ? d : path.join(base, d));
1695
+ // the git directory's parent is the repository it writes (a bare or linked directory elsewhere is not the root's)
1696
+ const gitDirAt = gitDir === undefined ? undefined : p.place(path.join(rel(gitDir), '..'));
1697
+ // A-SPEC-794.97 r5 (B-H1) — judged only where the target resolves to the root: a place the gate cannot resolve is left
1698
+ // to Stop (a variable pointing at the root is the deliberate class, a named limit)
1699
+ const judged = (gitDir !== undefined ? gitDirAt === 'root' : base !== undefined ? p.place(base) === 'root' : p.here)
1700
+ || (workTree !== undefined && p.place(rel(workTree)) === 'root');
1701
+ return { judged, sub: p.args[i], at: i };
1702
+ }
1703
+ /**
1704
+ * @implements A-SPEC-794.97 r4 (high-1, high-2) — git writes the principle 7 judgement must not lose sight of: a
1705
+ * replacement object (`git replace`, a refs/replace ref), which makes the baseline read as another commit, and the index
1706
+ * entries of a category file (update-index: --cacheinfo, --assume-unchanged, --skip-worktree, --index-info). Null when none.
1707
+ */
1708
+ function gitHiddenWriteOf(command, root) {
1709
+ let why = null;
1710
+ walkRootPrograms(command, root, (p) => {
1711
+ if (why !== null)
1712
+ return;
1713
+ if (p.name === UNREAD && p.args.some((a) => a === 'replace' || a === 'update-index' || a.includes('refs/replace'))) {
1714
+ why = 'a program the gate cannot read runs a git replace or update-index';
1715
+ return;
1716
+ }
1717
+ if (p.name !== 'git')
1718
+ return;
1719
+ const g = gitTarget(p);
1720
+ if (!g.judged)
1721
+ return;
1722
+ const rest = p.args.slice(g.at + 1);
1723
+ if (g.sub === 'replace' && rest.some((a) => !/^(?:-l|--list|--format=.*)$/.test(a))) {
1724
+ why = 'git replace makes a commit read as another (the baseline would read as the changed tree)';
1725
+ return;
1726
+ }
1727
+ if (rest.some((a) => a.includes('refs/replace'))) {
1728
+ why = 'a refs/replace ref makes a commit read as another';
1729
+ return;
1730
+ }
1731
+ if (g.sub === 'update-index') {
1732
+ if (rest.some((a) => a === '--index-info' || a === '--stdin')) {
1733
+ why = 'git update-index reads index entries the gate cannot list';
1734
+ return;
1735
+ }
1736
+ const p7 = require('../governance/autonomy');
1737
+ const paths = rest.flatMap((a) => a.split(',')).filter((a) => a !== '' && !a.startsWith('-'));
1738
+ const hit = paths.find((a) => p7.principle7WriteTarget(path.posix.normalize(a.replace(/\\/g, '/')), { ownRepo: true }) !== null);
1739
+ if (hit !== undefined)
1740
+ why = `git update-index sets the index entry of ${hit}, a principle 7 file, apart from its content`;
1741
+ }
1742
+ });
1743
+ return why;
1744
+ }
1745
+ /**
1746
+ * @implements A-SPEC-794.91 (L-b) — whether a clause of the command widens autonomy, read by words per clause with the
1747
+ * shell lexer (quotes, escapes and line continuations resolved by it; case folded). A clause counts when it holds the word
1748
+ * `autonomy` and, after it, a word full|on|delegate or a first non-option word the gate cannot read statically (`$S`,
1749
+ * `$'…'`); or when a word it cannot read statically ends in `nomy` (`${A}nomy`). The program is not required: an alias
1750
+ * (`hk`) runs the same CLI. An `on` in another clause is not read; a command the lexer cannot read keeps the 794.89
1751
+ * reading over the whole text (fail-closed).
1752
+ */
1753
+ function runsAutonomyWidening(command) {
1754
+ const flat = () => /\bautonomy\b[\s\S]*?\b(?:full|on|delegate)\b/.test(command.replace(/\\\r?\n/g, ' ').replace(/[\\'"`]/g, '').toLowerCase());
1755
+ let lexed;
1756
+ try {
1757
+ lexed = require('../guardrail/shell-lexer').lexShell(command);
1758
+ }
1759
+ catch {
1760
+ return flat();
1761
+ }
1762
+ if (!lexed.ok || lexed.tooDeep)
1763
+ return flat();
1764
+ const unread = (w) => !w.literal || /[$`]/.test(w.raw);
1765
+ for (const c of lexed.clauses) {
1766
+ const words = c.words;
1767
+ if (words.some((w) => unread(w) && /nomy['"]?$/i.test(w.raw)))
1768
+ return true;
1769
+ const at = words.findIndex((w) => w.value.toLowerCase() === 'autonomy');
1770
+ if (at < 0)
1771
+ continue;
1772
+ const after = words.slice(at + 1);
1773
+ if (after.some((w) => /^(?:full|on|delegate)$/.test(w.value.toLowerCase())))
1774
+ return true;
1775
+ const sub = after.find((w) => !w.value.startsWith('-'));
1776
+ if (sub !== undefined && unread(sub))
1777
+ return true;
1778
+ }
1779
+ return false;
1780
+ }
675
1781
  /**
676
1782
  * @implements A-SPEC-245.9 (1b-5, item 7) — `holmes-kit lock recover` retires a lock another process may hold: the
677
1783
  * operator's act. The CLI refuses it from an agent by the environment and the process ancestry, which a process
@@ -2049,7 +3155,8 @@ function normalizeHookInput(raw, host = process.platform) {
2049
3155
  }
2050
3156
  }
2051
3157
  const sessionId = str(r.session_id);
2052
- return { tool_name: psShell !== undefined ? 'Bash' : str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(sessionId ? { session_id: sessionId } : {}), ...(malformed ? { malformed: true } : {}),
3158
+ const agentId = str(r.agent_id);
3159
+ return { tool_name: psShell !== undefined ? 'Bash' : str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(sessionId ? { session_id: sessionId } : {}), ...(agentId ? { agent_id: agentId } : {}), ...(malformed ? { malformed: true } : {}),
2053
3160
  ...(ps !== null && 'unjudgeable' in ps ? { powershellUnjudgeable: ps.unjudgeable } : {}),
2054
3161
  ...(codexPs !== null ? { codexPowerShell: codexPs } : {}),
2055
3162
  ...(patchUnreadable ? { patchUnreadable: true } : {}), ...(shellMarked && !otherUnreadable ? { patchUnreadableCause: 'shell-marker' } : {}),
@@ -2089,8 +3196,20 @@ function preEditEvidenceGate(o) {
2089
3196
  return null;
2090
3197
  if (o.covered)
2091
3198
  return null;
2092
- const verdict = (0, impact_gate_1.evaluateEditEvidence)((0, impact_gate_1.loadEditEvidence)(o.projectRoot, o.relPath, o.declaredDigest, o.currentHead));
2093
- return (0, impact_gate_1.preEditEvidenceDecision)(verdict, o.mode);
3199
+ const evidence = (0, impact_gate_1.loadEditEvidence)(o.projectRoot, o.relPath, o.declaredDigest, o.currentHead);
3200
+ const verdict = (0, impact_gate_1.evaluateEditEvidence)(evidence);
3201
+ const decision = (0, impact_gate_1.preEditEvidenceDecision)(verdict, o.mode);
3202
+ // @implements A-SPEC-333.4 — a clean allow clears the file from the commit reminder (recorded with the final allow)
3203
+ if (decision === null && verdict.decision === 'allow' && o.advisory)
3204
+ (0, advisory_line_1.adviseClean)(o.projectRoot, o.advisory, o.relPath);
3205
+ // @implements A-SPEC-333.2 — only a warn allow is shaped; a deny is said in full and touches no store
3206
+ if (decision?.permissionDecision !== 'allow' || !o.advisory)
3207
+ return decision;
3208
+ const detail = (0, advisory_line_1.advisoryDetail)({ artifactDigest: evidence.artifactDigest, traceGaps: evidence.traceGaps, head: o.currentHead, codes: verdict.reasons.map((r) => r.code) });
3209
+ const said = (0, advisory_line_1.adviseWarn)(o.projectRoot, o.advisory, verdict, o.relPath, detail, decision.permissionDecisionReason ?? '');
3210
+ if (said === undefined)
3211
+ return decision;
3212
+ return said === null ? { permissionDecision: 'allow' } : { ...decision, permissionDecisionReason: said };
2094
3213
  }
2095
3214
  function decideOnGateError(opts) {
2096
3215
  if (opts.bypass) {
@@ -2509,9 +3628,127 @@ function judgeHook(input, specsDir, opts) {
2509
3628
  let personStaging = false;
2510
3629
  // @implements A-SPEC-794.49 — REQ-792: push and publish follow the profile's flags, and no grant lifts it
2511
3630
  const outwardEntry = fullEntry();
2512
- const outwardRoute = outwardEntry === null ? null : (0, full_autonomy_1.fullModeOutwardRefusal)((0, risk_classifier_1.outwardActsOf)(command), outwardEntry);
2513
- if (outwardRoute !== null) {
2514
- return { permissionDecision: 'deny', refusal: 'full-autonomy.refused', permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: a push or a publish is irreversible and outward — refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', outwardRoute)}` };
3631
+ // A-SPEC-794.69 — a script run reads the package.json npm would use: the nearest one at or above the directory the
3632
+ // command runs in. None up to the file-system root is no scripts; a malformed one, or an explicit --prefix/-w
3633
+ // directory without one, closes the run
3634
+ // A-SPEC-794.71 — each directory's scripts are read once per evaluation
3635
+ const scriptsRead = new Map();
3636
+ const readScripts = (dir, explicit) => {
3637
+ const key = `${explicit === true ? 'x' : 'w'}:${dir}`;
3638
+ if (!scriptsRead.has(key))
3639
+ scriptsRead.set(key, readScriptsAt(dir, explicit));
3640
+ return scriptsRead.get(key) ?? null;
3641
+ };
3642
+ const readScriptsAt = (dir, explicit) => {
3643
+ for (let d = dir;; d = path.dirname(d)) {
3644
+ let text = null;
3645
+ try {
3646
+ text = fs.readFileSync(path.join(d, 'package.json'), 'utf8');
3647
+ }
3648
+ catch (e) {
3649
+ if (e?.code !== 'ENOENT' && e?.code !== 'ENOTDIR')
3650
+ return null;
3651
+ }
3652
+ if (text !== null) {
3653
+ try {
3654
+ const s = JSON.parse(text).scripts;
3655
+ if (s === undefined)
3656
+ return {};
3657
+ if (!s || typeof s !== 'object' || Array.isArray(s))
3658
+ return null;
3659
+ return Object.fromEntries(Object.entries(s).filter((e) => typeof e[1] === 'string'));
3660
+ }
3661
+ catch {
3662
+ return null;
3663
+ }
3664
+ }
3665
+ if (explicit === true && d === dir)
3666
+ return null;
3667
+ if (path.dirname(d) === d)
3668
+ return {};
3669
+ }
3670
+ };
3671
+ // A-SPEC-794.71 — a script run in a directory the gate cannot resolve is looked up in the repository's packages:
3672
+ // git's tracked package.json files (node_modules excluded), or, outside a git work tree, a walk that skips
3673
+ // node_modules and stops at 8,000 entries. A malformed file is skipped and named; a limit closes and names itself.
3674
+ // Listed once per evaluation.
3675
+ let listed;
3676
+ const allScripts = () => {
3677
+ if (listed !== undefined)
3678
+ return listed;
3679
+ if (opts.projectRoot === undefined)
3680
+ return (listed = null);
3681
+ const root = opts.projectRoot;
3682
+ const out = { packages: [], unreadable: [] };
3683
+ const take = (dir) => {
3684
+ const s = readScripts(dir, true);
3685
+ if (s === null)
3686
+ out.unreadable.push(path.relative(root, path.join(dir, 'package.json')) || 'package.json');
3687
+ else
3688
+ out.packages.push({ dir, scripts: s });
3689
+ };
3690
+ // A-SPEC-794.72 — tracked files (submodules included) and untracked ones that are not ignored; --recurse-submodules
3691
+ // and --others do not combine, so two listings
3692
+ let files = null;
3693
+ try {
3694
+ const spec = ['--', '*package.json', ':!:**/node_modules/**'];
3695
+ const tracked = (0, bounded_io_1.gitOnce)(root, ['-c', 'core.fsmonitor=false', 'ls-files', '-z', '--recurse-submodules', ...spec], 'repo', { env: (0, root_1.cleanSubprocessEnv)() });
3696
+ const others = (0, bounded_io_1.gitOnce)(root, ['-c', 'core.fsmonitor=false', 'ls-files', '-z', '--others', '--exclude-standard', ...spec], 'repo', { env: (0, root_1.cleanSubprocessEnv)() });
3697
+ if (tracked.status === 0 && others.status === 0) {
3698
+ files = [...new Set(`${tracked.stdout}\0${others.stdout}`.split('\0'))].filter((p) => p === 'package.json' || p.endsWith('/package.json'));
3699
+ }
3700
+ }
3701
+ catch {
3702
+ files = null;
3703
+ }
3704
+ if (files !== null) {
3705
+ if (files.length > 8000)
3706
+ return (listed = { ...out, limit: `more than 8,000 tracked package.json files` });
3707
+ for (const f of files)
3708
+ take(path.dirname(path.join(root, f)));
3709
+ return (listed = out);
3710
+ }
3711
+ let seen = 0;
3712
+ const walk = (dir) => {
3713
+ if (++seen > 8000)
3714
+ return false;
3715
+ let entries;
3716
+ try {
3717
+ entries = fs.readdirSync(dir, { withFileTypes: true });
3718
+ }
3719
+ catch {
3720
+ return true;
3721
+ }
3722
+ if (entries.some((e) => e.isFile() && e.name === 'package.json'))
3723
+ take(dir);
3724
+ for (const e of entries) {
3725
+ // A-SPEC-794.72 — hidden directories (but .github), virtual environments and build output are not counted
3726
+ if (!e.isDirectory() || e.name === 'node_modules' || (e.name.startsWith('.') && e.name !== '.github')
3727
+ || ['venv', '__pycache__', 'dist', 'build'].includes(e.name))
3728
+ continue;
3729
+ if (!walk(path.join(dir, e.name)))
3730
+ return false;
3731
+ }
3732
+ return true;
3733
+ };
3734
+ return (listed = walk(root) ? out : { ...out, limit: 'more than 8,000 directories outside a git work tree' });
3735
+ };
3736
+ const outwardVerdict = outwardEntry === null ? null : (0, outward_acts_1.judgeOutward)(command, { cwd: shellBase, projectRoot: opts.projectRoot, readScripts, allScripts });
3737
+ // A-SPEC-794.82 — a command the judgement could not read whole is refused whatever the flags: its acts are unknown
3738
+ if (outwardEntry !== null && outwardVerdict !== null && outwardVerdict.unjudged !== undefined) {
3739
+ return { permissionDecision: 'deny', refusal: 'full-autonomy.refused', permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: a push or a publish is irreversible and outward, and this command could not be read whole — ${outwardVerdict.unjudged} — refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', 'the gate lets an outward act through only after reading the whole command')}` };
3740
+ }
3741
+ const outwardRoute = outwardEntry === null || outwardVerdict === null ? null : (0, full_autonomy_1.fullModeOutwardRefusal)(outwardVerdict.acts, outwardEntry);
3742
+ if (outwardRoute !== null && outwardVerdict !== null && outwardEntry !== null) {
3743
+ // the acts this profile leaves to the owner, each named with its clause, word, reason and rewrite
3744
+ const refused = outwardVerdict.findings.filter((f) => !outwardEntry.flags[f.act]);
3745
+ const acts = [...new Set(refused.map((f) => f.act))];
3746
+ // A-SPEC-794.87 — at most MAX_LISTED findings are listed, the rest counted
3747
+ const shown = [...new Set(refused.map(outward_acts_1.renderFinding))];
3748
+ const capped = shown.length > outward_acts_1.MAX_LISTED ? [...shown.slice(0, outward_acts_1.MAX_LISTED), `… and ${shown.length - outward_acts_1.MAX_LISTED} more`] : shown;
3749
+ const why = refused.length > 0 ? ` (${capped.join('; ')})` : '';
3750
+ // the prefix stays the refusal template's (A-SPEC-578.16); the act refused here follows it
3751
+ return { permissionDecision: 'deny', refusal: 'full-autonomy.refused', permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: a push or a publish is irreversible and outward — this command: a ${acts.join(' and a ') || 'push or a publish'}${why} — refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', outwardRoute)}` };
2515
3752
  }
2516
3753
  if (assessment.level === 'hard-hitl') {
2517
3754
  // @implements A-SPEC-245 — env first, then the grant files. The grant's mandatory nonce rides
@@ -2538,8 +3775,10 @@ function judgeHook(input, specsDir, opts) {
2538
3775
  // @implements A-SPEC-792.31 — the verdict is told where the spec store is
2539
3776
  const specsRel = path.relative(opts.projectRoot, specsDir).split(path.sep).join('/');
2540
3777
  // @implements A-SPEC-792.32 — one base (the shell's), and the stop lifted only by a caller's programmatic option
2541
- const verdict = auto.autonomousShellVerdict({ command, root: opts.projectRoot, shellStaging: (0, config_1.loadConfig)(opts.projectRoot).autonomy.shellStaging, specsRel,
2542
- base: shellBase, specStaging: opts.autonomySpecStaging === true }, auto.realShellDeps(opts.projectRoot));
3778
+ // @implements A-SPEC-794.86 — the R1 row from the config (on when absent)
3779
+ const autonomyCfg = (0, config_1.loadConfig)(opts.projectRoot).autonomy;
3780
+ const verdict = auto.autonomousShellVerdict({ command, root: opts.projectRoot, shellStaging: autonomyCfg.shellStaging, specsRel,
3781
+ base: shellBase, specStaging: opts.autonomySpecStaging === true, specRow: autonomyCfg.specStaging }, auto.realShellDeps(opts.projectRoot, specsRel));
2543
3782
  if (verdict.ok) {
2544
3783
  // @implements A-SPEC-792.32 — approved here, recorded at the final allow (every later Bash gate first), and
2545
3784
  // what is recorded is the verdict's proven (path, blob) pairs, computed from the bytes it proved
@@ -2718,6 +3957,113 @@ function judgeHook(input, specsDir, opts) {
2718
3957
  refusal: 'operator-act.refused', // A-SPEC-245.23 (item 3)
2719
3958
  };
2720
3959
  }
3960
+ // @implements A-SPEC-794.83 — an autonomy command run with an out-of-band variable the command itself sets: the
3961
+ // agent wrote that approval. Nothing is filed, so no config-write grant opens it (before, a person's grant of an
3962
+ // "environment read" ran the command with the agent's approval, which issued the profile); the same command
3963
+ // without the variable files its own request, which the person decides in the session form.
3964
+ // @implements A-SPEC-794.89 — the secret detector's own predicate (dumpsEnv), then the autonomy words over the text
3965
+ // with quotes, backslashes and line continuations removed and case folded: the narrower expression of 794.83 let
3966
+ // nine spellings through (a quoted name, an escaped `=`, `autonomy "full"`, an option first, capitals, an alias, read -r)
3967
+ if (dumpsEnv && runsAutonomyWidening(command)) {
3968
+ return {
3969
+ permissionDecision: 'deny',
3970
+ permissionDecisionReason: '[Holmes-Kit] the command runs an autonomy command with an out-of-band approval set in the command itself — an autonomy profile or grant is issued only through its own request, which the person decides in the session form: run the same command without setting the variable, and it files that request. No request was filed for this command.',
3971
+ refusal: 'profile.own-request',
3972
+ };
3973
+ }
3974
+ // @implements A-SPEC-794.95 (A-M1) — git writing a gate file from its store is a principle 7 write: each path it
3975
+ // reaches needs an open person-seal window naming it; a directory (or `.`) reaching the category, a dist path, or a
3976
+ // patch or stash that cannot be listed is refused in a repository that has principle 7 paths
3977
+ if (require('../governance/autonomy').isHolmesKitOwnRepo(opts.projectRoot)) { // A-SPEC-794.97 r4b (L5)
3978
+ // @implements A-SPEC-794.96 (S2, S3) — a commit or a build is judged against the working tree's principle 7 changes
3979
+ // A-SPEC-794.97 — against the live gate's baseline in the ledger, not HEAD: what a commit records and what a
3980
+ // build makes live are both "every principle 7 change since the baseline" (no staged-only reading, so staging in
3981
+ // the same command, a commit naming paths, or a commit made another way changes nothing)
3982
+ // A-SPEC-794.97 r4 (high-1, high-2) — replacement objects and a category file's index entries are refused
3983
+ const hidden = gitHiddenWriteOf(command, opts.projectRoot);
3984
+ if (hidden !== null) {
3985
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${hidden} (principle 7: the live gate's baseline and the changes since it are read from git's objects and index). Next: change the file itself and let Stop, the commit and the build judge it; a person seals an A-SPEC whose Files to Touch names it.` };
3986
+ }
3987
+ const act = commitOrBuildOf(command, opts.projectRoot);
3988
+ // A-SPEC-794.97 r5 (H1) — the judgement reads the tree before the command runs: a build after a git clause that moves
3989
+ // HEAD, the index or the working tree (pull, merge, checkout, switch, rebase, cherry-pick, am, revert, reset, stash,
3990
+ // restore, apply, commit) would make code nobody judged live; it is refused and records no baseline
3991
+ if (act === 'build-after-move') {
3992
+ // the refusal is gate.unjudgeable: the gate cannot judge the tree the build will compile, and a split command passes
3993
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: '[Holmes-Kit Gate Refusal] a shell command of a git step that changes the working tree and then a build: the gate judges the tree before the command runs, so the build would make code it did not judge the live gate (principle 7). Run the git step first, then run the build as its own command.' };
3994
+ }
3995
+ if (act !== null) {
3996
+ const p7 = require('../governance/autonomy');
3997
+ const v = p7.principle7Verdict(opts.projectRoot, readSpecsSync(specsDir), Date.parse(nowTs));
3998
+ // A-SPEC-794.97 r4b (M2) — what a window saw is recorded whether or not another file is unopened
3999
+ if (v !== null)
4000
+ p7.recordWindowBlobs(opts.projectRoot, nowTs, v);
4001
+ if (v !== null && v.unopened.length > 0) {
4002
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${act === 'build' ? 'this build would make the change the live gate' : 'this commit would record the change'} — ${p7.principle7RefusalText(v.unopened, v.base, { headSeen: v.headSeen, localOnly: v.localOnly })}` };
4003
+ }
4004
+ // condition 2 (supervisor) — with no baseline, a build records the first one only inside a person's window, so a
4005
+ // committed unsealed change cannot be laundered into the baseline; A-SPEC-794.97 r4 (medium-2): inside windows
4006
+ // that name every principle 7 file the commits since the oldest of them changed, not any window
4007
+ const gaps = v !== null && act === 'build' && !v.base.known ? p7.principle7FirstBaselineGaps(opts.projectRoot, v.ctx) : [];
4008
+ if (v !== null && gaps.length > 0) {
4009
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${v.base.commit.slice(0, 12)} — the live gate's baseline is unknown${v.base.recorded > 0 ? ' (the recorded baseline commit is not in this repository: garbage-collected, or another clone)' : ' (this ledger holds no baseline row: a new clone or worktree)'}, and the first one is recorded only by a build inside person-seal windows that name every principle 7 file changed since they opened (principle 7; not named: ${gaps.slice(0, 20).join(', ')}${gaps.length > 20 ? ` and ${gaps.length - 20} more` : ''}). `
4010
+ // A-SPEC-794.97 r4b (M4) — the remedy for the situation: the ledger that holds the row, or a person's seal
4011
+ + 'Next: commit or pull the ledger that holds the baseline row (the repository where the live gate was built), or a person seals the A-SPEC of the slice in the session form, then the build records the baseline.' };
4012
+ }
4013
+ if (v !== null && act === 'build')
4014
+ p7.recordBaseline(opts.projectRoot, nowTs);
4015
+ }
4016
+ const reached = gitStoreWrites(command, opts.projectRoot);
4017
+ if (reached !== null) {
4018
+ const p7 = require('../governance/autonomy');
4019
+ const opened = [];
4020
+ const why = (() => {
4021
+ if (reached === 'unreadable')
4022
+ return 'a patch or stash it applies cannot be listed';
4023
+ const rels = reached.map((raw) => path.posix.normalize(raw.replace(/\\/g, '/')).replace(/\/+$/, ''));
4024
+ // A-SPEC-794.97 (M4) — the ledger and the approvals store hold the baseline, the window records and the
4025
+ // grants: a patch never writes them
4026
+ const store = rels.find((rel) => /^\.ax\/(?:ledger|approvals)(?:\/|$)/.test(rel));
4027
+ if (store !== undefined)
4028
+ return `${store} is the governance store (the ledger or the approvals)`;
4029
+ // A-SPEC-794.96 (B-L1) — the paths first; specs are read only when one reaches the category
4030
+ if (!rels.some((rel) => p7.principle7WriteTarget(rel, { ownRepo: true }) !== null || rel === '.' || rel === '' || p7.isHighRiskPath(rel)))
4031
+ return null;
4032
+ const specsNow = readSpecsSync(specsDir);
4033
+ for (const rel of rels) {
4034
+ const target = p7.principle7WriteTarget(rel, { ownRepo: true });
4035
+ if (target === 'dist')
4036
+ return `${rel} is the build's`;
4037
+ if (target === null && (rel === '.' || rel === '' || p7.isHighRiskPath(rel)))
4038
+ return `${rel} is a directory reaching the gate category`;
4039
+ if (target === 'source') {
4040
+ const o = principle7Openers(opts.projectRoot, specsNow, nowTs, rel);
4041
+ if (o.openers.length === 0)
4042
+ return `${rel} is not named by an open person-seal window`;
4043
+ opened.push([rel, o]);
4044
+ }
4045
+ }
4046
+ return null;
4047
+ })();
4048
+ if (why === null)
4049
+ for (const [rel, o] of opened)
4050
+ recordWindowWrite(opts.projectRoot, nowTs, rel, o); // M-3
4051
+ if (why !== null) {
4052
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${why} — this git command writes a gate or approval-processing file from git's store (principle 7). `
4053
+ + 'A gate file is written only within a person-seal window of an A-SPEC whose Files to Touch names it; name the file there and have a person seal it, or leave the gate files out of the command.' };
4054
+ }
4055
+ }
4056
+ }
4057
+ // @implements A-SPEC-794.113 — the same subcommands behind any runner (the installer rule below reads the CLI as the
4058
+ // first word only), and `ledger rechain`
4059
+ if (!legacySessionApproval && (0, shell_argument_roles_1.installerInvocationOf)(command) === null && (0, shell_argument_roles_1.installerApplyIn)(command) === null) {
4060
+ const governed = governedCliAct(command);
4061
+ if (governed !== null) {
4062
+ return 'act' in governed
4063
+ ? { permissionDecision: 'deny', refusal: 'launch.refused', permissionDecisionReason: `[Holmes-Kit] ${governed.act}; it requires operator approval — the operator runs it from their own terminal, not the session (A-SPEC-794.113). Its --dry-run form shows what it would do.` }
4064
+ : { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: `[Holmes-Kit] the gate cannot read the holmes-kit words of this command — ${governed.unjudged} — so it is refused rather than judged (A-SPEC-794.113). Write the holmes-kit command out literally, or have the operator run it.` };
4065
+ }
4066
+ }
2721
4067
  const installerExact = legacySessionApproval ? null : (0, shell_argument_roles_1.installerInvocationOf)(command);
2722
4068
  const installerApply = legacySessionApproval ? null
2723
4069
  : installerExact === 'apply' ? command
@@ -3193,6 +4539,59 @@ function judgeHook(input, specsDir, opts) {
3193
4539
  if (computedWrite !== null && readSpecsSync(specsDir).length > 0) {
3194
4540
  return { permissionDecision: 'deny', refusal: 'shell.code-write', permissionDecisionReason: `${SHELL_CODE_WRITE_REASON} (its target is computed at run time: ${computedWrite}, A-SPEC-747.4)` };
3195
4541
  }
4542
+ // @implements A-SPEC-794.97 (M1) — a shell write's literal destinations are judged by principle 7 too, whatever their
4543
+ // extension (cp or echo > into a gate JSON table or .claude/ was allowed): dist/holmes is the build's, a gate file needs
4544
+ // an open person-seal window naming it
4545
+ if (require('../governance/autonomy').isHolmesKitOwnRepo(opts.projectRoot)) { // A-SPEC-794.97 r4b (L5)
4546
+ const p7 = require('../governance/autonomy');
4547
+ let specsP7 = null;
4548
+ for (const c of [...candidates, ...interpreterWrites.flatMap(expandInterp)]) {
4549
+ if (judgeCand(c, [opts.projectRoot]) !== 'in')
4550
+ continue;
4551
+ const rel = path.relative(opts.projectRoot, path.resolve(opts.projectRoot, judgedPath(c))).split(path.sep).join('/');
4552
+ const target = p7.principle7WriteTarget(rel, { ownRepo: true });
4553
+ if (target === null)
4554
+ continue;
4555
+ if (target === 'dist')
4556
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${rel}: ${p7.PRINCIPLE7_DIST_REFUSAL}.` };
4557
+ specsP7 ??= readSpecsSync(specsDir);
4558
+ if (principle7Openers(opts.projectRoot, specsP7, nowTs, rel).openers.length === 0) {
4559
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${rel}: ${p7.PRINCIPLE7_WRITE_REFUSAL} (principle 7; a shell write is judged as the file tools are).` };
4560
+ }
4561
+ }
4562
+ }
4563
+ // @implements A-SPEC-794.113 — what the reference judgements read is not written by the shell either: every literal
4564
+ // destination, and every path a clause moves, re-modes, cuts or links over, is judged where it lands. A source that
4565
+ // is only read (`cp .git/HEAD /tmp/x`, `cp -r .git /backup`) is not a destination and stays free; git's own
4566
+ // commands name no such destination.
4567
+ {
4568
+ // (a removal is a write here: deleting a playbook of the package handed its skill to another judge, and deleting
4569
+ // an object changes what git can answer — measured 11-12; `rm -f .git/index.lock` lands outside the store)
4570
+ const TOUCH_VERB = PLAIN ? (0, risk_classifier_1.verbWordRe)('mv|chmod|chown|chgrp|truncate|ln|rm|rmdir|unlink') : /\b(?:mv|chmod|chown|chgrp|truncate|ln|rm|rmdir|unlink)\b/;
4571
+ const touched = [];
4572
+ for (const seg of segments) {
4573
+ if (!TOUCH_VERB.test(seg.text))
4574
+ continue;
4575
+ for (const sub of seg.text.split(/[;|&]+/)) {
4576
+ if (!TOUCH_VERB.test(sub))
4577
+ continue;
4578
+ for (const raw of (0, dynamic_write_1.pathTokensOf)(sub))
4579
+ touched.push({ raw: raw.replace(/^['"]|['"]$/g, ''), base: seg.base });
4580
+ }
4581
+ }
4582
+ const judge = referenceInputJudge(opts.projectRoot);
4583
+ for (const c of [...candidates, ...touched, ...interpreterWrites.flatMap(expandInterp)]) {
4584
+ const absolute = (0, write_target_2.absoluteKindOf)(c.raw) !== null;
4585
+ // `~` is the user's home, where the runtime lives
4586
+ // a relative path after a cd the gate cannot resolve is judged from the root: refused when it spells the store
4587
+ // or the package from there (what it names from an unknown directory is a named limit)
4588
+ const abs = absolute ? c.raw : isTilde(c.raw) ? path.join(os.homedir(), c.raw.slice(1))
4589
+ : c.base === null ? c.raw : (0, write_target_2.pathFlavorFor)(c.base, c.raw).resolve(c.base, c.raw);
4590
+ const what = judge(abs);
4591
+ if (what !== null)
4592
+ return referenceInputDeny(c.raw, what);
4593
+ }
4594
+ }
3196
4595
  const codeList = distinct([...candidates, ...interpreterWrites.flatMap(expandInterp)].filter(governedCode));
3197
4596
  // Rule 43: only a governed project judges this list — an ungoverned one was refused for nothing it would check.
3198
4597
  if (codeList === null && readSpecsSync(specsDir).length > 0)
@@ -3430,6 +4829,13 @@ function judgeHook(input, specsDir, opts) {
3430
4829
  // so identity resolution, case folding and containment were all skipped on native Windows — the
3431
4830
  // very filesystem (NTFS) the case-folding comment below names.
3432
4831
  const absKind = (0, write_target_2.absoluteKindOf)(norm);
4832
+ // @implements A-SPEC-794.113 — what the reference judgements read is not written by the file tools: asked before the
4833
+ // "outside the project is free" answer below, because a deployed package and a linked worktree's store sit outside it
4834
+ if (absKind !== 'unc') {
4835
+ const what = referenceInputWrite(opts.projectRoot, norm);
4836
+ if (what !== null)
4837
+ return referenceInputDeny(norm, what);
4838
+ }
3433
4839
  if (absKind === 'unc') {
3434
4840
  // A network path has no local filesystem identity to resolve, so containment cannot be decided.
3435
4841
  // A-SPEC-191 §17/§29 both began as "the gate did not refuse to govern — it concluded there was
@@ -3832,6 +5238,13 @@ function judgeHook(input, specsDir, opts) {
3832
5238
  // code; interactively without strict the options change nothing but the owner's declared test folders.
3833
5239
  const writeClassify = (0, classification_mode_1.classifyOptionsFor)(opts.projectRoot, (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run);
3834
5240
  const action = (0, phase_1.classifyAction)(relPath, input.tool_input.content, writeClassify);
5241
+ // @implements A-SPEC-794.96 (B-H2) — principle 7 is judged whatever the classifier makes of the file: the gate's runtime
5242
+ // tables (guardrail/fixtures/*.json) and its wiring are not code, and left here without a window before
5243
+ if (action !== 'WRITE_CODE' && action !== 'WRITE_TEST') {
5244
+ const p7Verdict = principle7WriteVerdict(projectRoot, relPath, p, () => readSpecsSync(specsDir), nowTs);
5245
+ if (p7Verdict !== null)
5246
+ return p7Verdict;
5247
+ }
3835
5248
  if (!action) {
3836
5249
  // @implements A-SPEC-774 §2 — a write the classifier does not name is still a write. With no role policy it
3837
5250
  // stays free, as before; with one, the role must list WRITE_OTHER (a reviewer's NotebookEdit was allowed).
@@ -4310,6 +5723,14 @@ function judgeHook(input, specsDir, opts) {
4310
5723
  // code-write approval. Anchor deletion never blocks but rides the allow as a warning — silent
4311
5724
  // RTM loss is the C12 failure mode, made audible.
4312
5725
  const { judgeScope, fttPathTokens: fttTokens, matchesFtt } = require('../guardrail/scope-judgment');
5726
+ // @implements A-SPEC-794.91 (N2) — principle 7 binds the write, not only the seal: a gate or approval-processing file
5727
+ // has no tenure. It is written only under an approved A-SPEC a person sealed (the ledger's seal actor) whose Files to
5728
+ // Touch names it; dist/holmes/ is the build's alone. An environment code-write approval does not open it.
5729
+ {
5730
+ const p7Verdict = principle7WriteVerdict(projectRoot, relPath, p, () => specs, nowTs);
5731
+ if (p7Verdict !== null)
5732
+ return p7Verdict;
5733
+ }
4313
5734
  const { anchorSpecIds, stripStringLiterals } = require('../rtm/anchor-ids');
4314
5735
  const oldStr = input.tool_input.old_string ?? '';
4315
5736
  const newPayload = [input.tool_input.content ?? '', input.tool_input.new_string ?? ''].join('\n');
@@ -4368,12 +5789,11 @@ function judgeHook(input, specsDir, opts) {
4368
5789
  if (scopeVerdict.decision === 'admission-required' && !codeWriteCovered) { // @implements A-SPEC-133 — same code-write coverage as the stale gate
4369
5790
  // @implements A-SPEC-166.2 — remembered, so a following re-anchor to another spec is seen.
4370
5791
  (0, scope_refusal_memory_1.recordScopeRefusals)(projectRoot, relPath.replace(/\\/g, '/'), scopeVerdict.failedAdmissions.map((f) => f.id));
4371
- const failed = scopeVerdict.failedAdmissions
4372
- .map((f) => `${relPath} is anchored to ${f.id} but falls outside its 'Files to Touch' scope (${f.reason})`).join('; ');
4373
5792
  return {
4374
5793
  permissionDecision: 'deny',
4375
5794
  refusal: 'scope.outside', // A-SPEC-245.24
4376
- permissionDecisionReason: `[Holmes-Kit] ${failed} — extend that section first (spec edit is allowed), add it as a test under the anchored spec, or supply out-of-band approval`
5795
+ // A-SPEC-578.15 — the template lives in one place, so its readers produce it instead of copying it
5796
+ permissionDecisionReason: (0, anchor_scope_text_1.anchorScopeRefusal)(relPath, scopeVerdict.failedAdmissions)
4377
5797
  + (scopeWarnings ? `\n${scopeWarnings}` : ''),
4378
5798
  };
4379
5799
  }
@@ -4406,6 +5826,7 @@ function judgeHook(input, specsDir, opts) {
4406
5826
  // vouching for itself.
4407
5827
  declaredDigest: process.env.HOLMES_EVIDENCE?.trim() || null,
4408
5828
  currentHead: evidenceHead,
5829
+ ...(opts.advisory ? { advisory: opts.advisory } : {}),
4409
5830
  });
4410
5831
  if (evidenceDecision) {
4411
5832
  if (evidenceDecision.permissionDecision === 'allow')
@@ -4538,10 +5959,21 @@ if (require.main === module) {
4538
5959
  })();
4539
5960
  // @implements A-SPEC-245.4 — held through every pass below, settled once after the last one
4540
5961
  const settlement = new approval_grants_1.GrantSettlement();
5962
+ // @implements A-SPEC-333.2, A-SPEC-333.4 — the session reading these warnings; records wait for the final decision
5963
+ // below. Compression only where the compaction signal is observed (Claude Code); elsewhere only the ledger row.
5964
+ const rawFields = (rawHookInput !== null && typeof rawHookInput === 'object' ? rawHookInput : {});
5965
+ const advisoryHarness = (0, heartbeat_1.hookHarnessOf)(rawHookInput, process.env);
5966
+ const advisory = input.session_id
5967
+ ? { session: input.session_id, ...(input.agent_id ? { agent: input.agent_id } : {}), pending: [],
5968
+ compress: advisoryHarness === 'claude', harness: advisoryHarness ?? '', // A-SPEC-333.9 — the ledger names it
5969
+ ...(typeof rawFields.transcript_path === 'string' ? { transcriptPath: rawFields.transcript_path } : {}),
5970
+ ...(typeof rawFields.tool_use_id === 'string' ? { toolUseId: rawFields.tool_use_id } : {}) }
5971
+ : undefined;
4541
5972
  const judged = evaluateHook(input, specsDirWired, {
4542
5973
  projectRoot: hookProjectRoot,
4543
5974
  approval: readApprovalFromEnv(),
4544
5975
  settlement,
5976
+ ...(advisory ? { advisory } : {}),
4545
5977
  // Round 17: rm targets resolve from the directory the shell runs in (inside the project).
4546
5978
  resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
4547
5979
  resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
@@ -4562,9 +5994,13 @@ if (require.main === module) {
4562
5994
  tool: input.tool_name, toolInput: input.tool_input })
4563
5995
  : staged;
4564
5996
  // @implements A-SPEC-778 — in a run, refusals are logged and a repeated code stops the run; elsewhere unchanged.
4565
- const out = settleVerdict((hookRoot.anchored
5997
+ const settled = settleVerdict((hookRoot.anchored
4566
5998
  ? (0, run_refusals_1.applyRunRefusalStop)(roled, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id, tool: input.tool_name })
4567
5999
  : judged), settlement);
6000
+ // @implements A-SPEC-333.4 — an allowed `git commit` in a Claude session names the files still warned (information only)
6001
+ const reminder = advisory?.compress && settled.permissionDecision === 'allow' && input.tool_name === 'Bash'
6002
+ && (0, advisory_line_1.isGitCommit)(input.tool_input?.command ?? '') ? (0, advisory_line_1.commitReminder)(hookProjectRoot, advisory) : null;
6003
+ const out = reminder ? { ...settled, permissionDecisionReason: [settled.permissionDecisionReason, reminder].filter(Boolean).join('\n') } : settled;
4568
6004
  io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor(input.tool_name, out) }));
4569
6005
  // N3 provenance: record the audit-critical decision classes on the tamper-evident chain —
4570
6006
  // every DENY, and every ALLOW that was unlocked by an out-of-band approval. Fail-open: a
@@ -4589,6 +6025,8 @@ if (require.main === module) {
4589
6025
  // recorded as approved under a token that had expired in 2000. Under a session key that made
4590
6026
  // the whole log 'approved-action' and hid the real openings. Ask the counterfactual instead:
4591
6027
  // would this same call have been denied with no approval in hand?
6028
+ // A-SPEC-333.2, A-SPEC-333.4 — invariant: this re-ask never carries `advisory`. It reads no warning store and adds
6029
+ // nothing to `advisory.pending`, so only what the decision above said can be recorded below.
4592
6030
  const withoutApproval = out.permissionDecision === 'allow' && valid
4593
6031
  ? evaluateHook(input, specsDirWired, {
4594
6032
  projectRoot: hookProjectRoot,
@@ -4623,7 +6061,15 @@ if (require.main === module) {
4623
6061
  // @implements A-SPEC-133 — a master-key use becomes an audit line: the approval's
4624
6062
  // narrowing (or its absence) travels with the record (r7-191: promised, never shipped).
4625
6063
  inputs: [input.tool_name, target,
4626
- ...(acting ? [(0, provenance_chain_1.approvalMarkers)(acting)] : []), // one item, last position — the marker cannot split and self-contradict
6064
+ // one item — the marker cannot split and self-contradict; it rides only an unlocked allow, never a deny
6065
+ ...(acting ? [(0, provenance_chain_1.approvalMarkers)(acting)] : []),
6066
+ // @implements A-SPEC-578.15, A-SPEC-578.16 — a deny names its refusal kind and template inside the hashed
6067
+ // inputs (a new field would fail verification as smuggled data), so a report keys it by (code, template)
6068
+ // and never by its prose; they are a deny's last two items
6069
+ ...(out.permissionDecision === 'deny' ? [
6070
+ `code:${(0, refusal_codes_1.refusalFor)(out.permissionDecisionReason ?? '', out.refusal).code}`,
6071
+ `tpl:${(0, refusal_templates_1.refusalTemplate)(out.permissionDecisionReason ?? '')}`,
6072
+ ] : []),
4627
6073
  ].filter(Boolean),
4628
6074
  // round-9: a deny inherited the actor/rationale/authorization of an ambient approval that
4629
6075
  // did NOT cover it, so the audit line credited an authorizer who authorized nothing.
@@ -4635,6 +6081,12 @@ if (require.main === module) {
4635
6081
  }
4636
6082
  }
4637
6083
  catch { /* provenance must never break the gate */ }
6084
+ // @implements A-SPEC-333.2, A-SPEC-333.4 — the last act before the return: recorded only now, and only what this
6085
+ // allow actually carried (a deny records nothing)
6086
+ try {
6087
+ (0, advisory_line_1.commitAdvisory)(hookProjectRoot, advisory, out);
6088
+ }
6089
+ catch { /* an unrecorded warning is said again */ }
4638
6090
  if (out.permissionDecision === 'deny') {
4639
6091
  // Belt-and-suspenders: Claude Code's exit-code-2 contract feeds STDERR back to the
4640
6092
  // model as the block reason, while permissionDecisionReason in the stdout JSON is