@holmes-lab/holmes-kit 0.35.25 → 0.36.1

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 (127) hide show
  1. package/CHANGELOG.md +346 -0
  2. package/README.md +3 -2
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-status.js +4 -1
  5. package/dist/holmes/cli/approve-watch.js +3 -1
  6. package/dist/holmes/cli/approve.d.ts +10 -0
  7. package/dist/holmes/cli/approve.js +31 -1
  8. package/dist/holmes/cli/claude-switches.d.ts +7 -1
  9. package/dist/holmes/cli/claude-switches.js +11 -7
  10. package/dist/holmes/cli/codex-toml.d.ts +3 -0
  11. package/dist/holmes/cli/codex-toml.js +2 -1
  12. package/dist/holmes/cli/doctor.d.ts +25 -1
  13. package/dist/holmes/cli/doctor.js +153 -7
  14. package/dist/holmes/cli/index.js +99 -4
  15. package/dist/holmes/cli/init.js +4 -3
  16. package/dist/holmes/cli/os-notify.d.ts +3 -1
  17. package/dist/holmes/cli/os-notify.js +10 -4
  18. package/dist/holmes/cli/review.d.ts +25 -0
  19. package/dist/holmes/cli/review.js +111 -0
  20. package/dist/holmes/cli/roles-readme.d.ts +11 -0
  21. package/dist/holmes/cli/roles-readme.js +38 -16
  22. package/dist/holmes/cli/roles.d.ts +12 -0
  23. package/dist/holmes/cli/roles.js +86 -0
  24. package/dist/holmes/cli/run.d.ts +65 -0
  25. package/dist/holmes/cli/run.js +308 -0
  26. package/dist/holmes/cli/runtime-binding.d.ts +30 -0
  27. package/dist/holmes/cli/runtime-binding.js +96 -7
  28. package/dist/holmes/cli/test-platform.d.ts +16 -0
  29. package/dist/holmes/cli/test-platform.js +31 -1
  30. package/dist/holmes/config/config.d.ts +49 -0
  31. package/dist/holmes/config/config.js +146 -3
  32. package/dist/holmes/config/project-caps.d.ts +21 -0
  33. package/dist/holmes/config/project-caps.js +114 -0
  34. package/dist/holmes/governance/approval-queue.d.ts +17 -3
  35. package/dist/holmes/governance/approval-queue.js +48 -6
  36. package/dist/holmes/governance/autonomy.d.ts +6 -0
  37. package/dist/holmes/governance/autonomy.js +21 -0
  38. package/dist/holmes/governance/push-gate-runner.d.ts +8 -0
  39. package/dist/holmes/governance/push-gate-runner.js +49 -1
  40. package/dist/holmes/governance/replica-id.d.ts +9 -0
  41. package/dist/holmes/governance/replica-id.js +44 -7
  42. package/dist/holmes/governance/role-policy.d.ts +41 -1
  43. package/dist/holmes/governance/role-policy.js +137 -20
  44. package/dist/holmes/governance/run-mode.d.ts +14 -0
  45. package/dist/holmes/governance/run-mode.js +120 -0
  46. package/dist/holmes/governance/tool-actions.d.ts +30 -0
  47. package/dist/holmes/governance/tool-actions.js +121 -0
  48. package/dist/holmes/guardrail/agent-launch-policy.d.ts +15 -0
  49. package/dist/holmes/guardrail/agent-launch-policy.js +177 -0
  50. package/dist/holmes/guardrail/classification-mode.d.ts +17 -0
  51. package/dist/holmes/guardrail/classification-mode.js +135 -0
  52. package/dist/holmes/guardrail/dynamic-write.d.ts +43 -0
  53. package/dist/holmes/guardrail/dynamic-write.js +304 -0
  54. package/dist/holmes/guardrail/phase.d.ts +2 -1
  55. package/dist/holmes/guardrail/phase.js +22 -8
  56. package/dist/holmes/guardrail/powershell-shell.d.ts +21 -0
  57. package/dist/holmes/guardrail/powershell-shell.js +801 -0
  58. package/dist/holmes/guardrail/refusal-codes.d.ts +24 -0
  59. package/dist/holmes/guardrail/refusal-codes.js +141 -0
  60. package/dist/holmes/guardrail/risk-classifier.d.ts +17 -0
  61. package/dist/holmes/guardrail/risk-classifier.js +242 -26
  62. package/dist/holmes/guardrail/risk-types.d.ts +15 -0
  63. package/dist/holmes/guardrail/run-plan-scope.d.ts +23 -0
  64. package/dist/holmes/guardrail/run-plan-scope.js +155 -0
  65. package/dist/holmes/guardrail/run-refusals.d.ts +116 -0
  66. package/dist/holmes/guardrail/run-refusals.js +348 -0
  67. package/dist/holmes/guardrail/run-stages.d.ts +67 -0
  68. package/dist/holmes/guardrail/run-stages.js +188 -0
  69. package/dist/holmes/guardrail/scope-judgment.d.ts +5 -1
  70. package/dist/holmes/guardrail/scope-judgment.js +8 -10
  71. package/dist/holmes/guardrail/scope-refusal-memory.d.ts +3 -0
  72. package/dist/holmes/guardrail/scope-refusal-memory.js +85 -0
  73. package/dist/holmes/guardrail/shell-words.js +7 -7
  74. package/dist/holmes/guardrail/write-target.d.ts +31 -2
  75. package/dist/holmes/guardrail/write-target.js +118 -16
  76. package/dist/holmes/hooks/adapters/antigravity.d.ts +1 -1
  77. package/dist/holmes/hooks/adapters/antigravity.js +6 -2
  78. package/dist/holmes/hooks/pre-tool-use.d.ts +55 -2
  79. package/dist/holmes/hooks/pre-tool-use.js +749 -89
  80. package/dist/holmes/hooks/session-start.js +5 -3
  81. package/dist/holmes/hooks/stop.d.ts +32 -0
  82. package/dist/holmes/hooks/stop.js +129 -4
  83. package/dist/holmes/mcp/handlers/graph-operations.js +5 -5
  84. package/dist/holmes/mcp/handlers/maintenance-analysis.js +2 -2
  85. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -1
  86. package/dist/holmes/mcp/handlers/operator-inspection.js +3 -1
  87. package/dist/holmes/mcp/handlers/phase-queries.js +16 -1
  88. package/dist/holmes/mcp/handlers/requirement-triage.js +2 -2
  89. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -3
  90. package/dist/holmes/mcp/handlers/spec-approval.js +54 -8
  91. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +1 -0
  92. package/dist/holmes/mcp/handlers/spec-lifecycle.js +3 -3
  93. package/dist/holmes/mcp/handlers/spec-queries.d.ts +7 -0
  94. package/dist/holmes/mcp/handlers/spec-queries.js +5 -0
  95. package/dist/holmes/mcp/handlers/workspace-queries.js +2 -2
  96. package/dist/holmes/mcp/handlers.d.ts +2 -3
  97. package/dist/holmes/mcp/handlers.js +22 -2
  98. package/dist/holmes/mcp/harness-attestation.d.ts +2 -0
  99. package/dist/holmes/mcp/harness-attestation.js +3 -1
  100. package/dist/holmes/mcp/operator-recovery.d.ts +2 -0
  101. package/dist/holmes/mcp/operator-recovery.js +4 -3
  102. package/dist/holmes/mcp/server.js +9 -0
  103. package/dist/holmes/mcp/tool-schemas.js +6 -3
  104. package/dist/holmes/project/root.js +6 -1
  105. package/dist/holmes/project/run-records.d.ts +17 -0
  106. package/dist/holmes/project/run-records.js +126 -0
  107. package/dist/holmes/review/mrp.d.ts +35 -0
  108. package/dist/holmes/review/mrp.js +119 -0
  109. package/dist/holmes/review/verdicts.d.ts +117 -0
  110. package/dist/holmes/review/verdicts.js +345 -0
  111. package/dist/holmes/semantic/cloud-usage.d.ts +20 -0
  112. package/dist/holmes/semantic/cloud-usage.js +106 -0
  113. package/dist/holmes/semantic/embedder.d.ts +15 -6
  114. package/dist/holmes/semantic/embedder.js +84 -3
  115. package/dist/holmes/semantic/local-model.d.ts +21 -2
  116. package/dist/holmes/semantic/local-model.js +14 -3
  117. package/dist/holmes/semantic/tier.d.ts +25 -0
  118. package/dist/holmes/semantic/tier.js +86 -1
  119. package/dist/holmes/semantic/vector-cache.d.ts +1 -0
  120. package/dist/holmes/semantic/vector-cache.js +4 -1
  121. package/dist/holmes/spec/approval-blockers.d.ts +11 -1
  122. package/dist/holmes/spec/approval-blockers.js +70 -2
  123. package/dist/holmes/spec/renumber.d.ts +1 -1
  124. package/dist/holmes/spec/renumber.js +5 -2
  125. package/dist/holmes/spec/transition-policy.d.ts +5 -7
  126. package/dist/holmes/spec/transition-policy.js +17 -2
  127. package/package.json +1 -1
@@ -35,9 +35,14 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DEFAULT_SPECS_DIR = void 0;
37
37
  exports.resolveRmSignals = resolveRmSignals;
38
+ exports.resolveStagedStore = resolveStagedStore;
38
39
  exports.readApprovalFromEnv = readApprovalFromEnv;
39
40
  exports.sedInPlaceFiles = sedInPlaceFiles;
40
41
  exports.hookOutputFor = hookOutputFor;
42
+ exports.authorityMention = authorityMention;
43
+ exports.readOnlySearch = readOnlySearch;
44
+ exports.psShowsEnvironment = psShowsEnvironment;
45
+ exports.agentCliLaunch = agentCliLaunch;
41
46
  exports.dumpsEnvInCommandPosition = dumpsEnvInCommandPosition;
42
47
  exports.ledgerSummaryOf = ledgerSummaryOf;
43
48
  exports.normalizeHookInput = normalizeHookInput;
@@ -48,7 +53,8 @@ exports.gateErrorDecision = gateErrorDecision;
48
53
  exports.wiredSpecsDir = wiredSpecsDir;
49
54
  exports.evaluateHook = evaluateHook;
50
55
  exports.readSpecsSync = readSpecsSync;
51
- // @implements 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
56
+ // @implements 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
57
+ const powershell_shell_1 = require("../guardrail/powershell-shell");
52
58
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
53
59
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
54
60
  // evaluateHook in this file to prove it.
@@ -70,12 +76,24 @@ const constitution_debt_1 = require("../governance/constitution-debt");
70
76
  const tspec_state_1 = require("../guardrail/tspec-state");
71
77
  const identity_1 = require("../governance/identity");
72
78
  const role_policy_1 = require("../governance/role-policy");
79
+ const run_mode_1 = require("../governance/run-mode");
80
+ const classification_mode_1 = require("../guardrail/classification-mode");
81
+ const scope_refusal_memory_1 = require("../guardrail/scope-refusal-memory");
82
+ const agent_launch_policy_1 = require("../guardrail/agent-launch-policy");
73
83
  const risk_classifier_1 = require("../guardrail/risk-classifier");
84
+ const refusal_codes_1 = require("../guardrail/refusal-codes");
85
+ const run_refusals_1 = require("../guardrail/run-refusals");
86
+ const run_plan_scope_1 = require("../guardrail/run-plan-scope");
87
+ const run_stages_1 = require("../guardrail/run-stages");
74
88
  const proposed_content_1 = require("../cpg/proposed-content");
75
89
  const forbidden_edges_1 = require("../cpg/forbidden-edges");
76
90
  const required_calls_1 = require("../cpg/required-calls");
77
91
  const language_parser_1 = require("../cpg/language-parser");
78
92
  const write_target_1 = require("../guardrail/write-target");
93
+ const dynamic_write_1 = require("../guardrail/dynamic-write");
94
+ const SHELL_CODE_WRITE_REASON = '[Holmes-Kit] shell write to a project code file bypasses the No-Spec-No-Code gate — use the Write/Edit tools (gated) or supply out-of-band approval';
95
+ const project_caps_1 = require("../config/project-caps");
96
+ const write_target_2 = require("../guardrail/write-target");
79
97
  const shell_syntax_1 = require("../guardrail/shell-syntax");
80
98
  const anchors_1 = require("../guardrail/anchors");
81
99
  const governance_history_1 = require("../guardrail/governance-history");
