@holmes-lab/holmes-kit 0.30.0 → 0.31.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 (136) hide show
  1. package/CHANGELOG.md +494 -0
  2. package/README.md +10 -1
  3. package/bin/holmes-hook-antigravity.js +4 -0
  4. package/bin/holmes-kit.js +4 -0
  5. package/bin/holmes-pre-push.js +3 -0
  6. package/bin/holmes-stop-antigravity.js +4 -0
  7. package/dist/.build-id +1 -1
  8. package/dist/holmes/cli/agents.d.ts +41 -0
  9. package/dist/holmes/cli/agents.js +382 -2
  10. package/dist/holmes/cli/attest.d.ts +2 -0
  11. package/dist/holmes/cli/attest.js +66 -15
  12. package/dist/holmes/cli/ci-gate.js +16 -1
  13. package/dist/holmes/cli/claude-switches.d.ts +95 -0
  14. package/dist/holmes/cli/claude-switches.js +967 -0
  15. package/dist/holmes/cli/codex-hooks.d.ts +77 -0
  16. package/dist/holmes/cli/codex-hooks.js +802 -0
  17. package/dist/holmes/cli/codex-oracle.d.ts +194 -0
  18. package/dist/holmes/cli/codex-oracle.js +1245 -0
  19. package/dist/holmes/cli/codex-toml.d.ts +35 -0
  20. package/dist/holmes/cli/codex-toml.js +321 -52
  21. package/dist/holmes/cli/doctor.d.ts +98 -8
  22. package/dist/holmes/cli/doctor.js +1328 -94
  23. package/dist/holmes/cli/index.js +23 -11
  24. package/dist/holmes/cli/init.d.ts +11 -0
  25. package/dist/holmes/cli/init.js +736 -44
  26. package/dist/holmes/cli/mcp-launcher.d.ts +64 -6
  27. package/dist/holmes/cli/mcp-launcher.js +189 -6
  28. package/dist/holmes/cli/mcp-version.js +13 -2
  29. package/dist/holmes/cli/settings-merge.js +8 -2
  30. package/dist/holmes/cli/upgrade.d.ts +13 -0
  31. package/dist/holmes/cli/upgrade.js +116 -23
  32. package/dist/holmes/cli/workspace-scope.d.ts +22 -0
  33. package/dist/holmes/cli/workspace-scope.js +375 -0
  34. package/dist/holmes/cpg/cpg-scanner.d.ts +29 -0
  35. package/dist/holmes/cpg/cpg-scanner.js +403 -3
  36. package/dist/holmes/cpg/cycle-detect.js +2 -1
  37. package/dist/holmes/cpg/forbidden-edges.js +9 -2
  38. package/dist/holmes/cpg/required-calls.js +8 -1
  39. package/dist/holmes/governance/constitution-debt.js +3 -2
  40. package/dist/holmes/governance/constitution.js +15 -3
  41. package/dist/holmes/governance/provenance-chain.js +3 -2
  42. package/dist/holmes/governance/push-gate-runner.js +4 -3
  43. package/dist/holmes/guardrail/dependency-delta.js +4 -3
  44. package/dist/holmes/guardrail/linear-match.d.ts +57 -0
  45. package/dist/holmes/guardrail/linear-match.js +256 -0
  46. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -7
  47. package/dist/holmes/guardrail/risk-classifier.js +931 -44
  48. package/dist/holmes/guardrail/risk-types.d.ts +6 -0
  49. package/dist/holmes/guardrail/scope-judgment.d.ts +4 -24
  50. package/dist/holmes/guardrail/scope-judgment.js +100 -23
  51. package/dist/holmes/guardrail/shell-words.d.ts +42 -0
  52. package/dist/holmes/guardrail/shell-words.js +1720 -0
  53. package/dist/holmes/guardrail/write-target.d.ts +168 -3
  54. package/dist/holmes/guardrail/write-target.js +2379 -87
  55. package/dist/holmes/hooks/adapters/antigravity.d.ts +3 -1
  56. package/dist/holmes/hooks/adapters/antigravity.js +115 -11
  57. package/dist/holmes/hooks/pre-tool-use.d.ts +32 -6
  58. package/dist/holmes/hooks/pre-tool-use.js +923 -87
  59. package/dist/holmes/hooks/rtm-refresh-child.js +3 -1
  60. package/dist/holmes/hooks/rtm-refresh.js +8 -4
  61. package/dist/holmes/hooks/session-start.d.ts +10 -0
  62. package/dist/holmes/hooks/session-start.js +31 -7
  63. package/dist/holmes/hooks/stop.d.ts +2 -1
  64. package/dist/holmes/hooks/stop.js +197 -91
  65. package/dist/holmes/mcp/approval-commit.d.ts +5 -6
  66. package/dist/holmes/mcp/approval-commit.js +18 -2
  67. package/dist/holmes/mcp/elicit-approval.js +4 -2
  68. package/dist/holmes/mcp/handlers/graph-operations.js +3 -2
  69. package/dist/holmes/mcp/handlers/maintenance-analysis.js +11 -5
  70. package/dist/holmes/mcp/handlers/maintenance-evidence.js +3 -2
  71. package/dist/holmes/mcp/handlers/phase-queries.d.ts +22 -7
  72. package/dist/holmes/mcp/handlers/phase-queries.js +81 -2
  73. package/dist/holmes/mcp/handlers/requirement-triage.js +5 -3
  74. package/dist/holmes/mcp/handlers/review-evidence.js +8 -2
  75. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +11 -0
  76. package/dist/holmes/mcp/handlers/slice-orchestration.js +115 -16
  77. package/dist/holmes/mcp/handlers/spec-approval.d.ts +9 -0
  78. package/dist/holmes/mcp/handlers/spec-approval.js +110 -17
  79. package/dist/holmes/mcp/handlers/spec-authoring.js +17 -2
  80. package/dist/holmes/mcp/handlers/spec-queries.d.ts +39 -3
  81. package/dist/holmes/mcp/handlers/spec-queries.js +114 -7
  82. package/dist/holmes/mcp/handlers/test-execution.js +9 -3
  83. package/dist/holmes/mcp/handlers.d.ts +81 -9
  84. package/dist/holmes/mcp/handlers.js +70 -23
  85. package/dist/holmes/mcp/harness-attestation.d.ts +20 -0
  86. package/dist/holmes/mcp/harness-attestation.js +179 -0
  87. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +36 -0
  88. package/dist/holmes/mcp/requirement-triage-evidence.js +160 -4
  89. package/dist/holmes/mcp/server.js +20 -1
  90. package/dist/holmes/mcp/tool-schemas.js +26 -9
  91. package/dist/holmes/mcp/validate-args.js +12 -0
  92. package/dist/holmes/project/bounded-io.d.ts +102 -0
  93. package/dist/holmes/project/bounded-io.js +212 -0
  94. package/dist/holmes/project/change-source.js +3 -1
  95. package/dist/holmes/project/ci-runs.js +3 -2
  96. package/dist/holmes/project/ignore.d.ts +31 -2
  97. package/dist/holmes/project/ignore.js +409 -50
  98. package/dist/holmes/project/regular-file-guard.d.ts +13 -0
  99. package/dist/holmes/project/regular-file-guard.js +149 -0
  100. package/dist/holmes/project/root.js +12 -3
  101. package/dist/holmes/reverse/anchor.js +4 -3
  102. package/dist/holmes/reverse/scan.js +6 -2
  103. package/dist/holmes/review/commit-text.js +3 -2
  104. package/dist/holmes/review/condition-hunk-replay.js +3 -2
  105. package/dist/holmes/review/failed-test-names.js +13 -10
  106. package/dist/holmes/review/findings.js +3 -1
  107. package/dist/holmes/review/kills-check.js +6 -1
  108. package/dist/holmes/review/point-in-time-replay.js +5 -4
  109. package/dist/holmes/review/replay-corpus.js +5 -4
  110. package/dist/holmes/review/run-replay.js +3 -2
  111. package/dist/holmes/review/temporal-prior.js +3 -2
  112. package/dist/holmes/review/test-evidence.js +3 -2
  113. package/dist/holmes/review/test-outcomes.js +3 -2
  114. package/dist/holmes/review/test-runner.d.ts +6 -0
  115. package/dist/holmes/review/test-runner.js +36 -15
  116. package/dist/holmes/rtm/advisory-outcomes.js +3 -2
  117. package/dist/holmes/rtm/anchor-ids.js +42 -2
  118. package/dist/holmes/rtm/file-anchors.js +4 -1
  119. package/dist/holmes/rtm/ftt-fulfilment.js +8 -3
  120. package/dist/holmes/rtm/git-changes.js +3 -1
  121. package/dist/holmes/rtm/graph-store.js +3 -2
  122. package/dist/holmes/rtm/test-scope.js +9 -4
  123. package/dist/holmes/spec/compat-impact.d.ts +25 -4
  124. package/dist/holmes/spec/compat-impact.js +682 -11
  125. package/dist/holmes/spec/entity-git-snapshot.js +3 -2
  126. package/dist/holmes/spec/entity-integration.js +3 -2
  127. package/dist/holmes/spec/entity-renumber-transaction.d.ts +19 -0
  128. package/dist/holmes/spec/entity-renumber-transaction.js +79 -6
  129. package/dist/holmes/spec/remote-spec-refs.js +3 -2
  130. package/dist/holmes/spec/renumber.js +25 -10
  131. package/dist/holmes/spec/spec-parser.js +9 -3
  132. package/dist/holmes/spec/yaml-scalar.js +2 -2
  133. package/dist/holmes/update/refresh.js +3 -1
  134. package/dist/holmes/update/update-notice.d.ts +6 -0
  135. package/dist/holmes/update/update-notice.js +18 -1
  136. package/package.json +11 -4
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DEFAULT_SPECS_DIR = void 0;
37
37
  exports.resolveRmSignals = resolveRmSignals;
38
38
  exports.readApprovalFromEnv = readApprovalFromEnv;
39
+ exports.hookOutputFor = hookOutputFor;
39
40
  exports.dumpsEnvInCommandPosition = dumpsEnvInCommandPosition;
40
41
  exports.normalizeHookInput = normalizeHookInput;
41
42
  exports.preEditEvidenceGate = preEditEvidenceGate;
@@ -45,7 +46,7 @@ exports.gateErrorDecision = gateErrorDecision;
45
46
  exports.wiredSpecsDir = wiredSpecsDir;
46
47
  exports.evaluateHook = evaluateHook;
47
48
  exports.readSpecsSync = readSpecsSync;
48
- // @implements A-SPEC-278
49
+ // @implements A-SPEC-278, A-SPEC-733, A-SPEC-734
49
50
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
50
51
  // evaluateHook in this file to prove it.
51
52
  // @implements A-SPEC-643
@@ -80,9 +81,12 @@ const provenance_chain_1 = require("../governance/provenance-chain");
80
81
  const ledger_store_2 = require("../governance/ledger-store");
81
82
  const risk_gate_1 = require("../guardrail/risk-gate");
82
83
  const approval_queue_1 = require("../governance/approval-queue");
84
+ const shell_words_1 = require("../guardrail/shell-words");
85
+ const linear_match_1 = require("../guardrail/linear-match");
83
86
  const approval_grants_1 = require("../governance/approval-grants");
84
87
  const approval_blockers_1 = require("../spec/approval-blockers");
85
88
  const impact_gate_1 = require("../guardrail/impact-gate");
89
+ const bounded_io_1 = require("../project/bounded-io");
86
90
  // Resolve per-rm-target git facts (H1 git-aware guardrail): is each recursive-rm target a
87
91
  // regenerable build artifact (gitignored), version-controlled source (tracked), or escaping the
88
92
  // project? This is the I/O half — the classifier stays pure and merely consumes these signals.
@@ -94,8 +98,25 @@ const impact_gate_1 = require("../guardrail/impact-gate");
94
98
  // FAIL-OPEN and shell-injection-safe: uses execFileSync (arg arrays, no shell); any failure (not a
95
99
  // git repo, git missing, odd target) yields no signal for that target. Metachar/tilde targets are
96
100
  // skipped (the classifier's catastrophic floor handles them and they must never reach a subprocess).
97
- function resolveRmSignals(command, cwd) {
98
- const targets = (0, risk_classifier_1.rmCommandTargets)(command);
101
+ /**
102
+ * @implements A-SPEC-734 (round 14) — git did not answer (a timeout, a blocked root): every `rm` target that could
103
+ * reach a subprocess is judged tracked and in the project, the stricter answer. The static fallback read that as
104
+ * "not a repository" and allowed `rm -r <tracked dir>` with an empty reason (measured: a slow `core.fsmonitor`,
105
+ * an `include.path` FIFO).
106
+ */
107
+ function unanswered(targets) {
108
+ const out = {};
109
+ for (const raw of targets) {
110
+ const unq = raw.replace(/^["']/, '').replace(/["']$/, '');
111
+ if (!unq || unq.startsWith('~') || /[^A-Za-z0-9._/-]/.test(unq))
112
+ continue;
113
+ out[raw] = { gitIgnored: false, tracked: true, inProject: true };
114
+ }
115
+ return Object.keys(out).length ? out : undefined;
116
+ }
117
+ function resolveRmSignals(command, cwd, projectRoot, specsDir) {
118
+ // A-SPEC-728 (round 24): the text as the shell joins it (`r\m -rf .git`, `eval rm\ -rf\ src`).
119
+ const targets = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_1.joinShellText)(command))])];
99
120
  if (targets.length === 0)