@@ -136,7 +154,7 @@ function resolveRmSignals(command, cwd, projectRoot, specsDir, scratchTmpdir) {
136
154
  // was judged — 15 harmful commands were allowed with the root and refused without it.
137
155
  if (!PLAIN_RM.test(command.trim()))
138
156
  return signals;
139
- const absolute = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_1.joinShellText)(command))])]
157
+ const absolute = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_2.joinShellText)(command))])]
140
158
  .filter((raw) => { const t = raw.replace(/^["']/, '').replace(/["']$/, ''); return path.isAbsolute(t) && !/[^A-Za-z0-9._/-]/.test(t) && !t.split('/').includes('..'); });
141
159
  // @implements A-SPEC-773.2 — bounded like the git signals (round 8 of A-SPEC-728): at most 64 targets, each at most
142
160
  // 4,096 characters and 256 components; past that, no target gets the signal and today's verdict stands.
@@ -157,9 +175,81 @@ function resolveRmSignals(command, cwd, projectRoot, specsDir, scratchTmpdir) {
157
175
  }
158
176
  return added ? out : signals;
159
177
  }
178
+ /**
179
+ * @implements A-SPEC-226.3 — what `git status` says about the spec store, for a command that holds a staging verb. One
180
+ * child, none of the command's options (`-c core.fsmonitor=…` would run a program), the fsmonitor hook off and no
181
+ * optional index write. No repository is `undefined` (nothing can be staged); any other failure is `unanswered`.
182
+ */
183
+ function resolveStagedStore(command, projectRoot, specsDir) {
184
+ if (!/\bgit\b/.test(command) || !/\b(?:add|stage|commit)\b/.test(command))
185
+ return undefined;
186
+ if (!fs.existsSync(specsDir))
187
+ return undefined;
188
+ const r = (0, bounded_io_1.gitOnce)(projectRoot, ['--no-optional-locks', '-c', 'core.fsmonitor=false', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--', specsDir], 'repo', { env: (0, root_1.cleanSubprocessEnv)() });
189
+ const answer = (0, bounded_io_1.gitAnswerOf)(r, projectRoot);
190
+ if (answer === 'no-repository')
191
+ return undefined;
192
+ if (answer !== 'answered')
193
+ return { specsDir, unanswered: true };
194
+ let tracked = false;
195
+ let untracked = false;
196
+ const entries = String(r.stdout).split('\0');
197
+ for (let i = 0; i < entries.length; i++) {
198
+ const e = entries[i];
199
+ if (e.length < 3)
200
+ continue;
201
+ if (e[0] === 'R' || e[0] === 'C')
202
+ i++; // a rename or copy carries its source path as the next entry
203
+ if (e.startsWith('??'))
204
+ untracked = true;
205
+ else if (e[1] !== ' ')
206
+ tracked = true;
207
+ }
208
+ return { specsDir, tracked, untracked };
209
+ }
210
+ /**
211
+ * @implements A-SPEC-476.3 — what a file tool's write does to the caps in `<root>/ax.config.json`: `null` leaves both as
212
+ * they are, `'lowered'` only narrows, any other string names what it raises or removes (or that the result is unknown
213
+ * over a file that sets a cap). The text after the write is the Write content, the Edit applied to the disk, or a patch
214
+ * target's post-patch content (no content: the file goes away).
215
+ */
216
+ function projectCapsWriteAct(root, input) {
217
+ const beforeText = (0, project_caps_1.projectConfigText)(root);
218
+ const before = beforeText === undefined ? { ...project_caps_1.NARROWEST_CAPS } : (0, project_caps_1.projectCapsOfText)(beforeText);
219
+ const ti = input.tool_input;
220
+ const tool = input.tool_name.toLowerCase();
221
+ const applyEdit = (text, o, n, all) => {
222
+ if (typeof o !== 'string' || typeof n !== 'string' || o === '')
223
+ return undefined;
224
+ if (!text.includes(o))
225
+ return text; // the tool fails; nothing changes
226
+ return all === true ? text.split(o).join(n) : text.replace(o, () => n);
227
+ };
228
+ let after;
229
+ if (typeof ti.content === 'string')
230
+ after = ti.content;
231
+ else if (tool === 'apply_patch')
232
+ after = null;
233
+ else if (Array.isArray(ti.edits) && typeof beforeText === 'string') {
234
+ let t = beforeText;
235
+ for (const e of ti.edits)
236
+ t = t === undefined ? undefined : applyEdit(t, e?.old_string, e?.new_string, e?.replace_all);
237
+ after = t;
238
+ }
239
+ else if (typeof ti.old_string === 'string') {
240
+ after = typeof beforeText === 'string' ? applyEdit(beforeText, ti.old_string, ti.new_string, ti.replace_all) : beforeText === null ? null : undefined;
241
+ }
242
+ if (after === undefined)
243
+ return (0, project_caps_1.capsAtWidest)(before) ? null : `the result cannot be read, over semantic.maxTier ${before.semantic} and autonomy.ceiling ${before.ceiling}`;
244
+ const next = (0, project_caps_1.projectCapsOfText)(after);
245
+ if ((0, project_caps_1.sameCaps)(before, next))
246
+ return null;
247
+ const raised = (0, project_caps_1.raisedCaps)(before, next);
248
+ return raised.length > 0 ? raised.join(', ') : 'lowered';
249
+ }
160
250
  function gitRmSignals(command, cwd, projectRoot, specsDir) {
161
251
  // A-SPEC-728 (round 24): the text as the shell joins it (`r\m -rf .git`, `eval rm\ -rf\ src`).
162
- const targets = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_1.joinShellText)(command))])];
252
+ const targets = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_2.joinShellText)(command))])];
163
253
  if (targets.length === 0)
164
254
  return undefined;
165
255
  let repoRoot;
@@ -275,7 +365,7 @@ function gitRmSignals(command, cwd, projectRoot, specsDir) {
275
365
  // in (`commandBases`, flow-insensitive: loops, functions and traps run text later — measured), tracked in the project
276
366
  // when that set is unknown. Round 18's per-segment bases missed those and forced "tracked" on every segment the model
277
367
  // could not place (9 of 15 ordinary cleanups denied — measured).
278
- const cb = (0, write_target_1.commandBases)(command, baseReal);
368
+ const cb = (0, write_target_2.commandBases)(command, baseReal);
279
369
  // @implements A-SPEC-734 (round 20) — straight-line text runs where it is written: each segment naming the target keeps
280
370
  // its own base (a segment the model cannot place: its candidates and the start), so a `cd ..` written after the removal
281
371
  // does not move it (`rm -rf build; cd ..` was refused as out-of-project — measured). A command that can run text later
@@ -290,7 +380,7 @@ function gitRmSignals(command, cwd, projectRoot, specsDir) {
290
380
  // unknown, the flow-insensitive set.
291
381
  const segmentBases = new Map();
292
382
  if (cb.ordered && cb.unknown === null) {
293
- const segs = (0, write_target_1.shellSegments)(command, baseReal);
383
+ const segs = (0, write_target_2.shellSegments)(command, baseReal);
294
384
  let reach = segs.length > 2000 ? null : [baseReal];
295
385
  // Round 23: inside an `&&` chain a cd that fails stops the chain, so its successors see only where it leads; where the
296
386
  // chain breaks (`;`, `||`, a newline) every state the chain passed through is possible again.
@@ -313,7 +403,7 @@ function gitRmSignals(command, cwd, projectRoot, specsDir) {
313
403
  else {
314
404
  const next = new Set(andNext ? [] : from);
315
405
  for (const b of from) {
316
- const r = (0, write_target_1.commandBases)(seg.text, b);
406
+ const r = (0, write_target_2.commandBases)(seg.text, b);
317
407
  if (r.unknown !== null) {
318
408
  reach = null;
319
409
  break;
@@ -578,7 +668,8 @@ function startsHolmesServer(command) {
578
668
  function hookOutputFor(_toolName, out) {
579
669
  const { permissionDecision, permissionDecisionReason, ...rest } = out;
580
670
  if (permissionDecision === 'deny') {
581
- return { hookEventName: 'PreToolUse', ...rest, permissionDecision, ...(permissionDecisionReason !== undefined ? { permissionDecisionReason } : {}) };
671
+ // @implements A-SPEC-777 — every deny carries its refusal code as one machine-readable line.
672
+ return { hookEventName: 'PreToolUse', ...rest, permissionDecision, permissionDecisionReason: (0, refusal_codes_1.withRefusalLine)(permissionDecisionReason) };
582
673
  }
583
674
  const context = [typeof rest.additionalContext === 'string' ? rest.additionalContext : '', permissionDecisionReason ?? ''].filter((t) => t !== '').join('\n');
584
675
  const { additionalContext: _c, ...others } = rest;
@@ -782,6 +873,249 @@ function headBeforeLast(text, sep, target, head) {
782
873
  }
783
874
  return false;
784
875
  }
876
+ /**
877
+ * @implements A-SPEC-774.2 §1 — an authority name ANYWHERE, once shell quoting is removed. The usage-shape rule
878
+ * (`NAME=`, `$NAME`, `['NAME'`) missed `printf -v`, `read`, `export "$n=…"` and `HOLMES_\ROLE` (measured 2026-10-17):
879
+ * every builtin and every quoting is a new shape, while the name is the one thing they share.
880
+ */
881
+ function authorityMention(command) {
882
+ // @implements A-SPEC-774.9 §4 — HOLMES_RUN_ID too: the session may neither set nor unset its run marker.
883
+ return /\bHOLMES_(?:ROLE|GATE_BYPASS|AUTONOMOUS_APPROVAL|APPROVAL|LEDGER_KEY|RUN_ID)\b/.test(command.replace(/[\\'"]/g, ''));
884
+ }
885
+ const READ_ONLY_SEARCH = new Set(['grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack', 'cat', 'head', 'tail', 'wc', 'sort', 'uniq', 'cut', 'nl', 'ls', 'cd']);
886
+ const READ_ONLY_GIT = new Set(['grep', 'log', 'show', 'diff', 'blame']);
887
+ /**
888
+ * @implements A-SPEC-774.2 §2 — the one exception: a pipeline that only searches or reads files. No substitution, no
889
+ * eval/source/exec, no redirect beyond `2>/dev/null` / `2>&1`, and every segment starts with a reader. The
890
+ * environment-dump rules still run on it, so `grep NAME /proc/self/environ` stays refused.
891
+ */
892
+ function readOnlySearch(command) {
893
+ if (/\$\(|`|<\(|>\(|\beval\b|\bsource\b|\bexec\b/.test(command))
894
+ return false;
895
+ if (command.replace(/\b2>\/dev\/null\b|\b2>&1\b/g, '').includes('>'))
896
+ return false;
897
+ // @implements A-SPEC-747.3 (A) — the classifier's quote-aware split: a `|` inside a quoted pattern is text. It does
898
+ // not cut at a lone `&` (a background job), so a clause that still holds one outside quotes is not a read.
899
+ for (const seg of (0, risk_classifier_1.splitShellClauses)(command)) {
900
+ if (/&/.test(seg.replace(/"[^"]*"|'[^']*'/g, '').replace(/\b2>&1\b/g, '')))
901
+ return false;
902
+ const toks = seg.trim().split(/\s+/).filter((t) => t !== '');
903
+ if (toks.length === 0)
904
+ continue;
905
+ const word = toks[0];
906
+ if (word === 'git') {
907
+ if (!READ_ONLY_GIT.has(toks[1] ?? ''))
908
+ return false;
909
+ continue;
910
+ }
911
+ if (word === 'find') {
912
+ if (toks.some((t) => /^-(?:exec|execdir|ok|okdir|delete|fprint\w*|fls)$/.test(t)))
913
+ return false;
914
+ continue;
915
+ }
916
+ if (!READ_ONLY_SEARCH.has(word))
917
+ return false;
918
+ }
919
+ return true;
920
+ }
921
+ /**
922
+ * @implements A-SPEC-747.3 (B) — does a `ps` show process environments? Read as options in every clause where `ps`
923
+ * is the command (after `sudo`/`doas`/`command`/`exec`/`nice`/`nohup`/`time`/`xargs`/`watch` and their options):
924
+ * - a dash cluster (`-Ao`) or a BSD cluster (`aux`, `eww`, anywhere in the clause) shows the environment with `e`/`E`;
925
+ * - in a dash cluster a value-taking letter (`o O p U u G g t q M N C k s`) ends it, and its value — the rest of the
926
+ * cluster or the next word — is not read as letters (`-Ao etime,command`); BSD `o O p t k` do the same;
927
+ * - a long option (`--format=…`) is a value, not letters.
928
+ * A `ps` anywhere else (inside quotes, a substitution, `sh -c`) is judged by the old rule: `e` after `ps` in the piece.
929
+ */
930
+ const PS_WRAPPERS = new Set(['sudo', 'doas', 'command', 'exec', 'nice', 'nohup', 'time', 'xargs', 'watch']);
931
+ const PS_LONG_WITH_VALUE = new Set(['--format', '--sort', '--pid', '--ppid', '--user', '--User', '--group', '--Group', '--tty', '--cols', '--columns', '--rows', '--lines', '--width', '--sid', '--quick-pid']);
932
+ function psClauseShowsEnvironment(words) {
933
+ // procps reads BSD options anywhere (`ps --format=pid e`), so every word that is not a value is a cluster.
934
+ for (let i = 0; i < words.length; i++) {
935
+ const w = words[i];
936
+ if (w.startsWith('--')) {
937
+ if (!w.includes('=') && PS_LONG_WITH_VALUE.has(w))
938
+ i++;
939
+ continue;
940
+ }
941
+ const dash = w.startsWith('-');
942
+ const letters = dash ? w.slice(1) : w;
943
+ const valueLetters = dash ? 'oOpUuGgtqMNCks' : 'oOptk';
944
+ for (let j = 0; j < letters.length; j++) {
945
+ const ch = letters[j];
946
+ if (ch === 'e' || ch === 'E')
947
+ return true;
948
+ if (valueLetters.includes(ch)) {
949
+ if (j === letters.length - 1)
950
+ i++;
951
+ break;
952
+ }
953
+ }
954
+ }
955
+ return false;
956
+ }
957
+ function psShowsEnvironment(command) {
958
+ let rest = '';
959
+ for (const clause of (0, risk_classifier_1.splitShellClauses)(command)) {
960
+ const words = clause.split(/\s+/).filter((w) => w !== '').map((w) => w.replace(/^\\/, ''));
961
+ let k = 0;
962
+ while (k < words.length && (/^[A-Za-z_]\w*=/.test(words[k]) || PS_WRAPPERS.has(path.posix.basename(words[k]))
963
+ || (k > 0 && PS_WRAPPERS.has(path.posix.basename(words[k - 1])) && words[k].startsWith('-'))))
964
+ k++;
965
+ if (k < words.length && path.posix.basename(words[k]) === 'ps' && !/["'\x60$()]/.test(clause)) {
966
+ if (psClauseShowsEnvironment(words.slice(k + 1)))
967
+ return true;
968
+ continue;
969
+ }
970
+ rest += `${clause}\n`;
971
+ }
972
+ return tailAfterFirst(rest, /[;&|\n]/, /\bps\b/, /\s-?e\w*\b/);
973
+ }
974
+ // Lower-case program names (prose such as a `Claude` co-author trailer is not a program); a Windows `.exe`/`.cmd`
975
+ // spelling is case-insensitive, as that file system is.
976
+ const AGENT_CLI = { test: (w) => /^(?:claude|codex|gemini|agy|aider|cursor-agent|opencode|goose|qwen)$/.test(w)
977
+ || /^(?:claude|codex|gemini|agy|aider|cursor-agent|opencode|goose|qwen)\.(?:exe|cmd)$/i.test(w) };
978
+ const AGENT_PACKAGES = new Set(['@anthropic-ai/claude-code', '@openai/codex', '@google/gemini-cli']);
979
+ /** Commands that only print, search or read text: an agent name among their words is data, not a launch (774.5). */
980
+ const INERT_TEXT_COMMANDS = new Set(['echo', 'printf', 'gh', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack', 'ls', 'cat', 'head', 'tail', 'wc',
981
+ 'which', 'type', 'man', 'cd', 'mkdir', 'touch']);
982
+ const VERSION_ONLY = new Set(['--version', '-v', '-V', '--help', '-h']);
983
+ /**
984
+ * @implements A-SPEC-774.2 §3 — whether the command starts another agent CLI. A name can be assembled at run time
985
+ * (`n=HOLMES_RO; export "${n}LE=x"`), so no text rule over the name is complete; the act the name exists for is a child
986
+ * agent with a different authority, and that act is refused on its own. `--version`/`--help` alone is not a launch.
987
+ */
988
+ function agentCliLaunch(command) {
989
+ return agentLaunchSegments(command).length > 0 || interpreterSpawnsAgent(command);
990
+ }
991
+ /** @implements A-SPEC-774.9 — an interpreter that spawns an agent by name (the 774.2 rule, kept apart for reuse). */
992
+ function interpreterSpawnsAgent(command) {
993
+ return /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b/.test(command)
994
+ && /\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|subprocess|system|popen|Popen)\b/.test(command)
995
+ && /['"](?:claude|codex|gemini|agy|aider|cursor-agent|opencode|goose|qwen)(?:\.exe|\.cmd)?['"]/.test(command);
996
+ }
997
+ /** The words of every segment that launches an agent CLI (A-SPEC-774.5 §1), quote-aware. */
998
+ /**
999
+ * @implements A-SPEC-774.26 — with each word, the quoted span it came from (-1: unquoted or mixed), so the option check
1000
+ * can tell a quoted prompt (`-p "… cut -d= …"`) from options, and a quoted program (`tmux new -d 'claude …'`) from both.
1001
+ */
1002
+ function agentLaunchSegments(command) {
1003
+ const found = [];
1004
+ // @implements A-SPEC-774.5 §1 — by WORD, not by wrapper. The wrapper list (774.2) was walked through by `tmux new -d
1005
+ // '…'`, `script -q /dev/null …` and `watch …` (supervisor probe, 2026-10-17): launchers have no end. Quoting is
1006
+ // removed first, so a program inside a quoted argument is read as words of the same segment; the exceptions are a
1007
+ // segment led by an inert text command, and the agent's own `--version`/`--help`.
1008
+ // Segments are split on UNQUOTED separators only — a `|` inside a grep pattern is not a pipe (measured on this
1009
+ // change: `grep -n "a|claude" f` read `claude` as a command). Quoting is removed inside each segment afterwards.
1010
+ const segs = [];
1011
+ let cur = '';
1012
+ let curSpans = [];
1013
+ let quote = null;
1014
+ let span = -1;
1015
+ let spans = 0;
1016
+ const add = (s, at) => { for (const c of s) {
1017
+ cur += c;
1018
+ curSpans.push(at);
1019
+ } };
1020
+ for (let k = 0; k < command.length; k++) {
1021
+ const ch = command[k];
1022
+ if (quote) {
1023
+ if (ch === quote)
1024
+ quote = null;
1025
+ else if (ch === '\\' && quote === '"') {
1026
+ add(command[++k] ?? '', span);
1027
+ continue;
1028
+ }
1029
+ else
1030
+ add(ch, span);
1031
+ continue;
1032
+ }
1033
+ if (ch === '\\') {
1034
+ add(command[++k] ?? '', -1);
1035
+ continue;
1036
+ }
1037
+ if (ch === "'" || ch === '"') {
1038
+ quote = ch;
1039
+ span = spans++;
1040
+ continue;
1041
+ } // quoting joins, as the shell does: cl'aude' is claude
1042
+ if (/[|;&\n()]/.test(ch)) {
1043
+ segs.push({ text: cur, spanOf: curSpans });
1044
+ cur = '';
1045
+ curSpans = [];
1046
+ continue;
1047
+ }
1048
+ add(ch, -1);
1049
+ }
1050
+ segs.push({ text: cur, spanOf: curSpans });
1051
+ for (const seg of segs) {
1052
+ // A quote of the other kind inside a quoted span stays in the text (`'… "claude -p x"'`); it is not part of a name.
1053
+ const rawWords = [];
1054
+ let wcur = '';
1055
+ let wspan = null;
1056
+ const flush = () => {
1057
+ const w = wcur.replace(/["'\\]/g, '');
1058
+ if (w !== '')
1059
+ rawWords.push({ w, span: wspan ?? -1 });
1060
+ wcur = '';
1061
+ wspan = null;
1062
+ };
1063
+ for (let k = 0; k < seg.text.length; k++) {
1064
+ const c = seg.text[k];
1065
+ if (/\s/.test(c)) {
1066
+ flush();
1067
+ continue;
1068
+ }
1069
+ const s = seg.spanOf[k];
1070
+ wspan = wspan === null ? s : wspan === s ? s : -1;
1071
+ wcur += c;
1072
+ }
1073
+ flush();
1074
+ const words = rawWords.map((r) => r.w);
1075
+ const wordSpans = rawWords.map((r) => r.span);
1076
+ let i = 0;
1077
+ while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))
1078
+ i++; // leading NAME=value
1079
+ const rest = words.slice(i);
1080
+ if (rest.length === 0)
1081
+ continue;
1082
+ const base = (w) => w.split(/[\\/]/).pop() ?? w;
1083
+ const pkgOf = (w) => (/^(@?[^@]+)/.exec(w) ?? ['', ''])[1];
1084
+ // An option value names a program too (`git -c core.pager=claude`), so the text after the last `=` counts.
1085
+ const isAgent = (w) => [w, w.slice(w.lastIndexOf('=') + 1)].some((v) => AGENT_CLI.test(base(v)) || AGENT_PACKAGES.has(pkgOf(v)));
1086
+ if (!rest.some(isAgent))
1087
+ continue;
1088
+ const lead = base(rest[0]);
1089
+ if (isAgent(rest[0]) && rest.length > 1 && rest.slice(1).every((w) => VERSION_ONLY.has(w)))
1090
+ continue;
1091
+ if (INERT_TEXT_COMMANDS.has(lead))
1092
+ continue;
1093
+ if (lead === 'git') {
1094
+ // Only git's own options run a program: global ones before the subcommand (`-c core.pager=…`), and
1095
+ // `rebase -x/--exec`. The same letters inside a commit message are text.
1096
+ let j = 1;
1097
+ let runs = false;
1098
+ while (j < rest.length && rest[j].startsWith('-')) {
1099
+ if (/^(?:-c|--config-env|--exec-path)$/.test(rest[j])) {
1100
+ runs = true;
1101
+ j += 2;
1102
+ continue;
1103
+ }
1104
+ if (/^(?:--config-env=|--exec-path=)/.test(rest[j]))
1105
+ runs = true;
1106
+ j++;
1107
+ }
1108
+ if (rest[j] === 'rebase' && rest.slice(j + 1).some((w) => /^(?:-x|--exec(?:=.*)?)$/.test(w)))
1109
+ runs = true;
1110
+ if (!runs)
1111
+ continue;
1112
+ }
1113
+ if (lead === 'find' && !rest.some((w) => /^-(?:exec|execdir|ok|okdir)$/.test(w)))
1114
+ continue;
1115
+ found.push({ words, spans: wordSpans }); // with the leading NAME=value words: the interactive allowlist judges them (774.11)
1116
+ }
1117
+ return found;
1118
+ }
785
1119
  function dumpsEnvInCommandPosition(command, depth = 0) {
786
1120
  if (depth > 3)
787
1121
  return false;
@@ -1008,7 +1342,7 @@ function ledgerSummaryOf(reason) {
1008
1342
  const at = reason.indexOf(' Operator: ');
1009
1343
  return at === -1 ? reason : reason.slice(0, at);
1010
1344
  }
1011
- function normalizeHookInput(raw) {
1345
+ function normalizeHookInput(raw, host = process.platform) {
1012
1346
  const str = (v) => (typeof v === 'string' ? v : undefined);
1013
1347
  if (!raw || typeof raw !== 'object')
1014
1348
  return { tool_name: '', tool_input: {} };
@@ -1021,6 +1355,10 @@ function normalizeHookInput(raw) {
1021
1355
  const malformed = !tiIsObject
1022
1356
  || ['file_path', 'notebook_path'].some((f) => f in ti && typeof ti[f] !== 'string');
1023
1357
  const out = {};
1358
+ // @implements A-SPEC-776 — the fields below are the only ones kept, so a foreign tool's own path fields are read now.
1359
+ const foreignPaths = (0, write_target_2.foreignMcpPaths)(str(r.tool_name), ti);
1360
+ if (foreignPaths)
1361
+ out.foreign_paths = foreignPaths;
1024
1362
  // Assigned individually so an undefined never becomes a present-but-undefined key downstream.
1025
1363
  // @implements A-SPEC-232 — surrounding whitespace is trimmed HERE, at the input boundary, not
1026
1364
  // in each gate. Measured 2026-08-22: `src/app.ts ` walked past No-Spec-No-Code entirely, because
@@ -1039,9 +1377,25 @@ function normalizeHookInput(raw) {
1039
1377
  const ns = str(ti.new_string ?? ti.ReplacementContent);
1040
1378
  if (ns !== undefined)
1041
1379
  out.new_string = ns;
1042
- const cmd = str(ti.command ?? ti.CommandLine);
1380
+ // @implements A-SPEC-790 — a PowerShell tool's command is read with PowerShell syntax and judged from here on as the
1381
+ // Bash payload that performs the same acts. Measured 2026-10-18: the shell branch ran for 'bash' only, so Claude
1382
+ // Code's PowerShell tool deleted, wrote and force-pushed ungated. Text that cannot be read is refused in evaluateHook.
1383
+ const cmdRaw = str(ti.command ?? ti.CommandLine);
1384
+ const ps = cmdRaw !== undefined && (str(r.tool_name) ?? '').toLowerCase() === 'powershell' ? (0, powershell_shell_1.powershellAsShell)(cmdRaw) : null;
1385
+ const psShell = ps !== null && 'shell' in ps ? ps.shell : undefined;
1386
+ const cmd = psShell ?? cmdRaw;
1043
1387
  if (cmd !== undefined)
1044
1388
  out.command = cmd;
1389
+ // @implements A-SPEC-790.2 — Codex on Windows runs its shell tool in Windows PowerShell 5.1 (measured 2026-10-20,
1390
+ // codex-cli 0.154.0), but names it Bash; a Codex-shaped payload (turn_id without prompt_id, as hookHarnessOf reads it)
1391
+ // on a win32 host also carries its PowerShell reading. The host is an argument so either host's answer is testable.
1392
+ const toolLower = (str(r.tool_name) ?? '').toLowerCase();
1393
+ const codexShaped = typeof r.turn_id === 'string' && r.turn_id !== '' && !(typeof r.prompt_id === 'string' && r.prompt_id !== '');
1394
+ // @implements A-SPEC-790.7 — the Antigravity adapter marks its run_command on win32; the mark only adds a reading.
1395
+ const agyMarked = r.shell_dialect === 'powershell';
1396
+ const codexPs = host === 'win32' && (codexShaped || agyMarked) && ps === null && cmdRaw !== undefined
1397
+ && (toolLower === 'bash' || toolLower === 'shell')
1398
+ ? { ...(0, powershell_shell_1.powershellAsShell)(cmdRaw), harness: codexShaped ? 'codex' : 'antigravity' } : null;
1045
1399
  const wd = str(ti.workdir);
1046
1400
  if (wd !== undefined && wd.trim() !== '')
1047
1401
  out.workdir = wd.trim();
@@ -1071,13 +1425,13 @@ function normalizeHookInput(raw) {
1071
1425
  // The shell tool: its command when it runs `apply_patch`, and any nested whole patch. Any other write tool: only a
1072
1426
  // whole patch — prose that quotes patch lines is not a write. A path field does not hide the patch beside it.
1073
1427
  // A patch that cannot be read one way (no target, an empty path, too many, an indented header) is unreadable.
1074
- const toolName = (str(r.tool_name) ?? '').toLowerCase();
1428
+ const toolName = psShell !== undefined ? 'bash' : (str(r.tool_name) ?? '').toLowerCase();
1075
1429
  let patchUnreadable = false;
1076
1430
  let noopPaths = null; // @implements A-SPEC-769.7
1077
1431
  // @implements A-SPEC-163.7 — why: a shell command refused for a patch marker is told so (it has no file path to miss).
1078
1432
  let shellMarked = false;
1079
1433
  let otherUnreadable = false;
1080
- if (!write_target_1.READ_ONLY_TOOLS.includes(toolName)) {
1434
+ if (!write_target_2.READ_ONLY_TOOLS.includes(toolName)) {
1081
1435
  const strings = [];
1082
1436
  const collect = (v, depth) => {
1083
1437
  if (typeof v === 'string') {
@@ -1105,7 +1459,7 @@ function normalizeHookInput(raw) {
1105
1459
  // @implements A-SPEC-163.4 — which strings are patches is 163.2's rule; whether one is JUDGED is one positive
1106
1460
  // grammar. The shell tool's command is a patch only as one quoted-heredoc `apply_patch` (rule 3); every string
1107
1461
  // read as a patch must be canonical (rules 1-2). Anything else is unreadable, not unread.
1108
- const patches = strings.filter((text) => !(isShell && text === cmd) && (isPatchTool ? (0, write_target_1.hasPatchEnvelope)(text) : (0, write_target_1.isWholePatch)(text)));
1462
+ const patches = strings.filter((text) => !(isShell && text === cmd) && (isPatchTool ? (0, write_target_2.hasPatchEnvelope)(text) : (0, write_target_2.isWholePatch)(text)));
1109
1463
  if (isShell && cmd !== undefined) {
1110
1464
  const shellPatch = shellPatchOf(cmd);
1111
1465
  if (shellPatch === 'unreadable') {
@@ -1116,14 +1470,15 @@ function normalizeHookInput(raw) {
1116
1470
  patches.push(shellPatch.text);
1117
1471
  }
1118
1472
  if (patches.length > 0) {
1119
- const targets = patches.flatMap((text) => (0, write_target_1.patchTargetsOf)(text));
1120
- if (targets.length === 0 || targets.length > write_target_1.PATCH_TARGETS_MAX || patches.some((text) => !(0, write_target_1.canonicalPatch)(text))) {
1473
+ const targets = patches.flatMap((text) => (0, write_target_2.patchTargetsOf)(text));
1474
+ if (targets.length === 0 || targets.length > write_target_2.PATCH_TARGETS_MAX || patches.some((text) => !(0, write_target_2.canonicalPatch)(text))) {
1121
1475
  patchUnreadable = true;
1122
1476
  otherUnreadable = true;
1123
1477
  // @implements A-SPEC-769.7 — when the targets are readable and the only fault is a context-only update block,
1124
1478
  // the refusal names that condition and those paths instead of a missing path.
1125
- if (targets.length > 0 && targets.length <= write_target_1.PATCH_TARGETS_MAX) {
1126
- const reasons = patches.map(write_target_1.canonicalPatchReason);
1479
+ if (targets.length > 0 && targets.length <= write_target_2.PATCH_TARGETS_MAX) {
1480
+ // A-SPEC-163.8: the text alone — a bare `map(canonicalPatchReason)` would hand the array index to its options.
1481
+ const reasons = patches.map((text) => (0, write_target_2.canonicalPatchReason)(text));
1127
1482
  if (reasons.every((why) => why === null || why === 'no-op') && reasons.includes('no-op')) {
1128
1483
  noopPaths = targets.filter((t) => t.kind === 'update' && !/^[+-]/m.test(t.hunk ?? '')).map((t) => t.path);
1129
1484
  }
@@ -1133,7 +1488,10 @@ function normalizeHookInput(raw) {
1133
1488
  out.patch_targets = targets;
1134
1489
  }
1135
1490
  }
1136
- return { tool_name: str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(malformed ? { malformed: true } : {}),
1491
+ const sessionId = str(r.session_id);
1492
+ return { tool_name: psShell !== undefined ? 'Bash' : str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(sessionId ? { session_id: sessionId } : {}), ...(malformed ? { malformed: true } : {}),
1493
+ ...(ps !== null && 'unjudgeable' in ps ? { powershellUnjudgeable: ps.unjudgeable } : {}),
1494
+ ...(codexPs !== null ? { codexPowerShell: codexPs } : {}),
1137
1495
  ...(patchUnreadable ? { patchUnreadable: true } : {}), ...(shellMarked && !otherUnreadable ? { patchUnreadableCause: 'shell-marker' } : {}),
1138
1496
  ...(noopPaths !== null && !shellMarked ? { patchUnreadableCause: 'no-op', patchNoopPaths: noopPaths } : {}) };
1139
1497
  }
@@ -1277,6 +1635,23 @@ function wiredSpecsDir(argv, env) {
1277
1635
  exports.DEFAULT_SPECS_DIR = '.ax/specs';
1278
1636
  // @implements A-SPEC-100.2
1279
1637
  function evaluateHook(input, specsDir, opts) {
1638
+ // @implements A-SPEC-790.2 — a Codex shell payload on Windows: the Bash reading first (a denial there is the decision,
1639
+ // and nothing more is filed); then the PowerShell text Codex actually runs. Only ever stricter than the Bash reading.
1640
+ const codexPs = input.codexPowerShell;
1641
+ if (codexPs !== undefined) {
1642
+ const { codexPowerShell: _bashOnly, ...bashInput } = input;
1643
+ // @implements A-SPEC-790.8 — what the first reading spent answers the second for the same command: the operator's
1644
+ // single-use grant was spent by one reading and looked for anew by the other, so a granted command never passed.
1645
+ let spent = [];
1646
+ const bashVerdict = evaluateHook(bashInput, specsDir, { ...opts, onApprovalsSpent: (a) => { spent = a; } });
1647
+ if (bashVerdict.permissionDecision === 'deny')
1648
+ return bashVerdict;
1649
+ if ('unjudgeable' in codexPs) {
1650
+ const who = codexPs.harness === 'antigravity' ? 'an Antigravity' : 'a Codex';
1651
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${who} command that PowerShell runs and the gate cannot judge (${codexPs.unjudgeable}) is refused (REQ-790)` };
1652
+ }
1653
+ return evaluateHook({ ...bashInput, tool_input: { ...bashInput.tool_input, command: codexPs.shell } }, specsDir, { ...opts, carriedApprovals: { command: String(bashInput.tool_input?.command ?? ''), reading: codexPs.shell, approvals: spent } });
1654
+ }
1280
1655
  // @implements A-SPEC-728 (rule 40) — a spec edit's result is shared within this call only: a caller that hands the same
1281
1656
  // tool_input object back changed must not be judged on the earlier result.
1282
1657
  editedMemo = null;
@@ -1286,6 +1661,11 @@ function evaluateHook(input, specsDir, opts) {
1286
1661
  // disk); a move's source is judged as a delete; a relative target is `<base>/<path>` as written, not folded first;
1287
1662
  // a patch that cannot be read or applied is denied. When no target is denied, a payload with a path field or a
1288
1663
  // shell command is then judged as before.
1664
+ // @implements A-SPEC-790 — a PowerShell command whose text cannot be read is refused rather than judged.
1665
+ const psUnjudgeable = input.powershellUnjudgeable;
1666
+ if (psUnjudgeable !== undefined) {
1667
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a PowerShell command that cannot be judged (${psUnjudgeable}) is refused (REQ-790)` };
1668
+ }
1289
1669
  if (input.patchUnreadable) {
1290
1670
  const cause = input;
1291
1671
  // @implements A-SPEC-769.7 — four conditions, four sentences: shell marker, no-op update, and (below) the
@@ -1308,7 +1688,7 @@ function evaluateHook(input, specsDir, opts) {
1308
1688
  const stat = fs.statSync(source);
1309
1689
  if (!stat.isFile() || stat.size > PATCH_UPDATE_BYTES_MAX)
1310
1690
  return null;
1311
- return (0, write_target_1.applyPatchUpdateDetailed)(fs.readFileSync(source, 'utf8'), hunk);
1691
+ return (0, write_target_2.applyPatchUpdateDetailed)(fs.readFileSync(source, 'utf8'), hunk);
1312
1692
  }
1313
1693
  catch {
1314
1694
  return null;
@@ -1365,10 +1745,10 @@ function evaluateHook(input, specsDir, opts) {
1365
1745
  const command = input.tool_input.command;
1366
1746
  // @implements A-SPEC-728 (round 17) — the shell runs where the harness says (a Codex `workdir`, the
1367
1747
  // payload `cwd`), inside the project; relative words are judged from there, not from the root.
1368
- const shellBase = (0, write_target_1.shellBaseFor)(opts.projectRoot, input.tool_input.workdir, input.cwd);
1748
+ const shellBase = (0, write_target_2.shellBaseFor)(opts.projectRoot, input.tool_input.workdir, input.cwd);
1369
1749
  // @implements A-SPEC-728 (rule 42) — split once, before any other judgement, and refused past 4,096 segments: seventeen
1370
1750
  // shapes of repeated separators took 2.4–6.1 s at 256 KB, their cost spread over every segment of every rule (measured).
1371
- const segmentsOnce = (0, write_target_1.shellSegments)(command, shellBase);
1751
+ const segmentsOnce = (0, write_target_2.shellSegments)(command, shellBase);
1372
1752
  if (segmentsOnce.length > SHELL_SEGMENTS_MAX) {
1373
1753
  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)` };
1374
1754
  }
@@ -1382,12 +1762,21 @@ function evaluateHook(input, specsDir, opts) {
1382
1762
  catch {
1383
1763
  rmTargetSignals = undefined;
1384
1764
  }
1765
+ // @implements A-SPEC-226.3 — unlike the rm signals, a resolver that throws is not "no signal": it did not answer.
1766
+ let stagedStore;
1767
+ try {
1768
+ stagedStore = opts.resolveStagedStore?.(command);
1769
+ }
1770
+ catch {
1771
+ stagedStore = { specsDir, unanswered: true };
1772
+ }
1385
1773
  // projectRoot scopes the protected-`.ax` rules to THIS repository's governance directory; without
1386
1774
  // it the substring match gated `.ax` paths in any other project on the machine.
1387
1775
  const action = {
1388
1776
  kind: 'shell', target: command, command, rmTargetSignals,
1389
1777
  projectRoot: (0, linear_match_1.trimTrailing)(opts.projectRoot.replace(/\\/g, '/'), '/'),
1390
1778
  cwd: shellBase,
1779
+ ...(stagedStore ? { stagedStore } : {}),
1391
1780
  };
1392
1781
  const assess = opts?.assess ?? risk_classifier_1.assessRisk;
1393
1782
  const approval = opts.approval;
@@ -1410,13 +1799,21 @@ function evaluateHook(input, specsDir, opts) {
1410
1799
  // `rm -rf /`) has already judged its deletions; the wiring-deletion rule below must not re-deny it.
1411
1800
  // @implements A-SPEC-477.1 — spend only after every shell check succeeds.
1412
1801
  const pendingApprovals = [];
1802
+ // @implements A-SPEC-790.8 — a carried approval answers first, only for its own kind and the command as written;
1803
+ // it is not spent again and files no request. Every other approval resolves as before, against the text judged.
1804
+ const carried = opts.carriedApprovals?.reading === command ? opts.carriedApprovals : undefined;
1805
+ const resolveForCommand = (kind) => {
1806
+ const held = carried?.approvals.find((a) => (0, risk_gate_1.approvalCovers)(a, { kind, target: carried.command }, nowTs));
1807
+ return held !== undefined ? { approval: held, source: 'carried' }
1808
+ : (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind, target: command }, nowTs);
1809
+ };
1413
1810
  const legacySessionApproval = approval?.scope === undefined
1414
1811
  && (0, risk_gate_1.approvalCovers)(approval, { kind: 'config-write', target: command }, nowTs);
1415
1812
  let hardHitlCovered = false;
1416
1813
  if (assessment.level === 'hard-hitl') {
1417
1814
  // @implements A-SPEC-245 — env first, then the grant files. The grant's mandatory nonce rides
1418
1815
  // the SAME atomic ledger consumption below, so hard-hitl single-use needs no new machinery.
1419
- const resolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind: 'shell', target: command }, nowTs);
1816
+ const resolved = resolveForCommand('shell');
1420
1817
  const covers = resolved !== undefined;
1421
1818
  const deny = (why) => ({
1422
1819
  permissionDecision: 'deny',
@@ -1472,7 +1869,20 @@ function evaluateHook(input, specsDir, opts) {
1472
1869
  // Which of the two harms this is. Setting a role or a bypass is not reading a secret, it is
1473
1870
  // self-granting authority — reporting both as "reads the environment" sends an operator to
1474
1871
  // hunt a leak that never happened.
1475
- const GRANTS_SELF = /\bHOLMES_(?:ROLE|GATE_BYPASS|AUTONOMOUS_APPROVAL|SEMANTIC_API_KEY)\b/.test(command);
1872
+ // @implements A-SPEC-774.2 §5 — read over the de-quoted text, so `HOLMES_\ROLE=` is reported as what it is.
1873
+ const GRANTS_SELF = /\bHOLMES_(?:ROLE|GATE_BYPASS|AUTONOMOUS_APPROVAL|SEMANTIC_API_KEY)\b/.test(command.replace(/[\\'"]/g, ''));
1874
+ // @implements A-SPEC-774.9 — a launch is refused in a run (judged by the session, fail-closed); interactively
1875
+ // only a launch that switches the child's gate off is refused, so a person keeps what 0.35.25 allowed.
1876
+ const RUN = (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id);
1877
+ // @implements A-SPEC-774.11 §2 — interactively a launch passes only the known-safe option list; a deny-list of
1878
+ // gate-off flags did not close.
1879
+ // @implements A-SPEC-774.12 — and one gate-off marker list serves the shell segment and the interpreter spawn,
1880
+ // which cannot be read option by option (`spawnSync('codex',[…,'-c','approval_policy=never'])` passed).
1881
+ const GATE_OFF = RUN.run ? null
1882
+ // @implements A-SPEC-774.26 — the markers read the segment's option words, not its quoted prompt.
1883
+ : (agentLaunchSegments(command).map((s) => (0, agent_launch_policy_1.interactiveLaunchIssue)(s.words, s.spans) ?? (0, agent_launch_policy_1.gateOffMarker)((0, agent_launch_policy_1.launchOptionWords)(s.words, s.spans).join(' '))).find((x) => x !== null)
1884
+ ?? (interpreterSpawnsAgent(command) ? (0, agent_launch_policy_1.gateOffMarker)(command) : null));
1885
+ const AGENT_LAUNCH = (RUN.run && agentCliLaunch(command)) || GATE_OFF !== null;
1476
1886
  const providerCredential = /\b(?:GEMINI_API_KEY|GOOGLE_API_KEY)\b/.test(command);
1477
1887
  const usesSecret =
1478
1888
  // @implements A-SPEC-477 — the credential file is the same secret at rest; reading,
@@ -1486,15 +1896,18 @@ function evaluateHook(input, specsDir, opts) {
1486
1896
  // A quoted key only counts as a LOOKUP when something indexes or calls with it —
1487
1897
  // `env['VAR']`, `getenv("VAR")`, `ENVIRON["VAR"]`. A quoted bare word after a space is a
1488
1898
  // search pattern (`grep "VAR" file`), which is the false positive being removed.
1489
- new RegExp(String.raw `[[(]\s*['"\`]${SECRET}['"\`]`).test(command);
1490
- const dumpsEnv = usesSecret ||
1899
+ new RegExp(String.raw `[[(]\s*['"\`]${SECRET}['"\`]`).test(command) ||
1900
+ // @implements A-SPEC-774.2 §1-2 — the name in any position or spelling, except inside a read-only search.
1901
+ (authorityMention(command) && !readOnlySearch(command));
1902
+ const dumpsEnv = AGENT_LAUNCH ||
1903
+ usesSecret ||
1491
1904
  dumpsEnvInCommandPosition(command) || // env/printenv as a COMMAND
1492
1905
  // @implements A-SPEC-728 (round 4) — `[ \t]` where `\s` spanned newlines: 190 000 newlines made
1493
1906
  // every start re-scan the rest (23 s); a newline is itself a separator, so the verdict is the same.
1494
1907
  /(^|[;&|\n][ \t]*)(?:set|export[ \t]+-p|declare[ \t]+-x|typeset[ \t]+-x)[ \t]*(?:$|[;&|\n>])/.test(command) ||
1495
1908
  /\$\{!\s*\w/.test(command) || // ${!VAR*} indirection
1496
1909
  /\/proc\/(?:self|\d+|\$\$|\$\{?\w+\}?)\/environ/.test(command) || // /proc/*/environ incl. $$
1497
- tailAfterFirst(command, /[;&|\n]/, /\bps\b/, /\s-?e\w*\b/) || // ps e / ps -e www
1910
+ psShowsEnvironment(command) || // ps e / ps -e www / ps -E (A-SPEC-747.3)
1498
1911
  // Interpreter access to the environment, in any dash form (-e/-c/-p/--eval/--print/eval).
1499
1912
  // @implements A-SPEC-163
1500
1913
  // The bare `\bENV\b` alternative is GONE. It was narrowed once already (it denied
@@ -1535,12 +1948,16 @@ function evaluateHook(input, specsDir, opts) {
1535
1948
  };
1536
1949
  }
1537
1950
  if (dumpsEnv) {
1538
- const reason = GRANTS_SELF
1539
- ? '[Holmes-Kit] the command accesses Holmes authority or semantic-egress configuration — requires operator approval'
1540
- : providerCredential
1541
- ? '[Holmes-Kit] the command accesses a protected provider credential — requires operator approval'
1542
- : '[Holmes-Kit] command reads or dumps process environment (holds out-of-band approval secrets) — requires operator approval';
1543
- const resolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind: 'config-write', target: command }, nowTs);
1951
+ const reason = GATE_OFF !== null
1952
+ ? `[Holmes-Kit] the command launches an agent CLI with a setting that can switch its gate off (${GATE_OFF}) — an interactive launch may carry only known-safe options: prompt, model, effort, working directory, read-only or workspace sandbox, output format (A-SPEC-774.11), and the autonomy options measured to keep the child's gate (A-SPEC-774.26); run it without that option, or ask the operator`
1953
+ : AGENT_LAUNCH
1954
+ ? `[Holmes-Kit] the command launches an agent CLI in a run (${RUN.why}) — a child agent's role and environment are set by the orchestrator's adapter, not by the session (A-SPEC-774.9) — requires operator approval`
1955
+ : GRANTS_SELF
1956
+ ? '[Holmes-Kit] the command accesses Holmes authority or semantic-egress configuration — requires operator approval'
1957
+ : providerCredential
1958
+ ? '[Holmes-Kit] the command accesses a protected provider credential — requires operator approval'
1959
+ : '[Holmes-Kit] command reads or dumps process environment (holds out-of-band approval secrets) — requires operator approval';
1960
+ const resolved = resolveForCommand('config-write');
1544
1961
  if (!resolved) {
1545
1962
  let hint = (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: command, why: reason });
1546
1963
  // The queue deliberately suppresses duplicate writes, not the pending operator decision.
@@ -1601,9 +2018,10 @@ function evaluateHook(input, specsDir, opts) {
1601
2018
  // of the path, not an argument boundary. `[^'"\s]*` stopped at the first space and missed
1602
2019
  // `open('C:\Users\Given Family\a.ts','w')`; `[^'"]*` keeps the space and still cannot cross a quote.
1603
2020
  const NOT_QUOTE = String.raw `[^'"]*`;
1604
- const QUOTED_PATH = new RegExp(
1605
- // @implements A-SPEC-728 — plus the Codex user-level files, judged by identity below.
1606
- String.raw `['"](` + NOT_QUOTE + String.raw `\.` + CODE_EXT + '|' + NOT_QUOTE + CONFIG_FILE + '|' + NOT_QUOTE + String.raw `(?:config\.toml|hooks\.json)` + String.raw `)['"]`, 'g');
2021
+ // @implements A-SPEC-728 — plus the Codex user-level files, judged by identity below (USER_CFG_RE).
2022
+ // @implements A-SPEC-774.1 — every quoted path-like literal (a superset of the code, config and Codex
2023
+ // spellings it listed); the config rule keeps its own CFG_RE filter and the code rule asks the classifier.
2024
+ const QUOTED_PATH = new RegExp(String.raw `['"](` + NOT_QUOTE + String.raw `[\w.+-])['"]`, 'g');
1607
2025
  const out = [];
1608
2026
  for (const m of command.matchAll(QUOTED_PATH))
1609
2027
  if (m[1])
@@ -1664,14 +2082,14 @@ function evaluateHook(input, specsDir, opts) {
1664
2082
  // and the caller fails CLOSED — but only when such a candidate exists, so `cd "$X" && npm
1665
2083
  // test` stays free.
1666
2084
  const judgeCand = (c, roots) => {
1667
- if ((0, write_target_1.absoluteKindOf)(c.raw) !== null || isTilde(c.raw))
1668
- return (0, write_target_1.resolvesInside)(c.raw, roots) ? 'in' : 'out';
2085
+ if ((0, write_target_2.absoluteKindOf)(c.raw) !== null || isTilde(c.raw))
2086
+ return (0, write_target_2.resolvesInside)(c.raw, roots) ? 'in' : 'out';
1669
2087
  if (c.base === null)
1670
2088
  return 'unknown';
1671
- const pp = (0, write_target_1.pathFlavorFor)(c.base, c.raw);
2089
+ const pp = (0, write_target_2.pathFlavorFor)(c.base, c.raw);
1672
2090
  const abs = pp.resolve(c.base, c.raw);
1673
- const kind = (0, write_target_1.absoluteKindOf)(abs);
1674
- return (0, write_target_1.resolvesInside)(abs, roots, kind === 'drive' || kind === 'unc' ? path.win32 : path.posix) ? 'in' : 'out';
2091
+ const kind = (0, write_target_2.absoluteKindOf)(abs);
2092
+ return (0, write_target_2.resolvesInside)(abs, roots, kind === 'drive' || kind === 'unc' ? path.win32 : path.posix) ? 'in' : 'out';
1675
2093
  };
1676
2094
  const collectSeg = (seg, re, list) => {
1677
2095
  for (const m of seg.text.matchAll(re)) {
@@ -1682,7 +2100,11 @@ function evaluateHook(input, specsDir, opts) {
1682
2100
  };
1683
2101
  // @implements A-SPEC-728 (round 5) — the lazy `VERB[^;|&]*?PATH` extractions, in linear time
1684
2102
  // and as a superset of what the regex captured (110 s measured on 200 KB of repeated `cp`).
1685
- const WRITE_VERB = /\b(?:cp|mv|install|rsync|ln|dd|truncate|chmod|chown)\b/;
2103
+ // @implements A-SPEC-747.3 (C) — a verb only as a shell word in plain text (`grep -ln`, `java -cp`, `a.ln` are not);
2104
+ // any expansion, substitution, eval or IFS keeps the `\b…\b` test the 747.1 review requires.
2105
+ const PLAIN = (0, risk_classifier_1.plainShellText)(command);
2106
+ const WRITE_VERB = PLAIN ? (0, risk_classifier_1.verbWordRe)('cp|mv|install|rsync|ln|dd|truncate|chmod|chown') : /\b(?:cp|mv|install|rsync|ln|dd|truncate|chmod|chown)\b/;
2107
+ const COPY_VERB = PLAIN ? (0, risk_classifier_1.verbWordRe)('cp|mv|install|rsync|ln|dd') : /\b(?:cp|mv|install|rsync|ln|dd)\b/;
1686
2108
  // @implements A-SPEC-728 (rule 37) — a segment without the verb is not read, and each pattern is built once per
1687
2109
  // command, not once per segment (131,000 segments of `a\n` spent over half a second here — measured).
1688
2110
  const collectPaths = (seg, head, tail, list, mid) => {
@@ -1703,7 +2125,7 @@ function evaluateHook(input, specsDir, opts) {
1703
2125
  // over-approximation, sealed in A-SPEC-528.1 §3.
1704
2126
  const detBases = [...new Set(segments.map((s) => s.base).filter((b) => b !== null)), opts.projectRoot];
1705
2127
  const hasUnknownBase = segments.some((s) => s.base === null);
1706
- const expandInterp = (raw) => (0, write_target_1.absoluteKindOf)(raw) !== null || isTilde(raw)
2128
+ const expandInterp = (raw) => (0, write_target_2.absoluteKindOf)(raw) !== null || isTilde(raw)
1707
2129
  ? [{ raw, base: opts.projectRoot }]
1708
2130
  : [...detBases.map((b) => ({ raw, base: b })), ...(hasUnknownBase ? [{ raw, base: null }] : [])];
1709
2131
  // @implements A-SPEC-447 — one containment predicate, shared with the code rule below.
@@ -1740,12 +2162,12 @@ function evaluateHook(input, specsDir, opts) {
1740
2162
  if (userCfgList === null)
1741
2163
  return TOO_MANY_CANDIDATES;
1742
2164
  const userCfgKind = userCfgList
1743
- .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)))
2165
+ .map((c) => (c.base === null ? ((0, write_target_2.absoluteKindOf)(c.raw) !== null || /^(?:~|\$\{?(?:HOME|CODEX_HOME)\b)/.test(c.raw) ? (0, write_target_2.userHarnessConfigKindOf)(c.raw, opts.projectRoot) : null) : (0, write_target_2.userHarnessConfigKindOf)(c.raw, c.base)))
1744
2166
  .find((k) => k !== null);
1745
2167
  // One config-write approval (env or a granted queue request for this exact command) lifts both
1746
2168
  // rules below; the refusal files that request, as the Write/Edit config gate does.
1747
2169
  const liftByConfigWrite = (why) => {
1748
- const r = (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind: 'config-write', target: command }, nowTs);
2170
+ const r = resolveForCommand('config-write');
1749
2171
  if (r !== undefined) {
1750
2172
  pendingApprovals.push(r);
1751
2173
  return null;
@@ -1765,14 +2187,30 @@ function evaluateHook(input, specsDir, opts) {
1765
2187
  // ways in one adversarial round. Data heredoc bodies are not commands and are not judged.
1766
2188
  if (!hardHitlCovered && !configWriteLifted) {
1767
2189
  // Every segment, heredoc bodies included (round 2: a `<<` in quotes hid the lines after it).
1768
- const act = (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase);
2190
+ let act = (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase);
2191
+ // @implements A-SPEC-476.3 — a shell write to ax.config.json cannot be read, so it asks only where a cap could rise
2192
+ // (the disk sets one below its widest value); in a run it is refused outright, with no approval to lift it.
2193
+ if (act && act.includes(write_target_1.PROJECT_CAPS_LABEL)) {
2194
+ const onDisk = (0, project_caps_1.readProjectCaps)(opts.projectRoot);
2195
+ if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2196
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${act}: a run cannot change a project cap in ax.config.json, and a shell write to it cannot be read — the caps are the owner's and stay fixed for the run (A-SPEC-476.3)` };
2197
+ }
2198
+ if (!(0, project_caps_1.capsAtWidest)(onDisk)) {
2199
+ const refusal = liftByConfigWrite(`${act}: ax.config.json sets a project cap (semantic.maxTier ${onDisk.semantic}, autonomy.ceiling ${onDisk.ceiling}) and a shell write to it cannot be read — raising or removing a cap is the owner's act (A-SPEC-476.3)`);
2200
+ if (refusal)
2201
+ return refusal;
2202
+ }
2203
+ // @implements A-SPEC-476.7 — the cap act is settled; the rest of the command is judged with the caps file out of the
2204
+ // wiring set (the scan stops at its first act, and an allowed cap write hid an unlink of the hook wiring after it).
2205
+ act = (0, write_target_1.withoutProjectCaps)(() => (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase));
2206
+ }
1769
2207
  if (act) {
1770
2208
  // @implements A-SPEC-728 (round 9) — `.ax` is named for what it is: the spec store and ledger.
1771
2209
  // @implements A-SPEC-728 (rule 38) — an input too large to judge is refused as such (a large loop read "… is the wiring
1772
2210
  // that loads this session's gate").
1773
2211
  const refusal = liftByConfigWrite(/too (?:large|long|complex) to judge|too many calls to judge/.test(act)
1774
2212
  ? `${act}: it is refused rather than judged, because deleting, moving or rewriting the wiring that loads this session's gate turns governance off`
1775
- : act.includes(write_target_1.GOVERNANCE_STORE_LABEL) || /^\.ax\//.test(act)
2213
+ : act.includes(write_target_2.GOVERNANCE_STORE_LABEL) || /^\.ax\//.test(act)
1776
2214
  ? `${act} is this project's governance state — moving, deleting or bulk-replacing it turns No-Spec-No-Code off`
1777
2215
  : `${act} is the wiring that loads this session's gate — deleting, moving or rewriting it turns governance off`);
1778
2216
  if (refusal)
@@ -1792,8 +2230,11 @@ function evaluateHook(input, specsDir, opts) {
1792
2230
  // `> ../elsewhere/a.ts`, which leaves the governed tree entirely.
1793
2231
  // @implements A-SPEC-463 — same quoted-space fix as the config rule; `EXT_TAIL` is the
1794
2232
  // extension part and `pathAlt` supplies the prefix and the quoting alternatives.
1795
- const EXT_TAIL = `\\.${CODE_EXT}`;
1796
- const CODE_TAIL_RE_SED = new RegExp(`${EXT_TAIL}$`);
2233
+ // @implements A-SPEC-774.1 — every path in write position is collected (`ANY_TAIL`: a path ends on a path
2234
+ // character), and `governedCode` below keeps those the Write tool's classifier calls code or test. The private
2235
+ // extension list this replaced let `deploy.sh`, `Makefile`, `Dockerfile`, a CI workflow and `src/a.c` through
2236
+ // while `src/a.ts` was refused (measured 2026-10-17): two judges disagreed about what code is.
2237
+ const EXT_TAIL = '[\\w.+-]';
1797
2238
  const candidates = [];
1798
2239
  const CODE_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(EXT_TAIL)}`, 'g');
1799
2240
  for (const seg of segments) {
@@ -1803,8 +2244,7 @@ function evaluateHook(input, specsDir, opts) {
1803
2244
  // `sed -i` segment was a candidate, so `sed -i '' 's#a.test.ts#src/x.ts#' <outside>/notes.md` was denied as a
1804
2245
  // project code write (measured 2026-10-01).
1805
2246
  for (const raw of sedInPlaceFiles(seg.text))
1806
- if (CODE_TAIL_RE_SED.test(raw))
1807
- candidates.push({ raw, base: seg.base });
2247
+ candidates.push({ raw, base: seg.base });
1808
2248
  }
1809
2249
  // @implements A-SPEC-449 — the copy/move family. The CONFIG rule has carried it since
1810
2250
  // A-SPEC-191 §28 ("a gate that names one syntax for an act is a gate over that syntax, not
@@ -1813,10 +2253,11 @@ function evaluateHook(input, specsDir, opts) {
1813
2253
  // which is an ordinary backup and not this gate's business.
1814
2254
  // (A data heredoc body may still carry separators inside one segment, so the per-segment
1815
2255
  // text is split the way the whole command used to be — the base is the segment's either way.)
1816
- const CODE_TAIL_RE = new RegExp(`\\.${CODE_EXT}$`);
2256
+ // A-SPEC-774.1: any destination is a candidate; the classifier filter decides which are code.
2257
+ const CODE_TAIL_RE = { test: (_p) => true };
1817
2258
  for (const seg of segments) {
1818
2259
  for (const sub of seg.text.split(/[;|&]+/)) {
1819
- if (!/\b(?:cp|mv|install|rsync|ln|dd)\b/.test(sub))
2260
+ if (!COPY_VERB.test(sub))
1820
2261
  continue;
1821
2262
  const of = sub.match(new RegExp(`\\bof=${pathAlt(EXT_TAIL)}`));
1822
2263
  if (of) {
@@ -1874,7 +2315,7 @@ function evaluateHook(input, specsDir, opts) {
1874
2315
  if (/[/\\]$/.test(d))
1875
2316
  return true; // trailing separator = explicit dir
1876
2317
  try {
1877
- const abs = (0, write_target_1.absoluteKindOf)(d) !== null ? d : (seg.base === null ? undefined : (0, write_target_1.pathFlavorFor)(seg.base, d).resolve(seg.base, d));
2318
+ const abs = (0, write_target_2.absoluteKindOf)(d) !== null ? d : (seg.base === null ? undefined : (0, write_target_2.pathFlavorFor)(seg.base, d).resolve(seg.base, d));
1878
2319
  return abs !== undefined && fs.statSync(abs).isDirectory();
1879
2320
  }
1880
2321
  catch {
@@ -1887,17 +2328,79 @@ function evaluateHook(input, specsDir, opts) {
1887
2328
  }
1888
2329
  else if (argv.length >= 2) {
1889
2330
  const dest = argv[argv.length - 1];
1890
- if (CODE_TAIL_RE.test(dest))
1891
- candidates.push({ raw: dest, base: seg.base }); // dest is a code file
1892
- else if (looksLikeDir(dest))
2331
+ // A-SPEC-774.1: a directory first — every destination is now a candidate, so the order decides.
2332
+ if (looksLikeDir(dest))
1893
2333
  pushLanding(dest, argv.slice(0, -1)); // dest is a directory
2334
+ else if (CODE_TAIL_RE.test(dest))
2335
+ candidates.push({ raw: dest, base: seg.base }); // dest is a file
1894
2336
  }
1895
2337
  }
1896
2338
  }
1897
2339
  // @implements A-SPEC-447 — same predicate as the config rule; it lived in two copies, which
1898
2340
  // is how one of two gets fixed.
1899
- const CODE_RE = new RegExp(`\\.${CODE_EXT}$`);
1900
- const codeList = distinct([...candidates, ...interpreterWrites.filter((p) => CODE_RE.test(p)).flatMap(expandInterp)]);
2341
+ // @implements A-SPEC-774.1 — kept when the Write tool's classifier calls the landing file code or test. It is
2342
+ // judged project-relative where the candidate resolves inside the root (a CI folder is a location, not a
2343
+ // name), else as spelled; the filter runs before `distinct`, so the limit counts only governed targets.
2344
+ const judgedPath = (c) => {
2345
+ if (c.base === null && (0, write_target_2.absoluteKindOf)(c.raw) === null && !isTilde(c.raw))
2346
+ return c.raw;
2347
+ const abs = (0, write_target_2.absoluteKindOf)(c.raw) !== null || isTilde(c.raw) || c.base === null
2348
+ ? c.raw : (0, write_target_2.pathFlavorFor)(c.base, c.raw).resolve(c.base, c.raw);
2349
+ const rel = path.relative(opts.projectRoot, abs);
2350
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : abs;
2351
+ };
2352
+ // @implements A-SPEC-775.1 — judged in the mode the Write tool judges in (a run or the owner's strict opt-in).
2353
+ const shellClassify = (0, classification_mode_1.classifyOptionsFor)(opts.projectRoot, (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run);
2354
+ const governedCode = (c) => {
2355
+ const kind = (0, phase_1.classifyAction)(judgedPath(c).replace(/\\/g, '/'), undefined, shellClassify);
2356
+ return kind === 'WRITE_CODE' || kind === 'WRITE_TEST';
2357
+ };
2358
+ // @implements A-SPEC-774.5 §2 — under a role policy EVERY in-project shell write asks the role, as the Write
2359
+ // tool does: a WRITE_TEST-only reviewer wrote config/profile.yaml and requirements.txt through printf
2360
+ // (supervisor probe, 2026-10-17) because only code/test candidates were ever judged.
2361
+ const shellPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2362
+ if (shellPolicy !== null) {
2363
+ const shellIdentity = new identity_1.EnvIdentityProvider().current();
2364
+ for (const c of [...candidates, ...interpreterWrites.flatMap(expandInterp)]) {
2365
+ if (judgeCand(c, [opts.projectRoot]) !== 'in')
2366
+ continue;
2367
+ // @implements A-SPEC-774.10 — a legacy policy outside a run keeps the 0.35.25 freedom for WRITE_OTHER.
2368
+ const issue = (0, role_policy_1.roleCheck)((0, phase_1.classifyAction)(judgedPath(c).replace(/\\/g, '/'), undefined, shellClassify) ?? 'WRITE_OTHER', shellIdentity, shellPolicy, { run: (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run });
2369
+ if (issue)
2370
+ return { permissionDecision: 'deny', permissionDecisionReason: issue };
2371
+ }
2372
+ }
2373
+ // @implements A-SPEC-774.23 — a scoped run's shell writes stay inside its plan, as its file tool writes do.
2374
+ {
2375
+ const inProject = [...candidates, ...interpreterWrites.flatMap(expandInterp)]
2376
+ .filter((c) => judgeCand(c, [opts.projectRoot]) === 'in').map((c) => path.resolve(opts.projectRoot, judgedPath(c)));
2377
+ const outside = (0, run_plan_scope_1.planScopeRefusal)({ projectRoot: opts.projectRoot, specsDir, env: process.env, cwd: input.cwd, sessionId: input.session_id }, inProject);
2378
+ if (outside)
2379
+ return { permissionDecision: 'deny', permissionDecisionReason: outside };
2380
+ }
2381
+ // @implements A-SPEC-747.4 — a write whose destination or command word is computed at run time (xargs input, find's
2382
+ // `{}`, a variable, an IFS join) never reached the literal-destination rule above: 19 such writes to code files
2383
+ // were allowed on 0.35.25 and here (census 2026-10-19). A runner's literal destination joins the candidates; a
2384
+ // computed one is refused unless every literal path in the segment lies outside the project.
2385
+ let computedWrite = null;
2386
+ const commandTokens = segments.flatMap((seg) => (0, dynamic_write_1.pathTokensOf)(seg.text).map((raw) => ({ raw, base: seg.base })));
2387
+ const writeContext = (0, dynamic_write_1.commandContext)(command);
2388
+ for (const seg of segments) {
2389
+ const dw = (0, dynamic_write_1.dynamicWrites)(seg.text, writeContext);
2390
+ for (const raw of dw.statics)
2391
+ candidates.push({ raw, base: seg.base });
2392
+ if (dw.dynamic === null || computedWrite !== null)
2393
+ continue;
2394
+ if (!(commandTokens.length > 0 && commandTokens.every((c) => judgeCand(c, [opts.projectRoot]) === 'out')))
2395
+ computedWrite = dw.dynamic.why;
2396
+ }
2397
+ if (computedWrite === null && writeContext.computed && commandTokens.some((c) => governedCode(c) && judgeCand(c, [opts.projectRoot]) === 'in')) {
2398
+ computedWrite = 'computed command';
2399
+ }
2400
+ if (computedWrite !== null && readSpecsSync(specsDir).length > 0) {
2401
+ return { permissionDecision: 'deny', permissionDecisionReason: `${SHELL_CODE_WRITE_REASON} (its target is computed at run time: ${computedWrite}, A-SPEC-747.4)` };
2402
+ }
2403
+ const codeList = distinct([...candidates, ...interpreterWrites.flatMap(expandInterp)].filter(governedCode));
1901
2404
  // Rule 43: only a governed project judges this list — an ungoverned one was refused for nothing it would check.
1902
2405
  if (codeList === null && readSpecsSync(specsDir).length > 0)
1903
2406
  return TOO_MANY_CANDIDATES;
@@ -1919,22 +2422,24 @@ function evaluateHook(input, specsDir, opts) {
1919
2422
  const governed = readSpecsSync(specsDir).length > 0;
1920
2423
  if (governed) {
1921
2424
  return codeVerdicts.includes('in')
1922
- ? { permissionDecision: 'deny', permissionDecisionReason: '[Holmes-Kit] shell write to a project code file bypasses the No-Spec-No-Code gate — use the Write/Edit tools (gated) or supply out-of-band approval' }
2425
+ ? { permissionDecision: 'deny', permissionDecisionReason: SHELL_CODE_WRITE_REASON }
1923
2426
  : { permissionDecision: 'deny', permissionDecisionReason: UNRESOLVED_BASE_DENY };
1924
2427
  }
1925
2428
  }
1926
2429
  }
1927
- if (pendingApprovals.length > 0) {
2430
+ // @implements A-SPEC-790.8 — a carried approval was spent by the first reading; only the others are spent here.
2431
+ const spendable = pendingApprovals.flatMap((p) => (p.source === 'carried' ? [] : [p]));
2432
+ if (spendable.length > 0) {
1928
2433
  const deny = (why) => ({ permissionDecision: 'deny',
1929
2434
  permissionDecisionReason: `[Holmes-Kit] ${why}` });
1930
2435
  // @implements A-SPEC-477.1 — a later invalid approval must not spend an earlier valid one.
1931
2436
  // Validate the complete set, then check all replays and append under ONE existing ledger hold.
1932
2437
  // This coordinates validation; it does not promise rollback after an I/O failure during append.
1933
- if (pendingApprovals.some(({ approval }) => (0, provenance_chain_1.blankNonce)(approval.nonce))) {
2438
+ if (spendable.some(({ approval }) => (0, provenance_chain_1.blankNonce)(approval.nonce))) {
1934
2439
  return deny('the approval declared single-use (nonce) but the value is empty — single-use cannot be enforced, so it is denied');
1935
2440
  }
1936
2441
  const ledgerFile = (0, ledger_store_2.writerChainFile)(path.join(opts.projectRoot, '.ax', 'ledger'));
1937
- const unique = new Map(pendingApprovals.filter(({ approval }) => !!approval.nonce)
2442
+ const unique = new Map(spendable.filter(({ approval }) => !!approval.nonce)
1938
2443
  .map(({ approval }) => [approval.nonce, approval]));
1939
2444
  const check = () => {
1940
2445
  const conflict = (0, ledger_store_2.ledgerConflictReason)(path.dirname(ledgerFile));
@@ -1965,15 +2470,44 @@ function evaluateHook(input, specsDir, opts) {
1965
2470
  catch (err) {
1966
2471
  return deny(`could not obtain exclusive ledger access to spend the single-use approval (${err instanceof Error ? err.message : String(err)})`);
1967
2472
  }
1968
- for (const { source, approval } of pendingApprovals) {
2473
+ for (const { source, approval } of spendable) {
1969
2474
  if (source === 'grant' && approval.nonce)
1970
2475
  (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, approval.nonce);
1971
2476
  }
2477
+ opts.onApprovalsSpent?.(spendable.map(({ approval }) => approval));
2478
+ }
2479
+ // @implements A-SPEC-774.13 — an allowed interactive launch inherits this session's authority variables; a hook
2480
+ // cannot change a command's environment, so it names them (never their values) and gives the operator's re-run.
2481
+ if (agentCliLaunch(command) && !(0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2482
+ const inherited = ['HOLMES_APPROVAL', 'HOLMES_ROLE', 'HOLMES_GATE_BYPASS', 'HOLMES_AUTONOMOUS_APPROVAL', 'HOLMES_LEDGER_KEY']
2483
+ .filter((n) => typeof process.env[n] === 'string' && process.env[n] !== '');
2484
+ if (inherited.length > 0) {
2485
+ return { permissionDecision: 'allow', permissionDecisionReason: `[Holmes-Kit] the agent this command launches inherits `
2486
+ + `${inherited.join(', ')} from this session. To start it without that authority, the operator runs it from their own `
2487
+ + `terminal: env ${inherited.map((n) => `-u ${n}`).join(' ')} ${command.length > 200 ? `${command.slice(0, 200)}…` : command} (A-SPEC-774.13)` };
2488
+ }
1972
2489
  }
1973
2490
  // auto/notify/confirm, or hard-hitl with a valid approval: this slice blocks only
1974
2491
  // hard-hitl; confirm is advisory here.
1975
2492
  return { permissionDecision: 'allow' };
1976
2493
  }
2494
+ // @implements A-SPEC-776 — a foreign MCP tool that is not a read is judged as a Write of every path it names,
2495
+ // whatever the field is called; a location that is not a file path is refused rather than skipped.
2496
+ const foreign = input.tool_input.foreign_paths ?? (0, write_target_2.foreignMcpPaths)(input.tool_name, input.tool_input);
2497
+ if (foreign && (foreign.paths.length > 0 || foreign.unresolvable.length > 0)) {
2498
+ if (foreign.unresolvable.length > 0) {
2499
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} names ${foreign.unresolvable[0].slice(0, 120)} — a location the gate cannot resolve to a file, so it cannot be judged and is refused (A-SPEC-776)` };
2500
+ }
2501
+ if (foreign.paths.length > 64) {
2502
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} names more than 64 paths — too many to judge, refused rather than judged (A-SPEC-776)` };
2503
+ }
2504
+ for (const fp of foreign.paths) {
2505
+ const v = evaluateHook({ tool_name: 'Write', tool_input: { file_path: fp, content: '' }, ...(input.cwd === undefined ? {} : { cwd: input.cwd }) }, specsDir, opts);
2506
+ if (v.permissionDecision === 'deny') {
2507
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} → ${fp.slice(0, 120)}: ${v.permissionDecisionReason ?? ''}` };
2508
+ }
2509
+ }
2510
+ }
1977
2511
  // @implements A-SPEC-191 §27 (round 13) — `PATH_FIELDS` exists because `notebook_path` slipped
1978
2512
  // past a gate that knew only `file_path`, and this line still knew only `file_path`: a valid
1979
2513
  // NotebookEdit was denied in EVERY project with "cannot read the edit target path", which names
@@ -1997,7 +2531,7 @@ function evaluateHook(input, specsDir, opts) {
1997
2531
  permissionDecisionReason: '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)',
1998
2532
  };
1999
2533
  }
2000
- const writesCode = (0, write_target_1.writesFiles)(input.tool_name, input.tool_input);
2534
+ const writesCode = (0, write_target_2.writesFiles)(input.tool_name, input.tool_input);
2001
2535
  // @implements A-SPEC-144
2002
2536
  // A code-writing tool with NO readable target must not pass in a governed project. Measured
2003
2537
  // end-to-end after normalization landed: dropping a non-string `file_path` stopped the exception
@@ -2080,7 +2614,7 @@ function evaluateHook(input, specsDir, opts) {
2080
2614
  // "is this POSIX-absolute" while meaning "is this absolute". `C:/proj/src/app.ts` answers false,
2081
2615
  // so identity resolution, case folding and containment were all skipped on native Windows — the
2082
2616
  // very filesystem (NTFS) the case-folding comment below names.
2083
- const absKind = (0, write_target_1.absoluteKindOf)(norm);
2617
+ const absKind = (0, write_target_2.absoluteKindOf)(norm);
2084
2618
  if (absKind === 'unc') {
2085
2619
  // A network path has no local filesystem identity to resolve, so containment cannot be decided.
2086
2620
  // A-SPEC-191 §17/§29 both began as "the gate did not refuse to govern — it concluded there was
@@ -2106,7 +2640,7 @@ function evaluateHook(input, specsDir, opts) {
2106
2640
  // A drive letter means NTFS or FAT, both case-folding; that is carried by the syntax, so it is
2107
2641
  // a fact here rather than a guess about the host.
2108
2642
  if (flipped === projectRoot)
2109
- return (0, write_target_1.foldsCaseBySyntax)(absKind) || process.platform === 'darwin' || process.platform === 'win32';
2643
+ return (0, write_target_2.foldsCaseBySyntax)(absKind) || process.platform === 'darwin' || process.platform === 'win32';
2110
2644
  if (flipped === projectRoot)
2111
2645
  return false;
2112
2646
  try {
@@ -2121,7 +2655,7 @@ function evaluateHook(input, specsDir, opts) {
2121
2655
  // project reached over a path this process cannot resolve is the same situation. Only the
2122
2656
  // syntax fact is used here — a drive letter is NTFS or FAT, both case-folding — so POSIX
2123
2657
  // inputs, for which this is always false, keep their previous verdict exactly.
2124
- return (0, write_target_1.foldsCaseBySyntax)(absKind);
2658
+ return (0, write_target_2.foldsCaseBySyntax)(absKind);
2125
2659
  }
2126
2660
  })();
2127
2661
  const fold = (s) => (caseBlind ? s.toLowerCase() : s);
@@ -2135,7 +2669,7 @@ function evaluateHook(input, specsDir, opts) {
2135
2669
  if (canonical === null) {
2136
2670
  // @implements A-SPEC-728 — outside the project is free, EXCEPT the user-level harness config
2137
2671
  // that loads this session's gate (`~/.claude/settings*.json`, Codex `config.toml`/`hooks.json`).
2138
- const userKind = (0, write_target_1.userHarnessConfigKindOf)(norm, projectRoot);
2672
+ const userKind = (0, write_target_2.userHarnessConfigKindOf)(norm, projectRoot);
2139
2673
  if (userKind === null)
2140
2674
  return { permissionDecision: 'allow' };
2141
2675
  const userResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
@@ -2179,7 +2713,7 @@ function evaluateHook(input, specsDir, opts) {
2179
2713
  // that may do everything, or a `default:` granting it without any claim at all. REQ-152 identified
2180
2714
  // this threat and closed only the shell entrance; a plain Write was measured as ALLOWED. Unlike
2181
2715
  // specs, no approval seal covers this file, so the write itself must be the thing that is gated.
2182
- if ((0, write_target_1.protectedKindOf)(opts.projectRoot, norm) === path.join('.ax', 'roles')) {
2716
+ if ((0, write_target_2.protectedKindOf)(opts.projectRoot, norm) === path.join('.ax', 'roles')) {
2183
2717
  // @implements A-SPEC-245 — grant files answer here too; consumed on the allowed write below.
2184
2718
  const rolesResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2185
2719
  if (rolesResolved === undefined) {
@@ -2195,24 +2729,43 @@ function evaluateHook(input, specsDir, opts) {
2195
2729
  }
2196
2730
  // @implements A-SPEC-191 §22 — ask by identity. A spelling regex was defeated by a single in-project link.
2197
2731
  // @implements A-SPEC-728 — a project that itself sits in a harness home still protects those files.
2198
- const configKind = (0, write_target_1.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_1.userHarnessConfigKindOf)(norm, opts.projectRoot);
2732
+ const configKind = (0, write_target_2.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_2.userHarnessConfigKindOf)(norm, opts.projectRoot);
2199
2733
  // @implements A-SPEC-163 — identity, not spelling. Measured: `.ax//ledger//p.jsonl`,
2200
2734
  // `.ax/./ledger/p.jsonl` and `.AX/roles/policy.yaml` all reached the protected file while the
2201
2735
  // regex saw a different string. Adding `//` to the pattern would only move the next variant.
2202
- if (configKind !== null || (0, write_target_1.isProtectedTarget)(opts.projectRoot, norm)) {
2736
+ if (configKind !== null || (0, write_target_2.isProtectedTarget)(opts.projectRoot, norm)) {
2203
2737
  // @implements A-SPEC-133 — a token scoped to config-write authorizes this; a spec-only or
2204
2738
  // out-of-scope token does not, so config forgery cannot ride a narrow grant.
2205
2739
  const cfgResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2206
2740
  if (cfgResolved === undefined) {
2207
2741
  // @implements A-SPEC-193 §8 — name what was blocked. Baking a list into the sentence makes the
2208
2742
  // wording false as harnesses grow (REQ-155: a diagnosis that points at the wrong file has negative value).
2209
- const kindName = configKind ?? (0, write_target_1.protectedKindOf)(opts.projectRoot, norm) ?? 'config';
2743
+ const kindName = configKind ?? (0, write_target_2.protectedKindOf)(opts.projectRoot, norm) ?? 'config';
2210
2744
  return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${kindName} 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`
2211
2745
  + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: norm, why: `writing ${kindName}` }) };
2212
2746
  }
2213
2747
  if (cfgResolved.source === 'grant' && cfgResolved.approval.nonce)
2214
2748
  (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, cfgResolved.approval.nonce);
2215
2749
  }
2750
+ // @implements A-SPEC-476.3 — the owner's caps in ax.config.json narrow this agent: raising or removing one is the owner's
2751
+ // act (owner decision 2026-10-19), lowering stays free, and in a run no write changes one.
2752
+ if ((0, write_target_1.isProjectConfigTarget)(opts.projectRoot, norm)) {
2753
+ const capsAct = projectCapsWriteAct(opts.projectRoot, input);
2754
+ if (capsAct !== null) {
2755
+ if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2756
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a run cannot change a project cap in ax.config.json (${capsAct}) — the caps are the owner's and stay fixed for the run (A-SPEC-476.3)` };
2757
+ }
2758
+ if (capsAct !== 'lowered') {
2759
+ const capsResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2760
+ if (capsResolved === undefined) {
2761
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] this write raises or removes a project cap in ax.config.json (${capsAct}) — a cap narrows this agent, so only the owner lifts it: an out-of-band approval that includes config-write is required (A-SPEC-476.3)`
2762
+ + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: norm, why: `raising a project cap (${capsAct})` }) };
2763
+ }
2764
+ if (capsResolved.source === 'grant' && capsResolved.approval.nonce)
2765
+ (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, capsResolved.approval.nonce);
2766
+ }
2767
+ }
2768
+ }
2216
2769
  // Spec-file edit → graph-aware blast-radius risk (Tier-2 push-feed): a change to a widely-depended-on
2217
2770
  // or foundational (REQ) spec ripples across the graph, so its risk is assessed from the spec
2218
2771
  // dependency graph and escalated to out-of-band approval when the impact reaches the hard-hitl
@@ -2220,9 +2773,23 @@ function evaluateHook(input, specsDir, opts) {
2220
2773
  // @implements A-SPEC-191 §23 (round 12) — identity, like every other protected surface. The
2221
2774
  // resolved path is also what the disk is read with below: `existsSync(p)` on the caller's raw
2222
2775
  // spelling answered "not approved" for `<file>/` and skipped the seal-breaking branch entirely.
2223
- const specTarget = (0, write_target_1.specTargetOf)(opts.projectRoot, specsDir, norm);
2776
+ const specTarget = (0, write_target_2.specTargetOf)(opts.projectRoot, specsDir, norm);
2224
2777
  if (specTarget !== null) {
2225
2778
  const p = specTarget;
2779
+ // @implements A-SPEC-774 §1 — the role is asked first. This branch returned `allow` long before `roleCheck`
2780
+ // was reached, so a reviewer allowed only WRITE_TEST wrote A-SPEC and T-SPEC files (measured 2026-10-17).
2781
+ // A spec-write approval does not lift it: an approval changes what is approved, not who the caller is.
2782
+ const specPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2783
+ if (specPolicy !== null) {
2784
+ // The resolved path, not one made relative: the store's real path and the root's spelling can differ
2785
+ // (`/var` vs `/private/var`), and the authoring folders are matched as segments either way.
2786
+ const specAction = (0, phase_1.classifyAction)(p.replace(/\\/g, '/')) ?? 'AUTHOR_REQ';
2787
+ // @implements A-SPEC-774.14 — amends 774.8: the run carries its run-only default-breadth check here. 774.10's
2788
+ // legacy reading uses the same value.
2789
+ const specRoleIssue = (0, role_policy_1.roleCheck)(specAction, new identity_1.EnvIdentityProvider().current(), specPolicy, { run: (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run });
2790
+ if (specRoleIssue)
2791
+ return { permissionDecision: 'deny', permissionDecisionReason: specRoleIssue };
2792
+ }
2226
2793
  // F1: a spec cannot SELF-APPROVE. `status: approved` is what unlocks every downstream gate
2227
2794
  // (phaseCheck trusts the on-disk status). If the incoming write promotes a spec to approved and it
2228
2795
  // is not ALREADY approved on disk, that is a new approval — an out-of-band act, never a raw tool
@@ -2306,9 +2873,18 @@ function evaluateHook(input, specsDir, opts) {
2306
2873
  }
2307
2874
  // @implements A-SPEC-167 — the body is passed so a shebang can be seen. `Edit` carries only a
2308
2875
  // fragment, so the shebang check simply does not fire there; the path signals still answer.
2309
- const action = (0, phase_1.classifyAction)(relPath, input.tool_input.content);
2310
- if (!action)
2311
- return { permissionDecision: 'allow' };
2876
+ // @implements A-SPEC-775.1 — a run or the owner's strict opt-in narrows test folders and makes unclassified writes
2877
+ // code; interactively without strict the options change nothing but the owner's declared test folders.
2878
+ const writeClassify = (0, classification_mode_1.classifyOptionsFor)(opts.projectRoot, (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run);
2879
+ const action = (0, phase_1.classifyAction)(relPath, input.tool_input.content, writeClassify);
2880
+ if (!action) {
2881
+ // @implements A-SPEC-774 §2 — a write the classifier does not name is still a write. With no role policy it
2882
+ // stays free, as before; with one, the role must list WRITE_OTHER (a reviewer's NotebookEdit was allowed).
2883
+ const otherPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2884
+ // @implements A-SPEC-774.10 — read strictly only in a run or under a vocabulary-2 policy.
2885
+ const otherIssue = otherPolicy === null ? null : (0, role_policy_1.roleCheck)('WRITE_OTHER', new identity_1.EnvIdentityProvider().current(), otherPolicy, { run: (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run });
2886
+ return otherIssue ? { permissionDecision: 'deny', permissionDecisionReason: otherIssue } : { permissionDecision: 'allow' };
2887
+ }
2312
2888
  // Read specs synchronously via a fresh walk (hook must be sync)
2313
2889
  const specs = readSpecsSync(specsDir);
2314
2890
  // @implements A-SPEC-230 — structural constraints move from "checked by the suite" to "enforced at
@@ -2324,7 +2900,7 @@ function evaluateHook(input, specsDir, opts) {
2324
2900
  : typeof input.tool_input.new_string === 'string'
2325
2901
  ? { content: input.tool_input.new_string, mode: 'fragment' }
2326
2902
  : null;
2327
- if (proposed && (0, write_target_1.specTargetOf)(opts.projectRoot, specsDir, p) === null) {
2903
+ if (proposed && (0, write_target_2.specTargetOf)(opts.projectRoot, specsDir, p) === null) {
2328
2904
  const forbidden = [];
2329
2905
  const required = [];
2330
2906
  // @implements A-SPEC-691 — the allowances travel with the rules. They come out of the SAME
@@ -2371,15 +2947,30 @@ function evaluateHook(input, specsDir, opts) {
2371
2947
  // an existing one, because the gate looked at the file's anchors rather than the change's. Only
2372
2948
  // ADDED claims are checked — re-judging the file's existing ones would block the very edits
2373
2949
  // needed to fix a spec that moved back to draft.
2374
- if (typeof input.tool_input.content === 'string') {
2950
+ // @implements A-SPEC-166.1 — judged on what the write LEAVES, for Edit and MultiEdit as for Write: an Edit added a
2951
+ // draft spec's anchor to an anchored test file, was allowed, and locked the file (measured 2026-10-17). A file
2952
+ // that exists but cannot be read is refused — the payload never stands in for the disk (M2).
2953
+ const ti166 = input.tool_input;
2954
+ const writesText = typeof ti166.content === 'string' || typeof ti166.new_string === 'string' || Array.isArray(ti166.edits);
2955
+ if (writesText) {
2375
2956
  let previous;
2376
- try {
2377
- previous = fs.readFileSync(norm, 'utf8');
2957
+ if (fs.existsSync(norm)) {
2958
+ try {
2959
+ previous = fs.readFileSync(norm, 'utf8');
2960
+ }
2961
+ catch {
2962
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] cannot read ${relPath} to judge its anchors — the write is refused rather than judged by its own payload` };
2963
+ }
2378
2964
  }
2379
- catch {
2380
- previous = undefined;
2965
+ const edited = editedResult(previous ?? null, ti166);
2966
+ if (edited === TOO_LARGE) {
2967
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] the result of this write to ${relPath} is too large to judge its anchors` };
2381
2968
  }
2382
- const added = (0, anchors_1.newlyClaimed)(input.tool_input.content, previous);
2969
+ // An edit that does not apply: the incoming fragments are judged (over-inclusion is the safe direction).
2970
+ const leaves = edited ?? [ti166.content, ti166.new_string, ...(Array.isArray(ti166.edits)
2971
+ ? ti166.edits.map((e) => e.new_string) : [])]
2972
+ .filter((s) => typeof s === 'string').join('\n');
2973
+ const added = (0, anchors_1.newlyClaimed)(leaves, previous);
2383
2974
  // An anchor naming a spec that does not exist is worse than one naming a draft — it claims
2384
2975
  // authority from a document nobody can read. Unknown is treated as unapproved, the direction
2385
2976
  // REQ-144 established for everything the gate cannot resolve.
@@ -2518,6 +3109,14 @@ function evaluateHook(input, specsDir, opts) {
2518
3109
  const defaultSpecsAbs = path.resolve(opts.projectRoot, exports.DEFAULT_SPECS_DIR);
2519
3110
  if (specs.length === 0 && specsDirAbs === defaultSpecsAbs && !fs.existsSync(specsDirAbs)
2520
3111
  && !(0, governance_history_1.hasGovernanceHistory)(opts.projectRoot)) {
3112
+ // @implements A-SPEC-774.15 — the role gate does not depend on specs: a project that configured roles and has no
3113
+ // specs yet still asks the role (the shell and MCP paths already did). With no policy this is the old free allow.
3114
+ const ungovernedPolicy = (0, role_policy_1.loadRolePolicy)(projectRoot);
3115
+ if (ungovernedPolicy !== null) {
3116
+ const issue = (0, role_policy_1.roleCheck)(action, new identity_1.EnvIdentityProvider().current(), ungovernedPolicy, { run: (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run });
3117
+ if (issue)
3118
+ return { permissionDecision: 'deny', permissionDecisionReason: issue };
3119
+ }
2521
3120
  return { permissionDecision: 'allow' };
2522
3121
  }
2523
3122
  // Extract @implements A-SPEC-xxx from all available marker sources:
@@ -2622,8 +3221,13 @@ function evaluateHook(input, specsDir, opts) {
2622
3221
  // exists it is fail-closed: no role, an unregistered role, and a role without the action are all
2623
3222
  // refusals. The claim comes from the ENVIRONMENT only; a role in the payload would be the session
2624
3223
  // asserting its own authority, which is what ART-5 forbids on the spec axis.
2625
- const roleIssue = (0, role_policy_1.roleCheck)(action, new identity_1.EnvIdentityProvider().current(), (0, role_policy_1.loadRolePolicy)(projectRoot));
2626
- if (roleIssue && !codeWriteCovered) {
3224
+ // @implements A-SPEC-774.14 — amends 774.8: the run is passed here too (774.10's legacy reading uses it as well).
3225
+ const roleRun = (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run;
3226
+ const roleIssue = (0, role_policy_1.roleCheck)(action, new identity_1.EnvIdentityProvider().current(), (0, role_policy_1.loadRolePolicy)(projectRoot), { run: roleRun });
3227
+ // @implements A-SPEC-774.15 — a code-write approval answers the spec gate, not who the caller is: in a run only a
3228
+ // role-override approval lifts a role refusal. Interactively a code-write approval still lifts it (0.35.25).
3229
+ const roleOverride = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'role-override', target: relPath }, nowTs);
3230
+ if (roleIssue && !roleOverride && (roleRun || !codeWriteCovered)) {
2627
3231
  return { permissionDecision: 'deny', permissionDecisionReason: roleIssue };
2628
3232
  }
2629
3233
  // @implements A-SPEC-134
@@ -2704,7 +3308,7 @@ function evaluateHook(input, specsDir, opts) {
2704
3308
  // dispensation (ART-4 asks for coverage — the gate must not refuse it), or the out-of-band
2705
3309
  // code-write approval. Anchor deletion never blocks but rides the allow as a warning — silent
2706
3310
  // RTM loss is the C12 failure mode, made audible.
2707
- const { judgeScope, fttPathTokens: fttTokens } = require('../guardrail/scope-judgment');
3311
+ const { judgeScope, fttPathTokens: fttTokens, matchesFtt } = require('../guardrail/scope-judgment');
2708
3312
  const { anchorSpecIds, stripStringLiterals } = require('../rtm/anchor-ids');
2709
3313
  const oldStr = input.tool_input.old_string ?? '';
2710
3314
  const newPayload = [input.tool_input.content ?? '', input.tool_input.new_string ?? ''].join('\n');
@@ -2726,8 +3330,43 @@ function evaluateHook(input, specsDir, opts) {
2726
3330
  fttTokensOf: (id) => fttTokens(specs.find((s) => s.id === id)?.sections['Files to Touch'] ?? ''),
2727
3331
  removedAnchorIds: beforeIds.filter((id) => !afterIds.has(id)),
2728
3332
  });
2729
- const scopeWarnings = scopeVerdict.warnings.map((w) => `[Holmes-Kit] ${w}`).join('\n');
3333
+ let scopeWarnings = scopeVerdict.warnings.map((w) => `[Holmes-Kit] ${w}`).join('\n');
3334
+ // @implements A-SPEC-166.2 — anchor self-selection after a scope refusal: the gate refused admitting this file to X,
3335
+ // and this write adds an anchor SITE naming another spec instead (the 774.14 case: a new `@implements` line for a
3336
+ // spec the disk already carried is tenure, so nothing else asks). Refused in a run or under strict; warned otherwise.
3337
+ if (scopeVerdict.decision !== 'admission-required' && !codeWriteCovered) {
3338
+ const refused = (0, scope_refusal_memory_1.recentScopeRefusals)(projectRoot, relPath.replace(/\\/g, '/'))
3339
+ .filter((x) => !fttTokens(specs.find((s) => s.id === x)?.sections['Files to Touch'] ?? '').some((t) => matchesFtt(t, relPath)));
3340
+ if (refused.length > 0) {
3341
+ const { anchorSpecSites } = require('../rtm/anchor-ids');
3342
+ const disk = onDiskContent;
3343
+ const leftRaw = editedResult(disk === '' && !fs.existsSync(p) ? null : disk, input.tool_input);
3344
+ const left = typeof leftRaw === 'string' ? leftRaw : newPayload;
3345
+ const beforeSites = anchorSpecSites(disk);
3346
+ const afterSites = anchorSpecSites(left);
3347
+ const beforeCount = new Map();
3348
+ for (const s of beforeSites)
3349
+ beforeCount.set(s.spec, (beforeCount.get(s.spec) ?? 0) + 1);
3350
+ const added = new Set();
3351
+ for (const s of afterSites) {
3352
+ const n = beforeCount.get(s.spec) ?? 0;
3353
+ if (n > 0)
3354
+ beforeCount.set(s.spec, n - 1);
3355
+ else
3356
+ added.add(s.spec);
3357
+ }
3358
+ const others = [...added].filter((y) => !refused.includes(y));
3359
+ if (afterSites.length > beforeSites.length && others.length > 0) {
3360
+ const why = `[Holmes-Kit] the gate refused admitting ${relPath} to ${refused.join(', ')} within the last 2 hours; adding an anchor to ${others.join(', ')} instead is anchor self-selection — widen ${refused.join(', ')}'s Files to Touch (a spec amendment), or supply a covering approval`;
3361
+ if (writeClassify.strict)
3362
+ return { permissionDecision: 'deny', permissionDecisionReason: why };
3363
+ scopeWarnings = [scopeWarnings, why].filter(Boolean).join('\n');
3364
+ }
3365
+ }
3366
+ }
2730
3367
  if (scopeVerdict.decision === 'admission-required' && !codeWriteCovered) { // @implements A-SPEC-133 — same code-write coverage as the stale gate
3368
+ // @implements A-SPEC-166.2 — remembered, so a following re-anchor to another spec is seen.
3369
+ (0, scope_refusal_memory_1.recordScopeRefusals)(projectRoot, relPath.replace(/\\/g, '/'), scopeVerdict.failedAdmissions.map((f) => f.id));
2731
3370
  const failed = scopeVerdict.failedAdmissions
2732
3371
  .map((f) => `${relPath} is anchored to ${f.id} but falls outside its 'Files to Touch' scope (${f.reason})`).join('; ');
2733
3372
  return {
@@ -2892,12 +3531,32 @@ if (require.main === module) {
2892
3531
  const wired = wiredSpecsDir(process.argv, process.env);
2893
3532
  return path.isAbsolute(wired) ? wired : path.join(hookProjectRoot, wired);
2894
3533
  })();
2895
- const out = evaluateHook(input, specsDirWired, {
3534
+ const judged = evaluateHook(input, specsDirWired, {
2896
3535
  projectRoot: hookProjectRoot,
2897
3536
  approval: readApprovalFromEnv(),
2898
3537
  // Round 17: rm targets resolve from the directory the shell runs in (inside the project).
2899
- resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_1.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3538
+ resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3539
+ resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
2900
3540
  });
3541
+ // @implements A-SPEC-102.5 — a scoped run writes only inside its plan, whatever the text it read asks.
3542
+ const planned = hookRoot.anchored
3543
+ ? (0, run_plan_scope_1.applyPlanScope)(judged, { projectRoot: hookProjectRoot, specsDir: specsDirWired, env: process.env, cwd: input.cwd, sessionId: input.session_id,
3544
+ tool: input.tool_name, toolInput: input.tool_input })
3545
+ : judged;
3546
+ // @implements A-SPEC-781.1 — the run's stage decides which kinds of write it may make.
3547
+ const staged = hookRoot.anchored
3548
+ ? (0, run_stages_1.applyStageGate)(planned, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id,
3549
+ tool: input.tool_name, toolInput: input.tool_input })
3550
+ : planned;
3551
+ // @implements A-SPEC-774.19 — and the role acts only in the stages it declares.
3552
+ const roled = hookRoot.anchored
3553
+ ? (0, run_stages_1.applyRoleStage)(staged, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id,
3554
+ tool: input.tool_name, toolInput: input.tool_input })
3555
+ : staged;
3556
+ // @implements A-SPEC-778 — in a run, refusals are logged and a repeated code stops the run; elsewhere unchanged.
3557
+ const out = (hookRoot.anchored
3558
+ ? (0, run_refusals_1.applyRunRefusalStop)(roled, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id, tool: input.tool_name })
3559
+ : judged);
2901
3560
  io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor(input.tool_name, out) }));
2902
3561
  // N3 provenance: record the audit-critical decision classes on the tamper-evident chain —
2903
3562
  // every DENY, and every ALLOW that was unlocked by an out-of-band approval. Fail-open: a
@@ -2927,7 +3586,8 @@ if (require.main === module) {
2927
3586
  projectRoot: hookProjectRoot,
2928
3587
  approval: undefined,
2929
3588
  // A-SPEC-734 (round 17): the same base, project and spec directory as the decision it re-asks.
2930
- resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_1.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3589
+ resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3590
+ resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
2931
3591
  })
2932
3592
  : undefined;
2933
3593
  const unlocked = withoutApproval?.permissionDecision === 'deny';