100
121
  return undefined;
101
122
  let repoRoot;
@@ -106,41 +127,210 @@ function resolveRmSignals(command, cwd) {
106
127
  // comparisons below never matched `C:/…` against `C:\…`. Measured 2026-08-23: `rm -rf build`
107
128
  // in a real repo read as inProject=false, so a gitignored build dir was escalated as if it were
108
129
  // outside the project — fail-safe in direction, wrong in fact, and a needless HITL every time.
109
- repoRoot = (0, root_1.canonicalPath)((0, node_child_process_1.execFileSync)('git', ['rev-parse', '--show-toplevel'], { cwd, stdio: ['ignore', 'pipe', 'ignore'], env: (0, root_1.cleanSubprocessEnv)() })
130
+ // A-SPEC-734 (round 12): a root whose git timed out is not asked again (shared memory).
131
+ // A-SPEC-734 (round 14): and a git that did not answer is not "no repository" — see `unanswered`.
132
+ if ((0, bounded_io_1.gitRootBlocked)(cwd, 'repo'))
133
+ return unanswered(targets);
134
+ repoRoot = (0, root_1.canonicalPath)((0, node_child_process_1.execFileSync)('git', ['rev-parse', '--show-toplevel'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, cwd, stdio: ['ignore', 'pipe', 'pipe'], env: (0, root_1.cleanSubprocessEnv)() })
110
135
  .toString().trim());
111
136
  baseReal = (0, root_1.canonicalPath)(cwd);
112
137
  }
113
- catch {
138
+ catch (e) {
139
+ (0, bounded_io_1.noteGitFailure)(cwd, e, 'repo');
140
+ // A-SPEC-734 (round 15): only a git that SAYS "not a git repository" (or no git) is the static fallback; a refusal
141
+ // inside a repository (dubious ownership, an unknown extension, a corrupt index) is "did not answer" (measured:
142
+ // `rm -r src` was allowed with an empty reason).
143
+ if ((0, bounded_io_1.gitAnswerOf)(e, cwd) === 'unanswered')
144
+ return unanswered(targets);
114
145
  return undefined; // not a git repo / git unavailable -> static fallback
115
146
  }
116
- const signals = {};
147
+ // @implements A-SPEC-728 (round 7) — two git processes PER target let 1,300 targets (6.7 KB) take
148
+ // 35 s, past the hook timeout (measured). Targets are de-duplicated; ignored status comes from ONE
149
+ // `check-ignore --stdin -z`, tracked status from ONE listing of the repository.
150
+ const judged = new Map(); // raw → unquoted
117
151
  for (const raw of targets) {
152
+ if (judged.has(raw))
153
+ continue;
118
154
  const unq = raw.replace(/^["']/, '').replace(/["']$/, '');
119
155
  if (!unq || unq.startsWith('~') || /[^A-Za-z0-9._/-]/.test(unq))
120
156
  continue; // floor handles these; never shell them
121
- let resolved = path.resolve(baseReal, unq);
122
- // Resolve symlinks on the real target so a lexically-in-project path that SYMLINKS outside the
123
- // repo (e.g. `rm -rf link` where link -> /etc) is correctly seen as escaping (inProject=false →
124
- // dangerous). path.resolve alone is lexical and would be fooled. Non-existent targets keep the
125
- // lexical path (nothing to delete yet); realpath errors fail safe to the lexical value.
157
+ // Round 8: git is not asked about a target no real path can be (PATH_MAX, component count) — one
158
+ // deep target against `**/…` ignore rules took 57 s (measured); such a target keeps no signal.
159
+ if (unq.length > 4096 || unq.split('/').length > 256)
160
+ continue;
161
+ judged.set(raw, unq);
162
+ }
163
+ if (judged.size === 0)
164
+ return undefined;
165
+ const unqs = [...new Set(judged.values())];
166
+ const ignored = new Set();
167
+ try {
168
+ // Round 8: bounded — a timeout reads as "not ignored", the stricter answer.
169
+ // A-SPEC-734 (round 14): through the per-kind memory (it waited a second time — measured).
170
+ const r = (0, bounded_io_1.gitOnce)(repoRoot, ['check-ignore', '--stdin', '-z'], 'worktree', { cwd, input: unqs.join('\0') + '\0', env: (0, root_1.cleanSubprocessEnv)() });
171
+ for (const p of (r.stdout ?? '').split('\0'))
172
+ if (p !== '')
173
+ ignored.add(p);
174
+ }
175
+ catch { /* no signal */ }
176
+ let listed = null;
177
+ // A-SPEC-734 (round 14): an index read with the fsmonitor hook off; a listing git did not give in time is
178
+ // unknown, and an unknown in-project target is judged tracked — `rm -r <tracked dir>` was allowed silently
179
+ // under a slow fsmonitor (measured).
180
+ let listedUnknown = false;
181
+ try {
182
+ const r = (0, bounded_io_1.gitOnce)(repoRoot, ['-c', 'core.fsmonitor=false', 'ls-files', '-z', '--full-name'], 'repo', { env: (0, root_1.cleanSubprocessEnv)() });
183
+ if (r.status === 0)
184
+ listed = r.stdout.split('\0').filter((p) => p !== '');
185
+ else
186
+ listedUnknown = (0, bounded_io_1.gitUnanswered)(r, repoRoot);
187
+ }
188
+ catch {
189
+ listed = null;
190
+ }
191
+ // @implements A-SPEC-734 (round 17) — tracked lookups compare NFC and upper-case folded paths (an NFD project
192
+ // directory made tracked `src` untracked — measured); folding only ever makes more targets tracked.
193
+ const fold = (p) => p.normalize('NFC').toUpperCase();
194
+ const nfc = (p) => p.normalize('NFC');
195
+ // @implements A-SPEC-734 (round 16/17) — a signal that makes the verdict STRICTER (tracked, outside the repository)
196
+ // is taken from whichever repository answers; the one that RELAXES it (ignored ⇒ regenerable) only from the
197
+ // repository that tracks a file under this project's spec directory. Round 16 dropped every signal of a repository
198
+ // that tracked nothing under the project: a shell inside a submodule under the project lost `tracked`, and one
199
+ // force-added `.envrc` under a parent ignoring `*` restored "ignored ⇒ safe" (both allowed — measured).
200
+ let trustIgnored = projectRoot === undefined;
201
+ if (projectRoot !== undefined && listed !== null) {
126
202
  try {
127
- if (fs.existsSync(resolved))
128
- resolved = (0, root_1.canonicalPath)(resolved);
203
+ const specs = (0, root_1.canonicalPath)(specsDir ?? path.join(projectRoot, exports.DEFAULT_SPECS_DIR));
204
+ const specsRel = fold(path.relative(nfc(repoRoot), nfc(specs)).split(path.sep).join('/'));
205
+ if (specsRel !== '' && specsRel !== '..' && !specsRel.startsWith('../') && !path.isAbsolute(specsRel))
206
+ trustIgnored = listed.some((f) => fold(f).startsWith(specsRel + '/'));
129
207
  }
130
- catch { /* keep lexical */ }
131
- const inProject = resolved === repoRoot || resolved.startsWith(repoRoot + path.sep);
132
- let gitIgnored = false;
133
- let tracked = false;
134
- try {
135
- (0, node_child_process_1.execFileSync)('git', ['check-ignore', '-q', '--', unq], { cwd, stdio: 'ignore', env: (0, root_1.cleanSubprocessEnv)() });
136
- gitIgnored = true;
208
+ catch {
209
+ trustIgnored = false;
137
210
  }
138
- catch { /* exit!=0 -> not ignored/unknown */ }
139
- try {
140
- (0, node_child_process_1.execFileSync)('git', ['ls-files', '--error-unmatch', '--', unq], { cwd, stdio: 'ignore', env: (0, root_1.cleanSubprocessEnv)() });
141
- tracked = true;
211
+ }
212
+ const trackedSet = new Set((listed ?? []).map(fold));
213
+ const trackedDirs = new Set();
214
+ for (const f of trackedSet) {
215
+ let i = f.lastIndexOf('/');
216
+ while (i > 0) {
217
+ const d = f.slice(0, i);
218
+ if (trackedDirs.has(d))
219
+ break;
220
+ trackedDirs.add(d);
221
+ i = f.lastIndexOf('/', i - 1);
142
222
  }
143
- catch { /* not tracked */ }
223
+ }
224
+ /** A tracked entry at an ancestor of `rel` is a gitlink (a file has no children): the target is a submodule's. */
225
+ const underGitlink = (rel) => { let i = rel.lastIndexOf('/'); while (i > 0) {
226
+ if (trackedSet.has(rel.slice(0, i)))
227
+ return true;
228
+ i = rel.lastIndexOf('/', i - 1);
229
+ } return false; };
230
+ const signals = {};
231
+ // @implements A-SPEC-734 (round 17) — a relative target is judged from every directory the command may run any part
232
+ // in (`commandBases`, flow-insensitive: loops, functions and traps run text later — measured), tracked in the project
233
+ // when that set is unknown. Round 18's per-segment bases missed those and forced "tracked" on every segment the model
234
+ // could not place (9 of 15 ordinary cleanups denied — measured).
235
+ const cb = (0, write_target_1.commandBases)(command, baseReal);
236
+ // @implements A-SPEC-734 (round 20) — straight-line text runs where it is written: each segment naming the target keeps
237
+ // its own base (a segment the model cannot place: its candidates and the start), so a `cd ..` written after the removal
238
+ // does not move it (`rm -rf build; cd ..` was refused as out-of-project — measured). A command that can run text later
239
+ // or again (loops, functions, traps, eval, source, `-c` programs, expanded command words) uses the whole set.
240
+ // @implements A-SPEC-734 (round 21) — a segment the model places with certainty keeps that directory; one it cannot place
241
+ // is judged from the whole set. Round 20 judged it from the start and its candidates, which miss what the model could
242
+ // not read (`` cd `echo src` ``, zsh `pushd -q`/`repeat`, braceless functions — 15 of 44 cd shapes deleted tracked
243
+ // source, measured).
244
+ // @implements A-SPEC-734 (round 22) — for an ordered command, "the whole set" of an unplaced segment is what the cds
245
+ // written before it can reach, in order: the flow-insensitive closure applied a later `cd ..` to the start and refused
246
+ // `cd web && npm ci && cd .. && rm -rf build` as out-of-project (measured). Past 2,000 segments, or once the reach is
247
+ // unknown, the flow-insensitive set.
248
+ const segmentBases = new Map();
249
+ if (cb.ordered && cb.unknown === null) {
250
+ const segs = (0, write_target_1.shellSegments)(command, baseReal);
251
+ let reach = segs.length > 2000 ? null : [baseReal];
252
+ // Round 23: inside an `&&` chain a cd that fails stops the chain, so its successors see only where it leads; where the
253
+ // chain breaks (`;`, `||`, a newline) every state the chain passed through is possible again.
254
+ let chain = new Set(reach ?? []);
255
+ for (const seg of segs) {
256
+ const current = seg.base !== null ? [seg.base] : reach === null ? cb.bases : [...new Set([...reach, ...(seg.maybe ?? [])])];
257
+ for (const t of (0, risk_classifier_1.rmCommandTargets)(seg.text)) {
258
+ const key = t.replace(/^["']/, '').replace(/["']$/, '');
259
+ segmentBases.set(key, [...new Set([...(segmentBases.get(key) ?? []), ...current])]);
260
+ }
261
+ if (reach === null)
262
+ continue;
263
+ // @implements A-SPEC-734 (round 23) — the reach moves from a certain base or from itself, never from the model's
264
+ // candidates, which always hold the start (a `cd ../..` applied to it left the project — measured).
265
+ const from = seg.base !== null ? [seg.base] : reach;
266
+ const isCd = /(?:^|[^\w.-])(?:cd|chdir|pushd|popd)(?![\w.-])/.test(seg.text);
267
+ const andNext = seg.sep === '&&';
268
+ if (!isCd)
269
+ reach = from;
270
+ else {
271
+ const next = new Set(andNext ? [] : from);
272
+ for (const b of from) {
273
+ const r = (0, write_target_1.commandBases)(seg.text, b);
274
+ if (r.unknown !== null) {
275
+ reach = null;
276
+ break;
277
+ }
278
+ for (const x of r.bases)
279
+ if (!andNext || x !== b || r.bases.length === 1)
280
+ next.add(x);
281
+ if (next.size > 64) {
282
+ reach = null;
283
+ break;
284
+ }
285
+ }
286
+ if (reach !== null)
287
+ reach = [...(next.size > 0 ? next : new Set(from))];
288
+ }
289
+ if (reach === null)
290
+ continue;
291
+ for (const x of reach)
292
+ chain.add(x);
293
+ if (!andNext) {
294
+ reach = [...chain];
295
+ chain = new Set(reach);
296
+ }
297
+ }
298
+ }
299
+ for (const [raw, unq] of judged) {
300
+ const narrowed = segmentBases.get(unq);
301
+ const from = path.isAbsolute(unq) ? [baseReal] : cb.unknown !== null ? null : narrowed ?? cb.bases;
302
+ if (from === null) {
303
+ signals[raw] = { gitIgnored: false, tracked: true, inProject: true };
304
+ continue;
305
+ }
306
+ let tracked = false;
307
+ let inProject = true;
308
+ for (const b of from) {
309
+ let resolved = path.resolve(b, unq);
310
+ // Resolve symlinks on the real target so a lexically-in-project path that SYMLINKS outside the
311
+ // repo (e.g. `rm -rf link` where link -> /etc) is correctly seen as escaping (inProject=false →
312
+ // dangerous). path.resolve alone is lexical and would be fooled. Non-existent targets keep the
313
+ // lexical path (nothing to delete yet); realpath errors fail safe to the lexical value.
314
+ try {
315
+ if (fs.existsSync(resolved))
316
+ resolved = (0, root_1.canonicalPath)(resolved);
317
+ }
318
+ catch { /* keep lexical */ }
319
+ const inside = nfc(resolved) === nfc(repoRoot) || nfc(resolved).startsWith(nfc(repoRoot) + path.sep);
320
+ // Tracked = the pathspec names a tracked file, or a directory holding one (--error-unmatch's answer).
321
+ // Lexical from the canonical base (a missing target has no real path; git's pathspec is lexical too).
322
+ // Round 17: the lexical spelling from the segment's base, and the real path (an untracked link `s -> src` made
323
+ // `rm -r s/lib` untracked — measured); tracked by either is tracked.
324
+ const fromRoot = fold(path.relative(nfc(repoRoot), nfc(path.resolve(b, unq))).split(path.sep).join('/'));
325
+ const fromReal = fold(path.relative(nfc(repoRoot), nfc(resolved)).split(path.sep).join('/'));
326
+ const isTracked = (rel) => rel !== '' && !rel.startsWith('..') && (trackedSet.has(rel) || trackedDirs.has(rel) || underGitlink(rel));
327
+ if (listedUnknown ? inside : listed !== null && (isTracked(fromRoot) || isTracked(fromReal)))
328
+ tracked = true;
329
+ if (!inside)
330
+ inProject = false;
331
+ }
332
+ // git's ignore answer was asked from the session base only: it counts when every segment naming the target runs there.
333
+ const gitIgnored = trustIgnored && from.length === 1 && from[0] === baseReal && (ignored.has(unq) || ignored.has((0, linear_match_1.trimTrailing)(unq, '/')));
144
334
  signals[raw] = { gitIgnored, tracked, inProject };
145
335
  }
146
336
  return Object.keys(signals).length ? signals : undefined;
@@ -174,11 +364,344 @@ function readApprovalFromEnv() {
174
364
  * stripped of leading assignments/wrappers and, for a nested shell, its `-c` body is re-examined.
175
365
  * `env FOO=1 cmd` is a RUNNER (assignment then command), not a dump.
176
366
  */
367
+ // @implements A-SPEC-732 (round 2) — commands that start the Holmes MCP server or load its handlers.
368
+ // Round 4: the `server`/`handlers` tail is that MODULE only (`handlers.test.js` is a test run —
369
+ // measured false denial), and a command word that is a path ending in holmes-mcp is a start
370
+ // (`./bin/holmes-mcp.js`, `node_modules/.bin/holmes-mcp` — measured bypass).
371
+ const HOLMES_SERVER_TAIL = /\bholmes-mcp\b|dist[\\/]+holmes[\\/]+mcp[\\/]+(?:server|handlers)(?:\.js)?(?![\w.-])/;
372
+ const SERVER_RUNNERS = [
373
+ (0, linear_match_1.headThenTail)(/(?:^|[\s;&|(])(?:exec\s+)?(?:node|nodejs|bun|deno|tsx|ts-node)\b/, /[;&|\n]/, HOLMES_SERVER_TAIL),
374
+ (0, linear_match_1.headThenTail)(/\b(?:npx|pnpx|bunx|npm\s+(?:exec|x)|pnpm\s+(?:exec|dlx)|yarn\s+dlx)\b/, /[;&|\n]/, /\bholmes-mcp\b/),
375
+ // Round 6: the package itself, by name (`node node_modules/@holmes-lab/holmes-kit`, `require('@holmes-lab/holmes-kit')`).
376
+ (0, linear_match_1.headThenTail)(/(?:^|[\s;&|(])(?:exec\s+)?(?:node|nodejs|bun|deno|tsx|ts-node)\b/, /[;&|\n]/, /@holmes-lab\/holmes-kit(?:\/(?:bin\/holmes-mcp(?:\.js)?|dist\/holmes\/mcp\/(?:server|handlers)(?:\.js)?))?(?![\w.-]|\/[\w.-])/),
377
+ // Round 5 (measured): `yarn holmes-mcp`, `pnpm run holmes-mcp` — package-manager script runners.
378
+ (0, linear_match_1.headThenTail)(/(?:^|[\s;&|(])(?:yarn|pnpm|npm\s+run)\b/, /[;&|\n]/, /^\s*(?:run\s+)?holmes-mcp(?=$|[\s;&|)])/),
379
+ (0, linear_match_1.headThenTail)(/(?:^|[;&|(])\s*/, /[;&|\n]/, /^(?:exec\s+)?(?:[^\s;&|()]*[\\/])?holmes-mcp(?:\.js)?(?=$|[\s;&|)])/),
380
+ ];
381
+ /** A local module run: `node server.js`, `node ./handlers` — used only after a `cd` into the server's directory. */
382
+ const LOCAL_SERVER_RUN = /(?:^|[\s;&|(])(?:exec\s+)?(?:node|nodejs|bun|deno|tsx|ts-node)\s+(?:\.\/)?(?:server|handlers)(?:\.js)?(?=$|[\s;&|)])/;
383
+ /**
384
+ * @implements A-SPEC-732 (round 5) — the command as a shell would resolve its words: quotes and
385
+ * backslash escapes removed, `.`/`..` path segments resolved, case folded (macOS paths are
386
+ * case-insensitive). Measured allowed before: `dist/holmes/mcp/./server.js`, `dist/holmes/../holmes/
387
+ * mcp/server.js`, `DIST/…`, a quoted command word, `holmes\-mcp`. Linear: one pass per word.
388
+ */
389
+ function normalizedCommand(command) {
390
+ return command.replace(/\\(.)/g, '$1').replace(/["']/g, '').toLowerCase().split(/(\s+)/).map((word) => {
391
+ if (!word.includes('/'))
392
+ return word;
393
+ const out = [];
394
+ for (const seg of word.split('/')) {
395
+ if (seg === '.' && out.length > 0)
396
+ continue;
397
+ if (seg === '..' && out.length > 0 && out[out.length - 1] !== '..' && out[out.length - 1] !== '' && out[out.length - 1] !== '.') {
398
+ out.pop();
399
+ continue;
400
+ }
401
+ out.push(seg);
402
+ }
403
+ return out.join('/');
404
+ }).join('');
405
+ }
406
+ /** `cd <…holmes/mcp> && node server.js` on one line: the first such `cd`, then one test of the rest. */
407
+ function cdIntoServerDir(normalized) {
408
+ // Round 6: the whole command (a `cd` on one line, the start on the next), `pushd`, `cd --`, and any
409
+ // run of blanks after the verb (an 8-character look-back missed 9 spaces — measured).
410
+ const line = normalized;
411
+ // Wave 4 (measured): a backward lastIndexOf per occurrence was quadratic on one long word (220 KB:
412
+ // 2.6 s). The word start moves forward with the occurrences — one pass.
413
+ let wordStart = 0;
414
+ // The last two complete words before the current one, as [start, end) — kept as we scan forward.
415
+ let w1 = null;
416
+ let w2 = null;
417
+ let scanned = 0;
418
+ let at = line.indexOf('holmes/mcp');
419
+ while (at !== -1) {
420
+ for (; scanned < at; scanned++) {
421
+ const c = line[scanned];
422
+ if (c === ' ' || c === '\t' || c === '\n') {
423
+ if (scanned > wordStart) {
424
+ w2 = w1;
425
+ w1 = [wordStart, scanned];
426
+ }
427
+ wordStart = scanned + 1;
428
+ }
429
+ }
430
+ // The word before the path (skipping a `--`) must be `cd` or `pushd` at a command position.
431
+ let word = w1;
432
+ if (word && line.slice(word[0], word[1]) === '--')
433
+ word = w2;
434
+ const verb = word ? line.slice(word[0], word[1]) : '';
435
+ const verbStart = word ? word[0] : -1;
436
+ const lead = verbStart > 0 ? line[verbStart - 1] : '';
437
+ if ((verb === 'cd' || verb === 'pushd') && (verbStart <= 0 || /[\s;&|(]/.test(lead)))
438
+ return LOCAL_SERVER_RUN.test(line.slice(at));
439
+ at = line.indexOf('holmes/mcp', at + 1);
440
+ }
441
+ return false;
442
+ }
443
+ /**
444
+ * @implements A-SPEC-732 (round 6) — the command word after wrappers (`env nohup time command exec
445
+ * builtin`, `NAME=value` assignments) and group openers (`(`, `$(`, a backtick): `env holmes-mcp`,
446
+ * `(holmes-mcp)` and `$(holmes-mcp)` slipped past (measured). One pass over the pieces; each piece's
447
+ * head is stripped by a bounded loop.
448
+ */
449
+ function wrappedServerWord(normalized) {
450
+ // No iteration cap (a cap would let the 65th wrapper decide the verdict): a sticky regex walks an
451
+ // index, each step consuming at least one wrapper, so the walk is linear in the piece.
452
+ const WRAPPER = /(?:(?:env|nohup|time|command|exec|builtin)\s+|[A-Za-z_][A-Za-z0-9_]*=\S*\s+|\s+)/y;
453
+ const WORD = /(?:\S*\/)?holmes-mcp(?:\.js)?(?=$|\s)/y;
454
+ for (const piece of normalized.split(/[;&|\n()`]|\$\(/)) {
455
+ let i = 0;
456
+ for (;;) {
457
+ WRAPPER.lastIndex = i;
458
+ const m = WRAPPER.exec(piece);
459
+ if (!m || m[0].length === 0)
460
+ break;
461
+ i += m[0].length;
462
+ }
463
+ WORD.lastIndex = i;
464
+ if (WORD.test(piece))
465
+ return true;
466
+ }
467
+ return false;
468
+ }
469
+ function startsHolmesServer(command) {
470
+ if (SERVER_RUNNERS.some((t) => t.test(command)))
471
+ return true;
472
+ const normalized = normalizedCommand(command);
473
+ return SERVER_RUNNERS.some((t) => t.test(normalized)) || cdIntoServerDir(normalized) || wrappedServerWord(normalized);
474
+ }
475
+ /**
476
+ * @implements A-SPEC-732 (round 2) — the PreToolUse output. For `approval_commit` an unobjected call
477
+ * carries no decision: an `allow` would pre-empt the harness's own sensitive-tool confirmation, the
478
+ * premise of the host-gated route.
479
+ */
480
+ /**
481
+ * @implements A-SPEC-739 — the gate takes decisions away and never grants one. A deny reaches the harness as a deny with
482
+ * its reason; anything else carries no permission decision, so the harness's own flow (the user's confirmation, allow
483
+ * rules, auto mode) decides. Measured: Claude Code 2.1.281 handles a hook `allow` as "Hook approved tool use …,
484
+ * bypassing permission prompt", so every miss of the shell model ran unconfirmed; Codex 0.155 ignores `allow`
485
+ * ("unsupported permissionDecision:allow"). A pass's warning travels as `additionalContext` (A-SPEC-336's reason).
486
+ * Round-1 A-SPEC-718's approval_commit exception is now the rule for every tool.
487
+ */
488
+ function hookOutputFor(_toolName, out) {
489
+ const { permissionDecision, permissionDecisionReason, ...rest } = out;
490
+ if (permissionDecision === 'deny') {
491
+ return { hookEventName: 'PreToolUse', ...rest, permissionDecision, ...(permissionDecisionReason !== undefined ? { permissionDecisionReason } : {}) };
492
+ }
493
+ const context = [typeof rest.additionalContext === 'string' ? rest.additionalContext : '', permissionDecisionReason ?? ''].filter((t) => t !== '').join('\n');
494
+ const { additionalContext: _c, ...others } = rest;
495
+ return { hookEventName: 'PreToolUse', ...others, ...(context !== '' ? { additionalContext: context } : {}) };
496
+ }
497
+ /**
498
+ * @implements A-SPEC-729 (round 4) — whether a file-writing tool call on spec path `p` would bring a
499
+ * NEW REQ identity into the store: a REQ file that does not exist yet, or an existing spec whose `id:`
500
+ * or `type:` the write changes into another REQ. Returns what it saw, or null. Frontmatter is read
501
+ * with the downstream parser when the content is whole; an Edit fragment is read by its `id:`/`type:`
502
+ * lines.
503
+ */
504
+ /** A spec write's result larger than this is not computed (rule 39). */
505
+ const EDIT_RESULT_MAX = 16 * 1024 * 1024;
506
+ const TOO_LARGE = Symbol('too large');
507
+ /**
508
+ * @implements A-SPEC-728 (rule 39) — the text a Write/Edit/MultiEdit on `disk` would leave, or null when an edit does not
509
+ * apply, or TOO_LARGE past 16 MiB: the size is counted before any replacement (27 `replace_all` edits of `R` → `RR` on a
510
+ * 1.9 KB MultiEdit grew past V8's string limit and aborted the hook process — measured).
511
+ */
512
+ function editedResult(disk, ti) {
513
+ // Rule 40: computed once per call — the self-approval rule and the new-requirement rule share it.
514
+ if (editedMemo !== null && editedMemo.ti === ti && editedMemo.disk === disk)
515
+ return editedMemo.result;
516
+ const result = editedResultUncached(disk, ti);
517
+ editedMemo = { ti, disk, result };
518
+ return result;
519
+ }
520
+ let editedMemo = null;
521
+ /** Rule 40: the work of one result across ALL its edits — replacements made and characters scanned or built. */
522
+ const EDIT_REPLACEMENTS_MAX = 1024 * 1024;
523
+ /** Rule 42: 64 MiB — a linear search costs more per character than V8's native one (400 edits of a 68 KB spec: 54 MB). */
524
+ const EDIT_WORK_MAX = 64 * 1024 * 1024;
525
+ /** Rule 42: patterns up to this length use V8's search (≤ 141 ms over 16 MiB, measured); longer ones a linear search. */
526
+ const LONG_PATTERN = 256;
527
+ /** Rule 42: the shell limits — past them a command is refused as too large to judge rather than judged slowly. */
528
+ const SHELL_SEGMENTS_MAX = 4096;
529
+ const SHELL_CANDIDATES_MAX = 4096;
530
+ /**
531
+ * @implements A-SPEC-728 (rule 42) — a finder of `o` in `text` from an index, non-overlapping from the caller's side: V8's
532
+ * search of `a^k b a^k` in 16 MiB of `a` grows with `k` (10.6 s at `k` = 2,048 — measured), so a long pattern is searched
533
+ * with Knuth–Morris–Pratt.
534
+ */
535
+ function finderFor(o) {
536
+ if (o.length <= LONG_PATTERN)
537
+ return (text, from) => text.indexOf(o, from);
538
+ const fail = new Int32Array(o.length);
539
+ for (let i = 1, k = 0; i < o.length; i++) {
540
+ while (k > 0 && o[i] !== o[k])
541
+ k = fail[k - 1];
542
+ if (o[i] === o[k])
543
+ k++;
544
+ fail[i] = k;
545
+ }
546
+ return (text, from) => {
547
+ for (let i = from, k = 0; i < text.length; i++) {
548
+ while (k > 0 && text[i] !== o[k])
549
+ k = fail[k - 1];
550
+ if (text[i] === o[k])
551
+ k++;
552
+ if (k === o.length)
553
+ return i - o.length + 1;
554
+ }
555
+ return -1;
556
+ };
557
+ }
558
+ /**
559
+ * @implements A-SPEC-728 (rule 40) — rule 39 capped each step at 16 MiB and nothing else: 20 length-preserving
560
+ * `replace_all` edits over 16 M occurrences took 16.1 s from a 2.9 KB MultiEdit (measured).
561
+ */
562
+ function editedResultUncached(disk, ti) {
563
+ let replacements = 0;
564
+ let work = 0;
565
+ const apply = (text, o, n, all) => {
566
+ if (typeof o !== 'string' || typeof n !== 'string')
567
+ return null;
568
+ if (o === '')
569
+ return text === '' ? n : null;
570
+ work += text.length;
571
+ if (work > EDIT_WORK_MAX)
572
+ return TOO_LARGE;
573
+ const find = finderFor(o);
574
+ const first = find(text, 0);
575
+ if (first < 0)
576
+ return null;
577
+ const at = [first];
578
+ if (all === true) {
579
+ for (let p = find(text, first + o.length); p >= 0; p = find(text, p + o.length)) {
580
+ if (replacements + at.length + 1 > EDIT_REPLACEMENTS_MAX)
581
+ return TOO_LARGE;
582
+ at.push(p);
583
+ }
584
+ }
585
+ replacements += at.length;
586
+ const size = text.length + at.length * (n.length - o.length);
587
+ work += size;
588
+ if (size > EDIT_RESULT_MAX || work > EDIT_WORK_MAX || replacements > EDIT_REPLACEMENTS_MAX)
589
+ return TOO_LARGE;
590
+ let out = '';
591
+ let last = 0;
592
+ for (const p of at) {
593
+ out += text.slice(last, p) + n;
594
+ last = p + o.length;
595
+ }
596
+ return out + text.slice(last);
597
+ };
598
+ // Rule 40: a pair of old and new text is an edit of the file, before a `content` is taken as the whole file — Antigravity's
599
+ // `replace_file_content` arrives with both (its replacement was judged as the whole file).
600
+ // Rule 41: only when there is no `content` or it is that alias (a Write carrying a stray pair was judged on the pair), and a
601
+ // pair that does not apply leaves the `content` read as the whole file, as before rule 40 (Antigravity may still apply an
602
+ // inexact target through its `fast_apply` fallback; an H-SPEC turned into a REQ went from deny to `ask` — measured).
603
+ if (typeof ti.old_string === 'string' && typeof ti.new_string === 'string' && !Array.isArray(ti.edits)
604
+ && (typeof ti.content !== 'string' || ti.content === ti.new_string)) {
605
+ const applied = disk === null ? null : apply(disk, ti.old_string, ti.new_string, ti.replace_all);
606
+ return applied === null && typeof ti.content === 'string' ? ti.content : applied;
607
+ }
608
+ if (typeof ti.content === 'string')
609
+ return ti.content;
610
+ if (Array.isArray(ti.edits)) {
611
+ let cur = disk ?? '';
612
+ for (const e of ti.edits) {
613
+ if (cur === null || cur === TOO_LARGE)
614
+ break;
615
+ cur = apply(cur, e.old_string, e.new_string, e.replace_all);
616
+ }
617
+ return cur;
618
+ }
619
+ return null;
620
+ }
621
+ function newRequirementIdentity(p, toolName, ti) {
622
+ // Round 5: judged on the RESULT, parsed as the store parses it — a fragment regex missed quoted keys,
623
+ // YAML tags and flow mappings, and misread body lines as frontmatter.
624
+ const tool = (toolName ?? '').toLowerCase();
625
+ const exists = fs.existsSync(p);
626
+ let disk = null;
627
+ if (exists) {
628
+ try {
629
+ disk = fs.readFileSync(p, 'utf8');
630
+ }
631
+ catch {
632
+ disk = null;
633
+ }
634
+ }
635
+ const edited = editedResult(disk, ti);
636
+ if (edited === TOO_LARGE)
637
+ return 'a spec edit too large to judge';
638
+ const result = edited;
639
+ const identity = (text) => {
640
+ if (text === null)
641
+ return { req: false };
642
+ try {
643
+ const s = (0, spec_parser_1.parseSpec)(text);
644
+ const type = typeof s.type === 'string' ? s.type : '';
645
+ const id = typeof s.id === 'string' ? s.id : undefined;
646
+ return { id, req: type.toUpperCase() === 'REQ' || (type === '' && /^REQ-/i.test(id ?? '')) };
647
+ }
648
+ catch {
649
+ return { req: false };
650
+ }
651
+ };
652
+ const base = path.basename(p, '.md');
653
+ if (!exists) {
654
+ if (tool === 'edit')
655
+ return null; // Edit cannot create a file
656
+ if (/^REQ-/i.test(base))
657
+ return `${base} does not exist yet`;
658
+ return identity(result).req ? `${base} does not exist yet and would be read as a REQ` : null;
659
+ }
660
+ const after = identity(result);
661
+ if (!after.req)
662
+ return null;
663
+ const before = identity(disk);
664
+ if (!before.req)
665
+ return `the write turns ${base} into a REQ`;
666
+ if (after.id !== undefined && before.id !== undefined && after.id !== before.id)
667
+ return `the write changes ${before.id} into ${after.id}`;
668
+ return null;
669
+ }
670
+ /**
671
+ * @implements A-SPEC-728 (round 4) — linear forms of `HEAD[^SEP]*TAIL`. The regex restarts at every
672
+ * HEAD and rescans to the next separator, which is quadratic on a command of repeated heads (a hook
673
+ * verdict that arrives after the 30 s timeout lets the call through). Per separator-free piece:
674
+ * whether TAIL occurs after the FIRST head (the longest suffix any head leaves).
675
+ */
676
+ function tailAfterFirst(text, sep, head, tail) {
677
+ for (const piece of text.split(sep)) {
678
+ const m = head.exec(piece);
679
+ if (m && tail.test(piece.slice(m.index + m[0].length)))
680
+ return true;
681
+ }
682
+ return false;
683
+ }
684
+ /** Whether HEAD occurs before the LAST match of `target` (a global regex) in a separator-free piece. */
685
+ function headBeforeLast(text, sep, target, head) {
686
+ for (const piece of text.split(sep)) {
687
+ let last = -1;
688
+ for (const m of piece.matchAll(target))
689
+ last = m.index ?? last;
690
+ if (last >= 0 && head.test(piece.slice(0, last)))
691
+ return true;
692
+ }
693
+ return false;
694
+ }
177
695
  function dumpsEnvInCommandPosition(command, depth = 0) {
178
696
  if (depth > 3)
179
697
  return false;
180
698
  for (const rawSeg of command.split(/[;&|\n]+/)) {
181
- let seg = rawSeg.trim().replace(/^[({\s]+/, '').replace(/[)}\s]+$/, '');
699
+ // Round 6: the trailing trim is a loop — `[)}\s]+$` retried at every position of a long blank run.
700
+ let seg = rawSeg.trim().replace(/^[({\s]+/, '');
701
+ let end = seg.length;
702
+ while (end > 0 && /[)}\s]/.test(seg[end - 1]))
703
+ end--;
704
+ seg = seg.slice(0, end);
182
705
  // strip leading VAR=value assignments and neutral wrappers
183
706
  for (;;) {
184
707
  const next = seg.replace(/^(?:\w+=(?:"[^"]*"|'[^']*'|\S*)\s+|(?:command|eval|exec|builtin|nohup|time|sudo)\s+)/, '');
@@ -227,8 +750,9 @@ function incomingSetsApproved(ti) {
227
750
  }
228
751
  catch { /* fall through to regex */ }
229
752
  }
230
- const text = `${ti.content ?? ''}\n${ti.new_string ?? ''}`;
231
- return /^\s*status\s*:\s*["']?approved["']?\s*(?:#.*)?$/im.test(text);
753
+ // A-SPEC-729 (round 5): a MultiEdit's edits are text the write lands, too.
754
+ const text = `${ti.content ?? ''}\n${ti.new_string ?? ''}\n${(ti.edits ?? []).map((e) => e.new_string ?? '').join('\n')}`;
755
+ return (0, linear_match_1.setsApprovedStatus)(text); // A-SPEC-728 rule 38: the regex it replaces, in one pass
232
756
  }
233
757
  function normalizeHookInput(raw) {
234
758
  const str = (v) => (typeof v === 'string' ? v : undefined);
@@ -264,13 +788,30 @@ function normalizeHookInput(raw) {
264
788
  const cmd = str(ti.command ?? ti.CommandLine);
265
789
  if (cmd !== undefined)
266
790
  out.command = cmd;
791
+ const wd = str(ti.workdir);
792
+ if (wd !== undefined && wd.trim() !== '')
793
+ out.workdir = wd.trim();
267
794
  // @implements A-SPEC-163 — a path field the gate does not preserve is a path the gate cannot see,
268
795
  // which is how a NotebookEdit reached protected files unexamined.
269
796
  const nbRaw = str(ti.notebook_path);
270
797
  const nb = nbRaw === undefined ? undefined : (nbRaw.trim() || undefined);
271
798
  if (nb !== undefined)
272
799
  out.notebook_path = nb;
273
- return { tool_name: str(r.tool_name) ?? '', tool_input: out, ...(malformed ? { malformed: true } : {}) };
800
+ // @implements A-SPEC-729 (round 5) — an Edit's anchor and a MultiEdit's edits are kept: a rule that
801
+ // judges what a write PRODUCES needs them, and a MultiEdit's text was invisible to every content rule.
802
+ const os2 = str(ti.old_string);
803
+ if (os2 !== undefined)
804
+ out.old_string = os2;
805
+ if (typeof ti.replace_all === 'boolean')
806
+ out.replace_all = ti.replace_all;
807
+ if (Array.isArray(ti.edits)) {
808
+ out.edits = ti.edits.filter((e) => !!e && typeof e === 'object' && !Array.isArray(e))
809
+ .map((e) => ({ ...(typeof e.old_string === 'string' ? { old_string: e.old_string } : {}), ...(typeof e.new_string === 'string' ? { new_string: e.new_string } : {}),
810
+ ...(typeof e.replace_all === 'boolean' ? { replace_all: e.replace_all } : {}) }));
811
+ }
812
+ const cwdRaw = str(r.cwd);
813
+ const cwd = cwdRaw === undefined ? undefined : (cwdRaw.trim() || undefined);
814
+ return { tool_name: str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(malformed ? { malformed: true } : {}) };
274
815
  }
275
816
  /**
276
817
  * Which way to fail when the gate itself throws.
@@ -412,6 +953,9 @@ function wiredSpecsDir(argv, env) {
412
953
  exports.DEFAULT_SPECS_DIR = '.ax/specs';
413
954
  // @implements A-SPEC-100.2
414
955
  function evaluateHook(input, specsDir, opts) {
956
+ // @implements A-SPEC-728 (rule 40) — a spec edit's result is shared within this call only: a caller that hands the same
957
+ // tool_input object back changed must not be judged on the earlier result.
958
+ editedMemo = null;
415
959
  // @implements A-SPEC-133 — resolved once so every gate in this call shares one timestamp.
416
960
  const nowTs = opts?.now ?? new Date().toISOString();
417
961
  // @implements A-SPEC-125.4
@@ -424,6 +968,15 @@ function evaluateHook(input, specsDir, opts) {
424
968
  // depth — the harness normally sets tool_name, but the gate defends regardless).
425
969
  if ((input.tool_name ?? '').toLowerCase() === 'bash' && typeof input.tool_input.command === 'string' && input.tool_input.command.length > 0) {
426
970
  const command = input.tool_input.command;
971
+ // @implements A-SPEC-728 (round 17) — the shell runs where the harness says (a Codex `workdir`, the
972
+ // payload `cwd`), inside the project; relative words are judged from there, not from the root.
973
+ const shellBase = (0, write_target_1.shellBaseFor)(opts.projectRoot, input.tool_input.workdir, input.cwd);
974
+ // @implements A-SPEC-728 (rule 42) — split once, before any other judgement, and refused past 4,096 segments: seventeen
975
+ // shapes of repeated separators took 2.4–6.1 s at 256 KB, their cost spread over every segment of every rule (measured).
976
+ const segmentsOnce = (0, write_target_1.shellSegments)(command, shellBase);
977
+ if (segmentsOnce.length > SHELL_SEGMENTS_MAX) {
978
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a shell command of ${segmentsOnce.length} segments is too large to judge (more than ${SHELL_SEGMENTS_MAX}) — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
979
+ }
427
980
  // Git-aware rm signals (H1): resolved only when a resolver is injected (the CLI wires the real
428
981
  // git-backed one; unit tests omit it and exercise the pure static path). Fail-open: a throwing
429
982
  // resolver must never block a command, so a resolution error degrades to no signals.
@@ -438,7 +991,8 @@ function evaluateHook(input, specsDir, opts) {
438
991
  // it the substring match gated `.ax` paths in any other project on the machine.
439
992
  const action = {
440
993
  kind: 'shell', target: command, command, rmTargetSignals,
441
- projectRoot: opts.projectRoot.replace(/\\/g, '/').replace(/\/+$/, ''),
994
+ projectRoot: (0, linear_match_1.trimTrailing)(opts.projectRoot.replace(/\\/g, '/'), '/'),
995
+ cwd: shellBase,
442
996
  };
443
997
  const assess = opts?.assess ?? risk_classifier_1.assessRisk;
444
998
  const approval = opts.approval;
@@ -446,13 +1000,20 @@ function evaluateHook(input, specsDir, opts) {
446
1000
  try {
447
1001
  assessment = assess(action);
448
1002
  }
449
- catch {
1003
+ catch (e) {
1004
+ // @implements A-SPEC-728 (rule 44) — a classifier bound says what it is: too large to judge, not a classifier failure.
1005
+ if (e instanceof RangeError && /too large to judge/.test(e.message)) {
1006
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${e.message} — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
1007
+ }
450
1008
  return { permissionDecision: 'deny', permissionDecisionReason: '[Holmes-Kit] risk classification failed on a shell command — denied (fail-closed)' };
451
1009
  }
452
1010
  // @implements A-SPEC-133
453
1011
  // Hard-hitl needs an approval that COVERS this specific command (scope + not expired), and if
454
1012
  // the approval is single-use its nonce must not already be spent. An out-of-scope, expired, or
455
1013
  // replayed token denies exactly as an absent one — one token stops being a master key.
1014
+ // @implements A-SPEC-728 — an operator who approved THIS exact hard-hitl command (e.g. a covered
1015
+ // `rm -rf /`) has already judged its deletions; the wiring-deletion rule below must not re-deny it.
1016
+ let hardHitlCovered = false;
456
1017
  if (assessment.level === 'hard-hitl') {
457
1018
  // @implements A-SPEC-245 — env first, then the grant files. The grant's mandatory nonce rides
458
1019
  // the SAME atomic ledger consumption below, so hard-hitl single-use needs no new machinery.
@@ -465,6 +1026,7 @@ function evaluateHook(input, specsDir, opts) {
465
1026
  });
466
1027
  // @implements A-SPEC-244 — the refusal itself files the review request. The queue kind is the
467
1028
  // approval SCOPE kind ('shell'), so the reviewing CLI can mint a covering grant mechanically.
1029
+ hardHitlCovered = covers;
468
1030
  if (!covers) {
469
1031
  // @implements A-SPEC-564.2 — the base reason's length rides along so the refusal record
470
1032
  // knows the FULL feedback cost (base + hint), not just the hint's half.
@@ -565,7 +1127,9 @@ function evaluateHook(input, specsDir, opts) {
565
1127
  // @implements A-SPEC-477 — the credential file is the same secret at rest; reading,
566
1128
  // copying or redirecting it is the harvest in file form. Path-usage only, so mentioning
567
1129
  // the string in a search or a commit message stays free.
568
- /(?:\bcat\b|\bcp\b|\bless\b|\bhead\b|\btail\b|[<>])[^;&|\n]*[.\/\\]holmes[\/\\]credentials/.test(command) ||
1130
+ // @implements A-SPEC-728 (round 4) — one pass per segment: the old `(…|[<>])[^;&|\n]*…`
1131
+ // restarted at every `>` and took 7 s on 45 000 of them; the verdict is the same.
1132
+ headBeforeLast(command, /[;&|\n]/, /[.\/\\]holmes[\/\\]credentials/g, /\bcat\b|\bcp\b|\bless\b|\bhead\b|\btail\b|[<>]/) ||
569
1133
  new RegExp(String.raw `\$\{?\s*${SECRET}\b`).test(command) || // $VAR / ${VAR} — a read
570
1134
  new RegExp(String.raw `\b${SECRET}\s*=`).test(command) || // assignment — a self-issued approval / forged key
571
1135
  // A quoted key only counts as a LOOKUP when something indexes or calls with it —
@@ -574,10 +1138,12 @@ function evaluateHook(input, specsDir, opts) {
574
1138
  new RegExp(String.raw `[[(]\s*['"\`]${SECRET}['"\`]`).test(command);
575
1139
  const dumpsEnv = usesSecret ||
576
1140
  dumpsEnvInCommandPosition(command) || // env/printenv as a COMMAND
577
- /(^|[;&|\n]\s*)(?:set|export\s+-p|declare\s+-x|typeset\s+-x)\s*(?:$|[;&|\n>])/.test(command) ||
1141
+ // @implements A-SPEC-728 (round 4) — `[ \t]` where `\s` spanned newlines: 190 000 newlines made
1142
+ // every start re-scan the rest (23 s); a newline is itself a separator, so the verdict is the same.
1143
+ /(^|[;&|\n][ \t]*)(?:set|export[ \t]+-p|declare[ \t]+-x|typeset[ \t]+-x)[ \t]*(?:$|[;&|\n>])/.test(command) ||
578
1144
  /\$\{!\s*\w/.test(command) || // ${!VAR*} indirection
579
1145
  /\/proc\/(?:self|\d+|\$\$|\$\{?\w+\}?)\/environ/.test(command) || // /proc/*/environ incl. $$
580
- /\bps\b[^;&|\n]*\s-?e\w*\b/.test(command) || // ps e / ps -e www
1146
+ tailAfterFirst(command, /[;&|\n]/, /\bps\b/, /\s-?e\w*\b/) || // ps e / ps -e www
581
1147
  // Interpreter access to the environment, in any dash form (-e/-c/-p/--eval/--print/eval).
582
1148
  // @implements A-SPEC-163
583
1149
  // The bare `\bENV\b` alternative is GONE. It was narrowed once already (it denied
@@ -586,13 +1152,21 @@ function evaluateHook(input, specsDir, opts) {
586
1152
  // JSON key — was refused as an environment dump. The remaining alternatives
587
1153
  // (`process.env`, `os.environ`, `ENVIRON`, `getenv`) name real environment access; Perl's
588
1154
  // `%ENV`/`$ENV{…}` are the loss, and they are rarer than the false positives were.
589
- /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php|awk|gawk)\b[^\n]*?(?:process\s*\.\s*env|os\s*\.\s*environ|from\s+os\s+import\s+environ|ENVIRON|getenv)/i.test(command) ||
1155
+ tailAfterFirst(command, /\n/, /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php|awk|gawk)\b/i, /process\s*\.\s*env|os\s*\.\s*environ|from\s+os\s+import\s+environ|ENVIRON|getenv/i) ||
590
1156
  // @implements A-SPEC-163
591
1157
  // Perl's `$ENV{…}` and Ruby's bare `ENV` still have to be caught, but CASE-SENSITIVELY and
592
1158
  // not after a dot. The old alternative was `\bENV\b` under /i, which also matched `s.env` —
593
1159
  // reading one JSON key was refused as an environment dump (measured 2026-08-08). Requiring
594
1160
  // upper case and a non-dot boundary keeps the real reads and drops the property access.
595
- /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php|awk|gawk)\b[^\n]*?(?<![.\w])ENV\b/.test(command);
1161
+ tailAfterFirst(command, /\n/, /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php|awk|gawk)\b/, /(?<![.\w])ENV\b/);
1162
+ // @implements A-SPEC-732 (round 2) — an agent starting its own copy of the MCP server can pose as a
1163
+ // harness and answer its own approval; no agent task needs that copy (doctor starts one internally).
1164
+ if (startsHolmesServer(command)) {
1165
+ return {
1166
+ permissionDecision: 'deny',
1167
+ permissionDecisionReason: '[Holmes-Kit] the command starts the Holmes MCP server (or loads its handlers) itself — a copy the agent drives could answer its own approval (A-SPEC-732). The harness starts the server; use its tools. To run it by operator judgment, an approval that covers this command is required.',
1168
+ };
1169
+ }
596
1170
  if (dumpsEnv) {
597
1171
  return {
598
1172
  permissionDecision: 'deny',
@@ -624,7 +1198,9 @@ function evaluateHook(input, specsDir, opts) {
624
1198
  // `-m`, `--version` and `-v` out: only a BARE hyphen means "read the program from stdin",
625
1199
  // which covers heredocs and pipes alike.
626
1200
  const INTERP = /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b/;
627
- const ONE_LINER = /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b[^\n]*?(?:-e|--eval|-c|-r)\b/;
1201
+ // @implements A-SPEC-728 (round 5) — linear per line (the lazy regex rescanned from every
1202
+ // interpreter word: 2.3 s at 40 000 `node`); decides the same.
1203
+ const ONE_LINER = { test: (t) => tailAfterFirst(t, /\n/, /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b/, /(?:-e|--eval|-c|-r)\b/) };
628
1204
  const STDIN_PROGRAM = /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b\s+-(?![\w-])/;
629
1205
  if (!INTERP.test(command) || !(ONE_LINER.test(command) || STDIN_PROGRAM.test(command)))
630
1206
  return [];
@@ -633,8 +1209,10 @@ function evaluateHook(input, specsDir, opts) {
633
1209
  // obfuscation, and the idiom this repository writes its own spec bodies with. The
634
1210
  // spec/ledger rule never had this hole because it matches the PATH anywhere in the command.
635
1211
  // Write evidence is still REQUIRED, which is what keeps reads of the same path allowed.
636
- const WRITE_EVIDENCE = new RegExp(String.raw `\b(?:writeFileSync|appendFileSync|createWriteStream|write_text|writelines|File\.write|file_put_contents)\s*\(`
637
- + '|' + String.raw `\bopen\s*\([^)]*,\s*['"](?:[wax]\+?[bt]?|r\+[bt]?)['"]`);
1212
+ // @implements A-SPEC-728 (rule 37) — the `open(…, 'w')` half read linearly (quadratic as one regex, measured).
1213
+ const WRITE_CALL = new RegExp(String.raw `\b(?:writeFileSync|appendFileSync|createWriteStream|write_text|writelines|File\.write|file_put_contents)\s*\(`);
1214
+ const OPEN_WRITE = (0, linear_match_1.openForWriting)();
1215
+ const WRITE_EVIDENCE = { test: (t) => WRITE_CALL.test(t) || OPEN_WRITE.test(t) };
638
1216
  if (!WRITE_EVIDENCE.test(command))
639
1217
  return [];
640
1218
  // Assembled with String.raw throughout: a plain template literal collapses `\s` to `s`,
@@ -644,7 +1222,9 @@ function evaluateHook(input, specsDir, opts) {
644
1222
  // of the path, not an argument boundary. `[^'"\s]*` stopped at the first space and missed
645
1223
  // `open('C:\Users\Given Family\a.ts','w')`; `[^'"]*` keeps the space and still cannot cross a quote.
646
1224
  const NOT_QUOTE = String.raw `[^'"]*`;
647
- const QUOTED_PATH = new RegExp(String.raw `['"](` + NOT_QUOTE + String.raw `\.` + CODE_EXT + '|' + NOT_QUOTE + CONFIG_FILE + String.raw `)['"]`, 'g');
1225
+ const QUOTED_PATH = new RegExp(
1226
+ // @implements A-SPEC-728 — plus the Codex user-level files, judged by identity below.
1227
+ String.raw `['"](` + NOT_QUOTE + String.raw `\.` + CODE_EXT + '|' + NOT_QUOTE + CONFIG_FILE + '|' + NOT_QUOTE + String.raw `(?:config\.toml|hooks\.json)` + String.raw `)['"]`, 'g');
648
1228
  const out = [];
649
1229
  for (const m of command.matchAll(QUOTED_PATH))
650
1230
  if (m[1])
@@ -681,7 +1261,25 @@ function evaluateHook(input, specsDir, opts) {
681
1261
  // with the project root as the base; a `cd` earlier in the command moves that base, and the
682
1262
  // mismatch was measured both ways (2026-09-03 probe C1~C11): five in-project writes spelled
683
1263
  // from a subdirectory walked through, three legitimate out-of-tree writes were denied.
684
- const segments = (0, write_target_1.shellSegments)(command, opts.projectRoot);
1264
+ const segments = segmentsOnce;
1265
+ // @implements A-SPEC-728 (rule 42) — each candidate list judged once per path and base, and refused past 4,096 of them
1266
+ // (`> hooks.json` repeated to 256 KB looked every copy up — measured).
1267
+ const distinct = (list) => {
1268
+ const seen = new Set();
1269
+ const out = [];
1270
+ for (const c of list) {
1271
+ // Rule 43: a key that cannot collide — the U+0001 separator merged two candidates when a cd base held U+0001.
1272
+ const k = JSON.stringify([c.base, c.raw]);
1273
+ if (seen.has(k))
1274
+ continue;
1275
+ seen.add(k);
1276
+ out.push(c);
1277
+ if (out.length > SHELL_CANDIDATES_MAX)
1278
+ return null;
1279
+ }
1280
+ return out;
1281
+ };
1282
+ const TOO_MANY_CANDIDATES = { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a shell command with more than ${SHELL_CANDIDATES_MAX} distinct write targets is too large to judge — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
685
1283
  const isTilde = (p) => p === '~' || p.startsWith('~/');
686
1284
  // Relative candidate in a segment whose base is unknowable (dynamic cd argument): 'unknown',
687
1285
  // and the caller fails CLOSED — but only when such a candidate exists, so `cd "$X" && npm
@@ -703,11 +1301,23 @@ function evaluateHook(input, specsDir, opts) {
703
1301
  list.push({ raw: g, base: seg.base });
704
1302
  }
705
1303
  };
1304
+ // @implements A-SPEC-728 (round 5) — the lazy `VERB[^;|&]*?PATH` extractions, in linear time
1305
+ // and as a superset of what the regex captured (110 s measured on 200 KB of repeated `cp`).
1306
+ const WRITE_VERB = /\b(?:cp|mv|install|rsync|ln|dd|truncate|chmod|chown)\b/;
1307
+ // @implements A-SPEC-728 (rule 37) — a segment without the verb is not read, and each pattern is built once per
1308
+ // command, not once per segment (131,000 segments of `a\n` spent over half a second here — measured).
1309
+ const collectPaths = (seg, head, tail, list, mid) => {
1310
+ if (!head.test(seg.text))
1311
+ return;
1312
+ for (const raw of (0, linear_match_1.pathsAfter)(seg.text, head, tail, mid))
1313
+ list.push({ raw, base: seg.base });
1314
+ };
706
1315
  const cfgCandidates = [];
1316
+ const CFG_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(CONFIG_FILE)}`, 'g');
707
1317
  for (const seg of segments) {
708
- collectSeg(seg, new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(CONFIG_FILE)}`, 'g'), cfgCandidates);
709
- collectSeg(seg, new RegExp(`\\b(?:cp|mv|install|rsync|ln|dd|truncate|chmod|chown)\\b[^;|&]*?${pathAlt(CONFIG_FILE)}`, 'g'), cfgCandidates);
710
- collectSeg(seg, new RegExp(`\\bsed\\b[^;|&]*\\s-i\\b[^;|&]*?${pathAlt(CONFIG_FILE)}`, 'g'), cfgCandidates);
1318
+ collectSeg(seg, CFG_REDIRECT, cfgCandidates);
1319
+ collectPaths(seg, WRITE_VERB, CONFIG_FILE, cfgCandidates);
1320
+ collectPaths(seg, /\bsed\b/, CONFIG_FILE, cfgCandidates, /\s-i\b/);
711
1321
  }
712
1322
  // Interpreter one-liner paths keep their whole-text matching (A-SPEC-448/450); a RELATIVE one
713
1323
  // is judged as a may-analysis over every determinate base plus the start base — deny-only
@@ -720,8 +1330,10 @@ function evaluateHook(input, specsDir, opts) {
720
1330
  // @implements A-SPEC-447 — one containment predicate, shared with the code rule below.
721
1331
  const SESSION_ROOTS = [opts.projectRoot, path.join(os.homedir(), '.claude')];
722
1332
  const CFG_RE = new RegExp(`${CONFIG_FILE}$`);
723
- const cfgVerdicts = [...cfgCandidates, ...interpreterWrites.filter((p) => CFG_RE.test(p)).flatMap(expandInterp)]
724
- .map((c) => judgeCand(c, SESSION_ROOTS));
1333
+ const cfgList = distinct([...cfgCandidates, ...interpreterWrites.filter((p) => CFG_RE.test(p)).flatMap(expandInterp)]);
1334
+ if (cfgList === null)
1335
+ return TOO_MANY_CANDIDATES;
1336
+ const cfgVerdicts = cfgList.map((c) => judgeCand(c, SESSION_ROOTS));
725
1337
  const configWrite = cfgVerdicts.includes('in');
726
1338
  // Residual, stated rather than papered over: an INTERPRETER can write these files too. A first
727
1339
  // draft matched `node|python|perl|ruby` anywhere near the pattern and denied
@@ -731,6 +1343,64 @@ function evaluateHook(input, specsDir, opts) {
731
1343
  if (configWrite) {
732
1344
  return { permissionDecision: 'deny', permissionDecisionReason: registry_1.MESSAGES.INTEGRITY_CONFIG_EDIT('.claude/settings, .env, .mcp.json', 'A-SPEC-191') };
733
1345
  }
1346
+ // @implements A-SPEC-728 — the harness config that loads THIS session's gate also lives outside
1347
+ // the project: `~/.claude/settings*.json` and Codex's user-level `config.toml`/`hooks.json`
1348
+ // (the only place codex-cli 0.155 loads Holmes from). Judged by identity after `~`/`$HOME`/
1349
+ // `$CODEX_HOME` expansion, so no spelling is a door.
1350
+ const CODEX_FILE = String.raw `(?:config\.toml|hooks\.json)`;
1351
+ const userCfgCands = [...cfgCandidates];
1352
+ const CODEX_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(CODEX_FILE)}`, 'g');
1353
+ for (const seg of segments) {
1354
+ collectSeg(seg, CODEX_REDIRECT, userCfgCands);
1355
+ collectPaths(seg, WRITE_VERB, CODEX_FILE, userCfgCands);
1356
+ collectPaths(seg, /\bsed\b/, CODEX_FILE, userCfgCands, /\s-i\b/);
1357
+ }
1358
+ const USER_CFG_RE = /(?:config\.toml|hooks\.json|settings[\w.-]*\.json)$/;
1359
+ userCfgCands.push(...interpreterWrites.filter((p) => USER_CFG_RE.test(p)).flatMap(expandInterp));
1360
+ const userCfgList = distinct(userCfgCands);
1361
+ if (userCfgList === null)
1362
+ return TOO_MANY_CANDIDATES;
1363
+ const userCfgKind = userCfgList
1364
+ .map((c) => (c.base === null ? ((0, write_target_1.absoluteKindOf)(c.raw) !== null || /^(?:~|\$\{?(?:HOME|CODEX_HOME)\b)/.test(c.raw) ? (0, write_target_1.userHarnessConfigKindOf)(c.raw, opts.projectRoot) : null) : (0, write_target_1.userHarnessConfigKindOf)(c.raw, c.base)))
1365
+ .find((k) => k !== null);
1366
+ // One config-write approval (env or a granted queue request for this exact command) lifts both
1367
+ // rules below; the refusal files that request, as the Write/Edit config gate does.
1368
+ const liftByConfigWrite = (why) => {
1369
+ const r = (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind: 'config-write', target: command }, nowTs);
1370
+ if (r !== undefined) {
1371
+ if (r.source === 'grant' && r.approval.nonce)
1372
+ (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, r.approval.nonce);
1373
+ return null;
1374
+ }
1375
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${why} — an out-of-band approval that includes config-write is required (A-SPEC-728)`
1376
+ + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: command, why }) };
1377
+ };
1378
+ let configWriteLifted = false;
1379
+ if (userCfgKind) {
1380
+ const refusal = liftByConfigWrite(`${userCfgKind} is a hook/approval config — writing it can forge HOLMES_APPROVAL or turn governance off`);
1381
+ if (refusal)
1382
+ return refusal;
1383
+ configWriteLifted = true;
1384
+ }
1385
+ // @implements A-SPEC-728 — the identity rule over shell WORDS. Deleting, moving or rewriting a
1386
+ // wiring file disarms the gate; the verb-spelling rule it replaces was walked through twenty
1387
+ // ways in one adversarial round. Data heredoc bodies are not commands and are not judged.
1388
+ if (!hardHitlCovered && !configWriteLifted) {
1389
+ // Every segment, heredoc bodies included (round 2: a `<<` in quotes hid the lines after it).
1390
+ const act = (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase);
1391
+ if (act) {
1392
+ // @implements A-SPEC-728 (round 9) — `.ax` is named for what it is: the spec store and ledger.
1393
+ // @implements A-SPEC-728 (rule 38) — an input too large to judge is refused as such (a large loop read "… is the wiring
1394
+ // that loads this session's gate").
1395
+ const refusal = liftByConfigWrite(/too (?:large|long|complex) to judge|too many calls to judge/.test(act)
1396
+ ? `${act}: it is refused rather than judged, because deleting, moving or rewriting the wiring that loads this session's gate turns governance off`
1397
+ : act.includes(write_target_1.GOVERNANCE_STORE_LABEL) || /^\.ax\//.test(act)
1398
+ ? `${act} is this project's governance state — moving, deleting or bulk-replacing it turns No-Spec-No-Code off`
1399
+ : `${act} is the wiring that loads this session's gate — deleting, moving or rewriting it turns governance off`);
1400
+ if (refusal)
1401
+ return refusal;
1402
+ }
1403
+ }
734
1404
  // (c) Shell-writing PROJECT CODE files (redirect/tee/touch/sed -i to a relative code path)
735
1405
  // bypasses the No-Spec-No-Code Write/Edit gate entirely. Enforced only when this repo HAS
736
1406
  // governed specs (a spec-less repo has no phase gate to bypass — keeps the guardrail
@@ -746,10 +1416,11 @@ function evaluateHook(input, specsDir, opts) {
746
1416
  // extension part and `pathAlt` supplies the prefix and the quoting alternatives.
747
1417
  const EXT_TAIL = `\\.${CODE_EXT}`;
748
1418
  const candidates = [];
1419
+ const CODE_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(EXT_TAIL)}`, 'g');
749
1420
  for (const seg of segments) {
750
- collectSeg(seg, new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(EXT_TAIL)}`, 'g'), candidates);
751
- collectSeg(seg, new RegExp(`\\btouch\\s+[^;|&]*?${pathAlt(EXT_TAIL)}`, 'g'), candidates);
752
- collectSeg(seg, new RegExp(`\\bsed\\b[^;|&]*\\s-i\\b[^;|&]*?${pathAlt(EXT_TAIL)}`, 'g'), candidates);
1421
+ collectSeg(seg, CODE_REDIRECT, candidates);
1422
+ collectPaths(seg, /\btouch\s+/, EXT_TAIL, candidates);
1423
+ collectPaths(seg, /\bsed\b/, EXT_TAIL, candidates, /\s-i\b/);
753
1424
  }
754
1425
  // @implements A-SPEC-449 — the copy/move family. The CONFIG rule has carried it since
755
1426
  // A-SPEC-191 §28 ("a gate that names one syntax for an act is a gate over that syntax, not
@@ -809,7 +1480,7 @@ function evaluateHook(input, specsDir, opts) {
809
1480
  positional.push(unq(t));
810
1481
  }
811
1482
  const baseName = (s) => s.split(/[/\\]/).pop() ?? s;
812
- const stripSlash = (s) => s.replace(/[/\\]+$/, '');
1483
+ const stripSlash = (s) => (0, linear_match_1.trimTrailing)(s, '/\\');
813
1484
  const pushLanding = (destDir, sources) => {
814
1485
  for (const src of sources)
815
1486
  if (CODE_TAIL_RE.test(src))
@@ -842,8 +1513,11 @@ function evaluateHook(input, specsDir, opts) {
842
1513
  // @implements A-SPEC-447 — same predicate as the config rule; it lived in two copies, which
843
1514
  // is how one of two gets fixed.
844
1515
  const CODE_RE = new RegExp(`\\.${CODE_EXT}$`);
845
- const codeVerdicts = [...candidates, ...interpreterWrites.filter((p) => CODE_RE.test(p)).flatMap(expandInterp)]
846
- .map((c) => judgeCand(c, [opts.projectRoot]));
1516
+ const codeList = distinct([...candidates, ...interpreterWrites.filter((p) => CODE_RE.test(p)).flatMap(expandInterp)]);
1517
+ // Rule 43: only a governed project judges this list — an ungoverned one was refused for nothing it would check.
1518
+ if (codeList === null && readSpecsSync(specsDir).length > 0)
1519
+ return TOO_MANY_CANDIDATES;
1520
+ const codeVerdicts = (codeList ?? []).map((c) => judgeCand(c, [opts.projectRoot]));
847
1521
  // @implements A-SPEC-528.1 — an unresolvable base under a governed relative write candidate
848
1522
  // fails CLOSED: the gate cannot know where the file lands, and guessing is the bypass this
849
1523
  // slice closes. Config candidates get the same fail-closed unconditionally (the config rule
@@ -915,7 +1589,7 @@ function evaluateHook(input, specsDir, opts) {
915
1589
  // Holmes-Kit governs THIS project. An absolute path outside the project root (scratchpads, temp
916
1590
  // dirs, other checkouts) is not governed surface — gating it blocked ordinary harness scratch
917
1591
  // files (live over-block found in dogfooding). Relative paths are always in-project.
918
- const projectRoot = opts.projectRoot.replace(/\\/g, '/').replace(/\/+$/, '');
1592
+ const projectRoot = (0, linear_match_1.trimTrailing)(opts.projectRoot.replace(/\\/g, '/'), '/');
919
1593
  // @implements A-SPEC-191 §17 (round 11) — "inside the project" is a fact about the RESOLVED
920
1594
  // location, not about how the caller spelled the path. Measured: with the project reached through
921
1595
  // a symlinked ancestor (macOS `/var` → `/private/var`, a symlinked home, `/tmp`), the root came
@@ -932,20 +1606,37 @@ function evaluateHook(input, specsDir, opts) {
932
1606
  // the built hook — an in-project target spelled through `%TEMP%`'s alias (`C:\Users\SUNGNA~1\…`)
933
1607
  // resolved to a string the long-name root did not contain, and took the "outside → allow" exit
934
1608
  // below. Both sides must go through the one canonicaliser, or an alias is a free pass.
1609
+ // @implements A-SPEC-728 (rule 37) — the nearest ancestor that resolves is found by halving (whether an ancestor
1610
+ // resolves is monotone along a lexical chain), not by one throwing look-up and one `unshift` per missing component:
1611
+ // a 200 KB `file_path` took 6.6 s (measured). Still unbounded by count, still ending at the filesystem root.
935
1612
  const realOf = (abs) => {
936
- let head = abs;
937
- const tail = [];
938
- for (;;) {
939
- try {
940
- return [(0, root_1.canonicalPath)(head).replace(/\\/g, '/'), ...tail].join('/');
1613
+ const chain = [abs];
1614
+ for (let cur = abs, parent = path.dirname(cur); parent !== cur; cur = parent, parent = path.dirname(cur))
1615
+ chain.push(parent);
1616
+ const found = new Map();
1617
+ const resolved = (k) => {
1618
+ if (!found.has(k)) {
1619
+ let r = null;
1620
+ try {
1621
+ r = (0, root_1.canonicalPath)(chain[k]).replace(/\\/g, '/');
1622
+ }
1623
+ catch { /* not there */ }
1624
+ found.set(k, r);
941
1625
  }
942
- catch { /* walk up */ }
943
- const parent = path.dirname(head);
944
- if (parent === head)
945
- return abs;
946
- tail.unshift(path.basename(head));
947
- head = parent;
1626
+ return found.get(k) ?? null;
1627
+ };
1628
+ let lo = 0, hi = chain.length - 1;
1629
+ while (lo < hi) {
1630
+ const mid = (lo + hi) >> 1;
1631
+ if (resolved(mid) !== null)
1632
+ hi = mid;
1633
+ else
1634
+ lo = mid + 1;
948
1635
  }
1636
+ const real = resolved(hi);
1637
+ if (real === null)
1638
+ return abs;
1639
+ return [real, ...chain.slice(0, hi).reverse().map((c) => path.basename(c))].join('/');
949
1640
  };
950
1641
  // @implements A-SPEC-191 §20 (round 11) — §17 said "the resolved location, not the spelling", and
951
1642
  // resolved only SYMLINKS. On a case-insensitive filesystem (APFS, NTFS) `fs.realpathSync` keeps
@@ -974,8 +1665,8 @@ function evaluateHook(input, specsDir, opts) {
974
1665
  if (absKind === 'posix' || absKind === 'drive') {
975
1666
  const inside = (t, r) => t === r || t.startsWith(r + '/');
976
1667
  const asProject = (abs, base) => (abs.length <= base.length ? projectRoot : `${projectRoot}/${abs.slice(base.length + 1)}`);
977
- const realTarget = realOf(norm).replace(/\/+$/, '');
978
- const realRoot = realOf(projectRoot).replace(/\/+$/, '');
1668
+ const realTarget = (0, linear_match_1.trimTrailing)(realOf(norm), '/');
1669
+ const realRoot = (0, linear_match_1.trimTrailing)(realOf(projectRoot), '/');
979
1670
  // Case-blindness is a property of THIS filesystem, probed on the project root itself rather than
980
1671
  // assumed from the platform — a case-sensitive volume mounted on macOS must not have two distinct
981
1672
  // files folded together, and a case-insensitive volume on Linux must not keep the bypass.
@@ -1011,8 +1702,21 @@ function evaluateHook(input, specsDir, opts) {
1011
1702
  : inside(realTarget, realRoot) ? asProject(realTarget, realRoot)
1012
1703
  : inside(fold(realTarget), fold(realRoot)) ? asProject(realTarget, realRoot)
1013
1704
  : null;
1014
- if (canonical === null)
1705
+ if (canonical === null) {
1706
+ // @implements A-SPEC-728 — outside the project is free, EXCEPT the user-level harness config
1707
+ // that loads this session's gate (`~/.claude/settings*.json`, Codex `config.toml`/`hooks.json`).
1708
+ const userKind = (0, write_target_1.userHarnessConfigKindOf)(norm, projectRoot);
1709
+ if (userKind === null)
1710
+ return { permissionDecision: 'allow' };
1711
+ const userResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
1712
+ if (userResolved === undefined) {
1713
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${userKind} is a hook/approval config — it can forge HOLMES_APPROVAL or turn governance off, so an out-of-band approval that includes config-write is required`
1714
+ + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: norm, why: `writing ${userKind}` }) };
1715
+ }
1716
+ if (userResolved.source === 'grant' && userResolved.approval.nonce)
1717
+ (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, userResolved.approval.nonce);
1015
1718
  return { permissionDecision: 'allow' };
1719
+ }
1016
1720
  norm = canonical;
1017
1721
  }
1018
1722
  // @implements A-SPEC-191 §20e — an in-project target whose spelling cannot be decided is not a
@@ -1027,7 +1731,7 @@ function evaluateHook(input, specsDir, opts) {
1027
1731
  + ' — a target whose name cannot be pinned down is not allowed.',
1028
1732
  };
1029
1733
  }
1030
- norm = norm.length > 1 ? norm.replace(/\/+$/, '') : norm;
1734
+ norm = norm.length > 1 ? (0, linear_match_1.trimTrailing)(norm, '/') : norm; // A-SPEC-728 rule 38: linear (a 96 KB slash run took 4.5 s)
1031
1735
  // Everything downstream that reasons about WHERE a file sits — classifyAction's test rules and the
1032
1736
  // Files-to-Touch scope check — must see the PROJECT-RELATIVE path. Handing classifyAction an
1033
1737
  // absolute one let a project checked out under `/…/test/` read as one big test tree, which
@@ -1060,7 +1764,8 @@ function evaluateHook(input, specsDir, opts) {
1060
1764
  (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, rolesResolved.approval.nonce);
1061
1765
  }
1062
1766
  // @implements A-SPEC-191 §22 — ask by identity. A spelling regex was defeated by a single in-project link.
1063
- const configKind = (0, write_target_1.protectedFileKindOf)(opts.projectRoot, norm);
1767
+ // @implements A-SPEC-728 — a project that itself sits in a harness home still protects those files.
1768
+ const configKind = (0, write_target_1.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_1.userHarnessConfigKindOf)(norm, opts.projectRoot);
1064
1769
  // @implements A-SPEC-163 — identity, not spelling. Measured: `.ax//ledger//p.jsonl`,
1065
1770
  // `.ax/./ledger/p.jsonl` and `.AX/roles/policy.yaml` all reached the protected file while the
1066
1771
  // regex saw a different string. Adding `//` to the pattern would only move the next variant.
@@ -1107,6 +1812,30 @@ function evaluateHook(input, specsDir, opts) {
1107
1812
  return { permissionDecision: 'deny', permissionDecisionReason: registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
1108
1813
  }
1109
1814
  }
1815
+ // @implements A-SPEC-728 (rule 39) — and judged on the RESULT too: an Edit of `draft` into `approved` carries no
1816
+ // `status:` line of its own and left the file approved (measured). The result is parsed as the store parses it.
1817
+ if (!onDiskApproved && !specWriteCovered) {
1818
+ let disk = null;
1819
+ try {
1820
+ disk = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null;
1821
+ }
1822
+ catch {
1823
+ disk = null;
1824
+ }
1825
+ const edited = editedResult(disk, input.tool_input);
1826
+ let approvedAfter = false;
1827
+ if (typeof edited === 'string') {
1828
+ try {
1829
+ approvedAfter = (0, spec_parser_1.parseSpec)(edited).status === 'approved';
1830
+ }
1831
+ catch { /* not a spec the store would read as approved */ }
1832
+ }
1833
+ if (approvedAfter || edited === TOO_LARGE) {
1834
+ return { permissionDecision: 'deny', permissionDecisionReason: edited === TOO_LARGE
1835
+ ? `[Holmes-Kit] a spec edit too large to judge (its result passes ${EDIT_RESULT_MAX / (1024 * 1024)} MiB, or its edits pass ${EDIT_REPLACEMENTS_MAX / (1024 * 1024)} M replacements or ${EDIT_WORK_MAX / (1024 * 1024)} MiB of work) — refused rather than judged (A-SPEC-728)`
1836
+ : registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
1837
+ }
1838
+ }
1110
1839
  // @implements A-SPEC-132
1111
1840
  // Sealed-content forgery rule: once a spec is approved on disk, editing its BODY or its seal
1112
1841
  // fields is an approval-scope act — it either drifts the sealed content or forges the seal, both
@@ -1119,6 +1848,18 @@ function evaluateHook(input, specsDir, opts) {
1119
1848
  permissionDecisionReason: registry_1.MESSAGES.SEAL_APPROVED_SPEC_MUTATION(path.basename(p, '.md'), undefined, 'A-SPEC-132'),
1120
1849
  };
1121
1850
  }
1851
+ // @implements A-SPEC-729 (round 4) — a NEW REQ enters the store only through spec_create(type=REQ)
1852
+ // or spec_slice_init, which spend ledger-issued triage evidence. A hand-written REQ file walked
1853
+ // around that intake entirely and could then be sealed (measured on 179b435b).
1854
+ if (!specWriteCovered) {
1855
+ const newReq = newRequirementIdentity(p, input.tool_name, input.tool_input);
1856
+ if (newReq !== null) {
1857
+ return {
1858
+ permissionDecision: 'deny',
1859
+ permissionDecisionReason: `[Holmes-Kit] ${newReq} — a new REQ is created only by spec_create(type='REQ') or spec_slice_init with triage_evidence from requirement_triage(persist:true) (A-SPEC-729). Editing an existing REQ's body stays free.`,
1860
+ };
1861
+ }
1862
+ }
1122
1863
  const m = /(REQ|H-SPEC|A-SPEC|C-SPEC|T-SPEC)-\d{3,}(?:\.\d+)?/.exec(path.basename(p));
1123
1864
  if (m) {
1124
1865
  const br = (0, rtm_check_1.computeBlastRadius)(readSpecsSync(specsDir), m[0]);
@@ -1557,9 +2298,13 @@ function evaluateHook(input, specsDir, opts) {
1557
2298
  if (preEditMode !== 'off') {
1558
2299
  let evidenceHead = '';
1559
2300
  try {
1560
- evidenceHead = (0, node_child_process_1.execFileSync)('git', ['-C', projectRoot, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], env: (0, root_1.cleanSubprocessEnv)() }).trim();
2301
+ if (!(0, bounded_io_1.gitRootBlocked)(projectRoot, 'repo')) {
2302
+ evidenceHead = (0, node_child_process_1.execFileSync)('git', ['-C', projectRoot, 'rev-parse', 'HEAD'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], env: (0, root_1.cleanSubprocessEnv)() }).trim();
2303
+ }
2304
+ }
2305
+ catch (e) {
2306
+ (0, bounded_io_1.noteGitFailure)(projectRoot, e, 'repo'); /* non-git tree: the basis degrades to "" on both sides, never to a crash */
1561
2307
  }
1562
- catch { /* non-git tree: the basis degrades to "" on both sides, never to a crash */ }
1563
2308
  const evidenceDecision = preEditEvidenceGate({
1564
2309
  action, projectRoot, relPath, covered: codeWriteCovered, mode: preEditMode,
1565
2310
  // ENVIRONMENT only (A-SPEC-133's rule): a digest inside the payload would be the session
@@ -1595,7 +2340,9 @@ function readSpecsSync(root) {
1595
2340
  try {
1596
2341
  if (e.isDirectory())
1597
2342
  walk(q);
1598
- else if (e.name.endsWith('.md')) {
2343
+ // @implements A-SPEC-734 (round 10) — a regular `.md` (or a link to one) only: a FIFO named like a
2344
+ // spec blocked every gated edit and every Stop (measured).
2345
+ else if (e.name.endsWith('.md') && (e.isFile() || (e.isSymbolicLink() && fs.statSync(q).isFile()))) {
1599
2346
  const spec = (0, spec_parser_1.parseSpec)(fs.readFileSync(q, 'utf8'));
1600
2347
  // Only include valid specs with non-empty id
1601
2348
  if (spec.id) {
@@ -1619,9 +2366,18 @@ function readSpecsSync(root) {
1619
2366
  // CLI entry point: Claude Code passes hook JSON via stdin
1620
2367
  // Wrapped in fail-open error handling: any error emits allow + exits 0 to avoid blocking workflows
1621
2368
  if (require.main === module) {
1622
- let buf = '';
1623
- process.stdin.on('data', (c) => (buf += c));
1624
- process.stdin.on('end', () => {
2369
+ // @implements A-SPEC-734 (round 13) — this process never blocks on a file that is not a regular file.
2370
+ // Both threads run this block: the worker is started on this file.
2371
+ require('../project/regular-file-guard').installProcessGuards();
2372
+ /** One hook evaluation from its stdin text: what it writes and the exit code (never exits itself). */
2373
+ function runHookProcess(buf, io) {
2374
+ // Test seam for the deadline wall (A-SPEC-728 round 8): it can only make the evaluation SLOWER, so the
2375
+ // wall answers with the gate-error decision — it never opens anything.
2376
+ const stall = Number(process.env.HOLMES_HOOK_TEST_STALL_MS);
2377
+ if (Number.isFinite(stall) && stall > 0) {
2378
+ const until = Date.now() + stall;
2379
+ while (Date.now() < until) { /* stall */ }
2380
+ }
1625
2381
  try {
1626
2382
  // @implements A-SPEC-144 — normalize BEFORE deciding: most of the measured bypasses were a
1627
2383
  // wrong type reaching code that assumed a string, not an interesting failure of the gate.
@@ -1680,9 +2436,10 @@ if (require.main === module) {
1680
2436
  const out = evaluateHook(input, specsDirWired, {
1681
2437
  projectRoot: hookProjectRoot,
1682
2438
  approval: readApprovalFromEnv(),
1683
- resolveRmSignals: (command) => resolveRmSignals(command, hookProjectRoot),
2439
+ // Round 17: rm targets resolve from the directory the shell runs in (inside the project).
2440
+ resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_1.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
1684
2441
  });
1685
- process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', ...out } }));
2442
+ io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor(input.tool_name, out) }));
1686
2443
  // N3 provenance: record the audit-critical decision classes on the tamper-evident chain —
1687
2444
  // every DENY, and every ALLOW that was unlocked by an out-of-band approval. Fail-open: a
1688
2445
  // provenance write failure never changes the already-computed verdict.
@@ -1710,7 +2467,8 @@ if (require.main === module) {
1710
2467
  ? evaluateHook(input, specsDirWired, {
1711
2468
  projectRoot: hookProjectRoot,
1712
2469
  approval: undefined,
1713
- resolveRmSignals: (command) => resolveRmSignals(command, process.cwd()),
2470
+ // A-SPEC-734 (round 17): the same base, project and spec directory as the decision it re-asks.
2471
+ resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_1.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
1714
2472
  })
1715
2473
  : undefined;
1716
2474
  const unlocked = withoutApproval?.permissionDecision === 'deny';
@@ -1752,10 +2510,10 @@ if (require.main === module) {
1752
2510
  // model as the block reason, while permissionDecisionReason in the stdout JSON is
1753
2511
  // read on the exit-0 (allow) channel. Write the reason to both so the remediation
1754
2512
  // string reaches the model regardless of which channel a given CC version honors.
1755
- process.stderr.write(`${out.permissionDecisionReason ?? ''}\n`);
1756
- process.exit(2);
2513
+ io.err(`${out.permissionDecisionReason ?? ''}\n`);
2514
+ return 2;
1757
2515
  }
1758
- process.exit(0);
2516
+ return 0;
1759
2517
  }
1760
2518
  catch (err) {
1761
2519
  // @implements A-SPEC-144
@@ -1775,13 +2533,91 @@ if (require.main === module) {
1775
2533
  }
1776
2534
  })();
1777
2535
  const decision = gateErrorDecision(message, process.env, process.argv, errProjectRoot);
1778
- process.stderr.write(`[Holmes-Kit PreToolUse Hook] Error: ${message}\n`);
1779
- process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', ...decision } }));
2536
+ io.err(`[Holmes-Kit PreToolUse Hook] Error: ${message}\n`);
2537
+ io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor('', decision) }));
1780
2538
  if (decision.permissionDecision === 'deny') {
1781
- process.stderr.write(`${decision.permissionDecisionReason ?? ''}\n`);
1782
- process.exit(2);
2539
+ io.err(`${decision.permissionDecisionReason ?? ''}\n`);
2540
+ return 2;
1783
2541
  }
1784
- process.exit(0);
2542
+ return 0;
1785
2543
  }
1786
- });
2544
+ }
2545
+ /**
2546
+ * @implements A-SPEC-728 (round 8) — the deadline wall. A verdict after the harness's hook timeout lets
2547
+ * the call through, and each review round found another shape with super-linear cost or unbounded
2548
+ * memory (tree-sitter on pathological content: 48 s; brace expansion: a 4 GB heap abort). The
2549
+ * evaluation runs in a worker thread with a heap limit and a deadline below every harness timeout; a
2550
+ * worker that runs out of either, crashes or answers nothing gets the gate-error decision (A-SPEC-144:
2551
+ * governance decides the direction — deny where governed). It can never turn a deny into an allow.
2552
+ */
2553
+ function gateErrorOutcome(message) {
2554
+ const errProjectRoot = (() => {
2555
+ try {
2556
+ const { resolveProjectRoot } = require('../project/root');
2557
+ return resolveProjectRoot(process.cwd()).root;
2558
+ }
2559
+ catch {
2560
+ return process.cwd();
2561
+ }
2562
+ })();
2563
+ const decision = gateErrorDecision(message, process.env, process.argv, errProjectRoot);
2564
+ let stderr = `[Holmes-Kit PreToolUse Hook] Error: ${message}\n`;
2565
+ const stdout = JSON.stringify({ hookSpecificOutput: hookOutputFor('', decision) });
2566
+ if (decision.permissionDecision === 'deny') {
2567
+ stderr += `${decision.permissionDecisionReason ?? ''}\n`;
2568
+ return { stdout, stderr, code: 2 };
2569
+ }
2570
+ return { stdout, stderr, code: 0 };
2571
+ }
2572
+ const HOOK_DEADLINE_MS = () => {
2573
+ const asked = Number(process.env.HOLMES_HOOK_DEADLINE_MS);
2574
+ return Number.isFinite(asked) && asked > 0 ? Math.max(1000, Math.min(20_000, asked)) : 20_000;
2575
+ };
2576
+ const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
2577
+ const collect = (buf) => {
2578
+ let stdout = '', stderr = '';
2579
+ const code = runHookProcess(buf, { out: (t) => { stdout += t; }, err: (t) => { stderr += t; } });
2580
+ return { stdout, stderr, code };
2581
+ };
2582
+ const emit = (r) => {
2583
+ process.stdout.write(r.stdout);
2584
+ if (r.stderr)
2585
+ process.stderr.write(r.stderr);
2586
+ process.exit(r.code);
2587
+ };
2588
+ if (!isMainThread) {
2589
+ parentPort.postMessage(collect(workerData.buf));
2590
+ }
2591
+ else {
2592
+ let buf = '';
2593
+ process.stdin.on('data', (c) => (buf += c));
2594
+ process.stdin.on('end', () => {
2595
+ let settled = false;
2596
+ const deadline = HOOK_DEADLINE_MS();
2597
+ const done = (r) => {
2598
+ if (settled)
2599
+ return;
2600
+ settled = true;
2601
+ clearTimeout(timer);
2602
+ emit(r);
2603
+ };
2604
+ let worker;
2605
+ try {
2606
+ worker = new Worker(__filename, { workerData: { buf }, argv: process.argv.slice(2), resourceLimits: { maxOldGenerationSizeMb: 2048 } });
2607
+ }
2608
+ catch (e) {
2609
+ // No worker available: judge inline rather than not at all.
2610
+ emit(collect(buf));
2611
+ return;
2612
+ }
2613
+ const timer = setTimeout(() => {
2614
+ void worker.terminate();
2615
+ done(gateErrorOutcome(`the gate could not reach a verdict within ${Math.round(deadline / 1000)} s — a command or content too complex to judge in time`));
2616
+ }, deadline);
2617
+ worker.once('message', (r) => done(r));
2618
+ worker.once('error', (e) => done(gateErrorOutcome(`the gate stopped without a verdict: ${e.message}`)));
2619
+ worker.once('exit', (code) => { if (!settled)
2620
+ done(gateErrorOutcome(`the gate stopped without a verdict (exit ${code})`)); });
2621
+ });
2622
+ }
1787
2623
  }