@holmes-lab/holmes-kit 0.35.24 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +363 -0
  2. package/README.md +4 -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 +34 -4
  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 +31 -1
  13. package/dist/holmes/cli/doctor.js +204 -7
  14. package/dist/holmes/cli/index.js +115 -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-approval.js +3 -2
  27. package/dist/holmes/cli/runtime-binding.d.ts +30 -0
  28. package/dist/holmes/cli/runtime-binding.js +116 -11
  29. package/dist/holmes/cli/scratch.d.ts +12 -0
  30. package/dist/holmes/cli/scratch.js +20 -0
  31. package/dist/holmes/cli/test-platform.d.ts +16 -0
  32. package/dist/holmes/cli/test-platform.js +31 -1
  33. package/dist/holmes/config/config.d.ts +49 -0
  34. package/dist/holmes/config/config.js +146 -3
  35. package/dist/holmes/config/project-caps.d.ts +21 -0
  36. package/dist/holmes/config/project-caps.js +114 -0
  37. package/dist/holmes/governance/approval-queue.d.ts +17 -3
  38. package/dist/holmes/governance/approval-queue.js +51 -8
  39. package/dist/holmes/governance/autonomy.d.ts +6 -0
  40. package/dist/holmes/governance/autonomy.js +21 -0
  41. package/dist/holmes/governance/push-gate-runner.d.ts +8 -0
  42. package/dist/holmes/governance/push-gate-runner.js +49 -1
  43. package/dist/holmes/governance/replica-id.d.ts +9 -0
  44. package/dist/holmes/governance/replica-id.js +44 -7
  45. package/dist/holmes/governance/role-policy.d.ts +41 -1
  46. package/dist/holmes/governance/role-policy.js +137 -20
  47. package/dist/holmes/governance/run-mode.d.ts +14 -0
  48. package/dist/holmes/governance/run-mode.js +120 -0
  49. package/dist/holmes/governance/tool-actions.d.ts +30 -0
  50. package/dist/holmes/governance/tool-actions.js +121 -0
  51. package/dist/holmes/guardrail/agent-launch-policy.d.ts +15 -0
  52. package/dist/holmes/guardrail/agent-launch-policy.js +177 -0
  53. package/dist/holmes/guardrail/classification-mode.d.ts +17 -0
  54. package/dist/holmes/guardrail/classification-mode.js +135 -0
  55. package/dist/holmes/guardrail/dynamic-write.d.ts +43 -0
  56. package/dist/holmes/guardrail/dynamic-write.js +304 -0
  57. package/dist/holmes/guardrail/impact-gate.d.ts +2 -0
  58. package/dist/holmes/guardrail/impact-gate.js +34 -11
  59. package/dist/holmes/guardrail/phase.d.ts +2 -1
  60. package/dist/holmes/guardrail/phase.js +22 -8
  61. package/dist/holmes/guardrail/powershell-shell.d.ts +21 -0
  62. package/dist/holmes/guardrail/powershell-shell.js +801 -0
  63. package/dist/holmes/guardrail/refusal-codes.d.ts +24 -0
  64. package/dist/holmes/guardrail/refusal-codes.js +140 -0
  65. package/dist/holmes/guardrail/risk-classifier.d.ts +17 -0
  66. package/dist/holmes/guardrail/risk-classifier.js +255 -27
  67. package/dist/holmes/guardrail/risk-types.d.ts +16 -0
  68. package/dist/holmes/guardrail/run-plan-scope.d.ts +23 -0
  69. package/dist/holmes/guardrail/run-plan-scope.js +155 -0
  70. package/dist/holmes/guardrail/run-refusals.d.ts +116 -0
  71. package/dist/holmes/guardrail/run-refusals.js +348 -0
  72. package/dist/holmes/guardrail/run-stages.d.ts +67 -0
  73. package/dist/holmes/guardrail/run-stages.js +188 -0
  74. package/dist/holmes/guardrail/scope-judgment.d.ts +5 -1
  75. package/dist/holmes/guardrail/scope-judgment.js +8 -10
  76. package/dist/holmes/guardrail/scope-refusal-memory.d.ts +3 -0
  77. package/dist/holmes/guardrail/scope-refusal-memory.js +85 -0
  78. package/dist/holmes/guardrail/shell-words.js +7 -7
  79. package/dist/holmes/guardrail/write-target.d.ts +31 -2
  80. package/dist/holmes/guardrail/write-target.js +118 -16
  81. package/dist/holmes/hooks/pre-tool-use.d.ts +36 -2
  82. package/dist/holmes/hooks/pre-tool-use.js +740 -81
  83. package/dist/holmes/hooks/session-start.js +5 -3
  84. package/dist/holmes/hooks/stop.d.ts +35 -1
  85. package/dist/holmes/hooks/stop.js +142 -7
  86. package/dist/holmes/mcp/elicit-approval.js +4 -4
  87. package/dist/holmes/mcp/handlers/graph-operations.js +5 -5
  88. package/dist/holmes/mcp/handlers/maintenance-analysis.js +2 -2
  89. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -1
  90. package/dist/holmes/mcp/handlers/operator-inspection.js +3 -1
  91. package/dist/holmes/mcp/handlers/phase-queries.js +16 -1
  92. package/dist/holmes/mcp/handlers/requirement-triage.js +2 -2
  93. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -3
  94. package/dist/holmes/mcp/handlers/spec-approval.js +56 -9
  95. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +1 -0
  96. package/dist/holmes/mcp/handlers/spec-lifecycle.js +3 -3
  97. package/dist/holmes/mcp/handlers/spec-queries.d.ts +7 -0
  98. package/dist/holmes/mcp/handlers/spec-queries.js +5 -0
  99. package/dist/holmes/mcp/handlers/workspace-queries.js +2 -2
  100. package/dist/holmes/mcp/handlers.d.ts +2 -3
  101. package/dist/holmes/mcp/handlers.js +22 -2
  102. package/dist/holmes/mcp/harness-attestation.d.ts +2 -0
  103. package/dist/holmes/mcp/harness-attestation.js +3 -1
  104. package/dist/holmes/mcp/operator-recovery.d.ts +2 -0
  105. package/dist/holmes/mcp/operator-recovery.js +4 -3
  106. package/dist/holmes/mcp/server.js +9 -0
  107. package/dist/holmes/mcp/tool-schemas.js +6 -3
  108. package/dist/holmes/project/npx-bin.d.ts +26 -0
  109. package/dist/holmes/project/npx-bin.js +272 -2
  110. package/dist/holmes/project/root.js +6 -1
  111. package/dist/holmes/project/run-records.d.ts +17 -0
  112. package/dist/holmes/project/run-records.js +126 -0
  113. package/dist/holmes/project/scratch-root.d.ts +12 -0
  114. package/dist/holmes/project/scratch-root.js +132 -0
  115. package/dist/holmes/review/mrp.d.ts +35 -0
  116. package/dist/holmes/review/mrp.js +119 -0
  117. package/dist/holmes/review/verdicts.d.ts +117 -0
  118. package/dist/holmes/review/verdicts.js +345 -0
  119. package/dist/holmes/runtime/dispatch.js +6 -3
  120. package/dist/holmes/semantic/cloud-usage.d.ts +20 -0
  121. package/dist/holmes/semantic/cloud-usage.js +106 -0
  122. package/dist/holmes/semantic/embedder.d.ts +15 -6
  123. package/dist/holmes/semantic/embedder.js +84 -3
  124. package/dist/holmes/semantic/local-model.d.ts +21 -2
  125. package/dist/holmes/semantic/local-model.js +14 -3
  126. package/dist/holmes/semantic/tier.d.ts +25 -0
  127. package/dist/holmes/semantic/tier.js +86 -1
  128. package/dist/holmes/semantic/vector-cache.d.ts +1 -0
  129. package/dist/holmes/semantic/vector-cache.js +4 -1
  130. package/dist/holmes/spec/approval-blockers.d.ts +11 -1
  131. package/dist/holmes/spec/approval-blockers.js +70 -2
  132. package/dist/holmes/spec/renumber.d.ts +1 -1
  133. package/dist/holmes/spec/renumber.js +5 -2
  134. package/dist/holmes/spec/transition-policy.d.ts +5 -7
  135. package/dist/holmes/spec/transition-policy.js +17 -2
  136. 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-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
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.
@@ -57,6 +63,7 @@ const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
57
63
  // @implements A-SPEC-194, A-SPEC-195
58
64
  const registry_1 = require("../messages/registry");
59
65
  const root_1 = require("../project/root");
66
+ const scratch_root_1 = require("../project/scratch-root");
60
67
  const fs = __importStar(require("node:fs"));
61
68
  const path = __importStar(require("node:path"));
62
69
  const os = __importStar(require("node:os"));
@@ -69,12 +76,24 @@ const constitution_debt_1 = require("../governance/constitution-debt");
69
76
  const tspec_state_1 = require("../guardrail/tspec-state");
70
77
  const identity_1 = require("../governance/identity");
71
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");
72
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");
73
88
  const proposed_content_1 = require("../cpg/proposed-content");
74
89
  const forbidden_edges_1 = require("../cpg/forbidden-edges");
75
90
  const required_calls_1 = require("../cpg/required-calls");
76
91
  const language_parser_1 = require("../cpg/language-parser");
77
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");
78
97
  const shell_syntax_1 = require("../guardrail/shell-syntax");
79
98
  const anchors_1 = require("../guardrail/anchors");
80
99
  const governance_history_1 = require("../guardrail/governance-history");
@@ -119,9 +138,118 @@ function unanswered(targets) {
119
138
  }
120
139
  return Object.keys(out).length ? out : undefined;
121
140
  }
122
- function resolveRmSignals(command, cwd, projectRoot, specsDir) {
141
+ /**
142
+ * @implements A-SPEC-773 — the git signals, plus `scratch: true` for each literal absolute target whose real path lies
143
+ * strictly under the trusted Holmes scratch root (owner decision 2026-10-17). Added whether or not the cwd is in a
144
+ * repository; the trust check runs once per call. `scratchTmpdir` is the temporary directory to read the root under
145
+ * (tests; the hook passes nothing and reads os.tmpdir()).
146
+ */
147
+ /** `rm`, option words, an optional `--`, then absolute targets — no separator, redirection, expansion or escape. */
148
+ const SCRATCH_TARGETS_MAX = 64;
149
+ const PLAIN_RM = /^rm(?:[ \t]+-[A-Za-z]+)*(?:[ \t]+--)?(?:[ \t]+\/[A-Za-z0-9._/-]+)+$/;
150
+ function resolveRmSignals(command, cwd, projectRoot, specsDir, scratchTmpdir) {
151
+ const signals = gitRmSignals(command, cwd, projectRoot, specsDir);
152
+ // @implements A-SPEC-773.1 — only a command that IS one plain rm. Round 1 (2026-10-17): `xargs`/`parallel` add
153
+ // targets at run time, an alias does, and a link or move earlier in the same command changes the real path after it
154
+ // was judged — 15 harmful commands were allowed with the root and refused without it.
155
+ if (!PLAIN_RM.test(command.trim()))
156
+ return signals;
157
+ const absolute = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_2.joinShellText)(command))])]
158
+ .filter((raw) => { const t = raw.replace(/^["']/, '').replace(/["']$/, ''); return path.isAbsolute(t) && !/[^A-Za-z0-9._/-]/.test(t) && !t.split('/').includes('..'); });
159
+ // @implements A-SPEC-773.2 — bounded like the git signals (round 8 of A-SPEC-728): at most 64 targets, each at most
160
+ // 4,096 characters and 256 components; past that, no target gets the signal and today's verdict stands.
161
+ if (absolute.length === 0 || absolute.length > SCRATCH_TARGETS_MAX)
162
+ return signals;
163
+ if (absolute.some((t) => t.length > 4096 || t.split('/').length > 256))
164
+ return signals;
165
+ const root = (0, scratch_root_1.trustedScratchRoot)(scratchTmpdir);
166
+ if (root === null)
167
+ return signals;
168
+ const out = { ...(signals ?? {}) };
169
+ let added = false;
170
+ for (const raw of absolute) {
171
+ if (!(0, scratch_root_1.isUnderScratchRoot)(raw.replace(/^["']/, '').replace(/["']$/, ''), root))
172
+ continue;
173
+ out[raw] = { ...(out[raw] ?? {}), scratch: true };
174
+ added = true;
175
+ }
176
+ return added ? out : signals;
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
+ }
250
+ function gitRmSignals(command, cwd, projectRoot, specsDir) {
123
251
  // A-SPEC-728 (round 24): the text as the shell joins it (`r\m -rf .git`, `eval rm\ -rf\ src`).
124
- 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))])];
125
253
  if (targets.length === 0)
126
254
  return undefined;
127
255
  let repoRoot;
@@ -237,7 +365,7 @@ function resolveRmSignals(command, cwd, projectRoot, specsDir) {
237
365
  // in (`commandBases`, flow-insensitive: loops, functions and traps run text later — measured), tracked in the project
238
366
  // when that set is unknown. Round 18's per-segment bases missed those and forced "tracked" on every segment the model
239
367
  // could not place (9 of 15 ordinary cleanups denied — measured).
240
- const cb = (0, write_target_1.commandBases)(command, baseReal);
368
+ const cb = (0, write_target_2.commandBases)(command, baseReal);
241
369
  // @implements A-SPEC-734 (round 20) — straight-line text runs where it is written: each segment naming the target keeps
242
370
  // its own base (a segment the model cannot place: its candidates and the start), so a `cd ..` written after the removal
243
371
  // does not move it (`rm -rf build; cd ..` was refused as out-of-project — measured). A command that can run text later
@@ -252,7 +380,7 @@ function resolveRmSignals(command, cwd, projectRoot, specsDir) {
252
380
  // unknown, the flow-insensitive set.
253
381
  const segmentBases = new Map();
254
382
  if (cb.ordered && cb.unknown === null) {
255
- const segs = (0, write_target_1.shellSegments)(command, baseReal);
383
+ const segs = (0, write_target_2.shellSegments)(command, baseReal);
256
384
  let reach = segs.length > 2000 ? null : [baseReal];
257
385
  // Round 23: inside an `&&` chain a cd that fails stops the chain, so its successors see only where it leads; where the
258
386
  // chain breaks (`;`, `||`, a newline) every state the chain passed through is possible again.
@@ -275,7 +403,7 @@ function resolveRmSignals(command, cwd, projectRoot, specsDir) {
275
403
  else {
276
404
  const next = new Set(andNext ? [] : from);
277
405
  for (const b of from) {
278
- const r = (0, write_target_1.commandBases)(seg.text, b);
406
+ const r = (0, write_target_2.commandBases)(seg.text, b);
279
407
  if (r.unknown !== null) {
280
408
  reach = null;
281
409
  break;
@@ -540,7 +668,8 @@ function startsHolmesServer(command) {
540
668
  function hookOutputFor(_toolName, out) {
541
669
  const { permissionDecision, permissionDecisionReason, ...rest } = out;
542
670
  if (permissionDecision === 'deny') {
543
- 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) };
544
673
  }
545
674
  const context = [typeof rest.additionalContext === 'string' ? rest.additionalContext : '', permissionDecisionReason ?? ''].filter((t) => t !== '').join('\n');
546
675
  const { additionalContext: _c, ...others } = rest;
@@ -744,6 +873,249 @@ function headBeforeLast(text, sep, target, head) {
744
873
  }
745
874
  return false;
746
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
+ }
747
1119
  function dumpsEnvInCommandPosition(command, depth = 0) {
748
1120
  if (depth > 3)
749
1121
  return false;
@@ -983,6 +1355,10 @@ function normalizeHookInput(raw) {
983
1355
  const malformed = !tiIsObject
984
1356
  || ['file_path', 'notebook_path'].some((f) => f in ti && typeof ti[f] !== 'string');
985
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;
986
1362
  // Assigned individually so an undefined never becomes a present-but-undefined key downstream.
987
1363
  // @implements A-SPEC-232 — surrounding whitespace is trimmed HERE, at the input boundary, not
988
1364
  // in each gate. Measured 2026-08-22: `src/app.ts ` walked past No-Spec-No-Code entirely, because
@@ -1001,7 +1377,13 @@ function normalizeHookInput(raw) {
1001
1377
  const ns = str(ti.new_string ?? ti.ReplacementContent);
1002
1378
  if (ns !== undefined)
1003
1379
  out.new_string = ns;
1004
- 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;
1005
1387
  if (cmd !== undefined)
1006
1388
  out.command = cmd;
1007
1389
  const wd = str(ti.workdir);
@@ -1033,13 +1415,13 @@ function normalizeHookInput(raw) {
1033
1415
  // The shell tool: its command when it runs `apply_patch`, and any nested whole patch. Any other write tool: only a
1034
1416
  // whole patch — prose that quotes patch lines is not a write. A path field does not hide the patch beside it.
1035
1417
  // A patch that cannot be read one way (no target, an empty path, too many, an indented header) is unreadable.
1036
- const toolName = (str(r.tool_name) ?? '').toLowerCase();
1418
+ const toolName = psShell !== undefined ? 'bash' : (str(r.tool_name) ?? '').toLowerCase();
1037
1419
  let patchUnreadable = false;
1038
1420
  let noopPaths = null; // @implements A-SPEC-769.7
1039
1421
  // @implements A-SPEC-163.7 — why: a shell command refused for a patch marker is told so (it has no file path to miss).
1040
1422
  let shellMarked = false;
1041
1423
  let otherUnreadable = false;
1042
- if (!write_target_1.READ_ONLY_TOOLS.includes(toolName)) {
1424
+ if (!write_target_2.READ_ONLY_TOOLS.includes(toolName)) {
1043
1425
  const strings = [];
1044
1426
  const collect = (v, depth) => {
1045
1427
  if (typeof v === 'string') {
@@ -1067,7 +1449,7 @@ function normalizeHookInput(raw) {
1067
1449
  // @implements A-SPEC-163.4 — which strings are patches is 163.2's rule; whether one is JUDGED is one positive
1068
1450
  // grammar. The shell tool's command is a patch only as one quoted-heredoc `apply_patch` (rule 3); every string
1069
1451
  // read as a patch must be canonical (rules 1-2). Anything else is unreadable, not unread.
1070
- const patches = strings.filter((text) => !(isShell && text === cmd) && (isPatchTool ? (0, write_target_1.hasPatchEnvelope)(text) : (0, write_target_1.isWholePatch)(text)));
1452
+ const patches = strings.filter((text) => !(isShell && text === cmd) && (isPatchTool ? (0, write_target_2.hasPatchEnvelope)(text) : (0, write_target_2.isWholePatch)(text)));
1071
1453
  if (isShell && cmd !== undefined) {
1072
1454
  const shellPatch = shellPatchOf(cmd);
1073
1455
  if (shellPatch === 'unreadable') {
@@ -1078,14 +1460,15 @@ function normalizeHookInput(raw) {
1078
1460
  patches.push(shellPatch.text);
1079
1461
  }
1080
1462
  if (patches.length > 0) {
1081
- const targets = patches.flatMap((text) => (0, write_target_1.patchTargetsOf)(text));
1082
- if (targets.length === 0 || targets.length > write_target_1.PATCH_TARGETS_MAX || patches.some((text) => !(0, write_target_1.canonicalPatch)(text))) {
1463
+ const targets = patches.flatMap((text) => (0, write_target_2.patchTargetsOf)(text));
1464
+ if (targets.length === 0 || targets.length > write_target_2.PATCH_TARGETS_MAX || patches.some((text) => !(0, write_target_2.canonicalPatch)(text))) {
1083
1465
  patchUnreadable = true;
1084
1466
  otherUnreadable = true;
1085
1467
  // @implements A-SPEC-769.7 — when the targets are readable and the only fault is a context-only update block,
1086
1468
  // the refusal names that condition and those paths instead of a missing path.
1087
- if (targets.length > 0 && targets.length <= write_target_1.PATCH_TARGETS_MAX) {
1088
- const reasons = patches.map(write_target_1.canonicalPatchReason);
1469
+ if (targets.length > 0 && targets.length <= write_target_2.PATCH_TARGETS_MAX) {
1470
+ // A-SPEC-163.8: the text alone — a bare `map(canonicalPatchReason)` would hand the array index to its options.
1471
+ const reasons = patches.map((text) => (0, write_target_2.canonicalPatchReason)(text));
1089
1472
  if (reasons.every((why) => why === null || why === 'no-op') && reasons.includes('no-op')) {
1090
1473
  noopPaths = targets.filter((t) => t.kind === 'update' && !/^[+-]/m.test(t.hunk ?? '')).map((t) => t.path);
1091
1474
  }
@@ -1095,7 +1478,9 @@ function normalizeHookInput(raw) {
1095
1478
  out.patch_targets = targets;
1096
1479
  }
1097
1480
  }
1098
- return { tool_name: str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(malformed ? { malformed: true } : {}),
1481
+ const sessionId = str(r.session_id);
1482
+ return { tool_name: psShell !== undefined ? 'Bash' : str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(sessionId ? { session_id: sessionId } : {}), ...(malformed ? { malformed: true } : {}),
1483
+ ...(ps !== null && 'unjudgeable' in ps ? { powershellUnjudgeable: ps.unjudgeable } : {}),
1099
1484
  ...(patchUnreadable ? { patchUnreadable: true } : {}), ...(shellMarked && !otherUnreadable ? { patchUnreadableCause: 'shell-marker' } : {}),
1100
1485
  ...(noopPaths !== null && !shellMarked ? { patchUnreadableCause: 'no-op', patchNoopPaths: noopPaths } : {}) };
1101
1486
  }
@@ -1248,6 +1633,11 @@ function evaluateHook(input, specsDir, opts) {
1248
1633
  // disk); a move's source is judged as a delete; a relative target is `<base>/<path>` as written, not folded first;
1249
1634
  // a patch that cannot be read or applied is denied. When no target is denied, a payload with a path field or a
1250
1635
  // shell command is then judged as before.
1636
+ // @implements A-SPEC-790 — a PowerShell command whose text cannot be read is refused rather than judged.
1637
+ const psUnjudgeable = input.powershellUnjudgeable;
1638
+ if (psUnjudgeable !== undefined) {
1639
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a PowerShell command that cannot be judged (${psUnjudgeable}) is refused (REQ-790)` };
1640
+ }
1251
1641
  if (input.patchUnreadable) {
1252
1642
  const cause = input;
1253
1643
  // @implements A-SPEC-769.7 — four conditions, four sentences: shell marker, no-op update, and (below) the
@@ -1270,7 +1660,7 @@ function evaluateHook(input, specsDir, opts) {
1270
1660
  const stat = fs.statSync(source);
1271
1661
  if (!stat.isFile() || stat.size > PATCH_UPDATE_BYTES_MAX)
1272
1662
  return null;
1273
- return (0, write_target_1.applyPatchUpdateDetailed)(fs.readFileSync(source, 'utf8'), hunk);
1663
+ return (0, write_target_2.applyPatchUpdateDetailed)(fs.readFileSync(source, 'utf8'), hunk);
1274
1664
  }
1275
1665
  catch {
1276
1666
  return null;
@@ -1327,10 +1717,10 @@ function evaluateHook(input, specsDir, opts) {
1327
1717
  const command = input.tool_input.command;
1328
1718
  // @implements A-SPEC-728 (round 17) — the shell runs where the harness says (a Codex `workdir`, the
1329
1719
  // payload `cwd`), inside the project; relative words are judged from there, not from the root.
1330
- const shellBase = (0, write_target_1.shellBaseFor)(opts.projectRoot, input.tool_input.workdir, input.cwd);
1720
+ const shellBase = (0, write_target_2.shellBaseFor)(opts.projectRoot, input.tool_input.workdir, input.cwd);
1331
1721
  // @implements A-SPEC-728 (rule 42) — split once, before any other judgement, and refused past 4,096 segments: seventeen
1332
1722
  // shapes of repeated separators took 2.4–6.1 s at 256 KB, their cost spread over every segment of every rule (measured).
1333
- const segmentsOnce = (0, write_target_1.shellSegments)(command, shellBase);
1723
+ const segmentsOnce = (0, write_target_2.shellSegments)(command, shellBase);
1334
1724
  if (segmentsOnce.length > SHELL_SEGMENTS_MAX) {
1335
1725
  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)` };
1336
1726
  }
@@ -1344,12 +1734,21 @@ function evaluateHook(input, specsDir, opts) {
1344
1734
  catch {
1345
1735
  rmTargetSignals = undefined;
1346
1736
  }
1737
+ // @implements A-SPEC-226.3 — unlike the rm signals, a resolver that throws is not "no signal": it did not answer.
1738
+ let stagedStore;
1739
+ try {
1740
+ stagedStore = opts.resolveStagedStore?.(command);
1741
+ }
1742
+ catch {
1743
+ stagedStore = { specsDir, unanswered: true };
1744
+ }
1347
1745
  // projectRoot scopes the protected-`.ax` rules to THIS repository's governance directory; without
1348
1746
  // it the substring match gated `.ax` paths in any other project on the machine.
1349
1747
  const action = {
1350
1748
  kind: 'shell', target: command, command, rmTargetSignals,
1351
1749
  projectRoot: (0, linear_match_1.trimTrailing)(opts.projectRoot.replace(/\\/g, '/'), '/'),
1352
1750
  cwd: shellBase,
1751
+ ...(stagedStore ? { stagedStore } : {}),
1353
1752
  };
1354
1753
  const assess = opts?.assess ?? risk_classifier_1.assessRisk;
1355
1754
  const approval = opts.approval;
@@ -1434,7 +1833,20 @@ function evaluateHook(input, specsDir, opts) {
1434
1833
  // Which of the two harms this is. Setting a role or a bypass is not reading a secret, it is
1435
1834
  // self-granting authority — reporting both as "reads the environment" sends an operator to
1436
1835
  // hunt a leak that never happened.
1437
- const GRANTS_SELF = /\bHOLMES_(?:ROLE|GATE_BYPASS|AUTONOMOUS_APPROVAL|SEMANTIC_API_KEY)\b/.test(command);
1836
+ // @implements A-SPEC-774.2 §5 — read over the de-quoted text, so `HOLMES_\ROLE=` is reported as what it is.
1837
+ const GRANTS_SELF = /\bHOLMES_(?:ROLE|GATE_BYPASS|AUTONOMOUS_APPROVAL|SEMANTIC_API_KEY)\b/.test(command.replace(/[\\'"]/g, ''));
1838
+ // @implements A-SPEC-774.9 — a launch is refused in a run (judged by the session, fail-closed); interactively
1839
+ // only a launch that switches the child's gate off is refused, so a person keeps what 0.35.25 allowed.
1840
+ const RUN = (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id);
1841
+ // @implements A-SPEC-774.11 §2 — interactively a launch passes only the known-safe option list; a deny-list of
1842
+ // gate-off flags did not close.
1843
+ // @implements A-SPEC-774.12 — and one gate-off marker list serves the shell segment and the interpreter spawn,
1844
+ // which cannot be read option by option (`spawnSync('codex',[…,'-c','approval_policy=never'])` passed).
1845
+ const GATE_OFF = RUN.run ? null
1846
+ // @implements A-SPEC-774.26 — the markers read the segment's option words, not its quoted prompt.
1847
+ : (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)
1848
+ ?? (interpreterSpawnsAgent(command) ? (0, agent_launch_policy_1.gateOffMarker)(command) : null));
1849
+ const AGENT_LAUNCH = (RUN.run && agentCliLaunch(command)) || GATE_OFF !== null;
1438
1850
  const providerCredential = /\b(?:GEMINI_API_KEY|GOOGLE_API_KEY)\b/.test(command);
1439
1851
  const usesSecret =
1440
1852
  // @implements A-SPEC-477 — the credential file is the same secret at rest; reading,
@@ -1448,15 +1860,18 @@ function evaluateHook(input, specsDir, opts) {
1448
1860
  // A quoted key only counts as a LOOKUP when something indexes or calls with it —
1449
1861
  // `env['VAR']`, `getenv("VAR")`, `ENVIRON["VAR"]`. A quoted bare word after a space is a
1450
1862
  // search pattern (`grep "VAR" file`), which is the false positive being removed.
1451
- new RegExp(String.raw `[[(]\s*['"\`]${SECRET}['"\`]`).test(command);
1452
- const dumpsEnv = usesSecret ||
1863
+ new RegExp(String.raw `[[(]\s*['"\`]${SECRET}['"\`]`).test(command) ||
1864
+ // @implements A-SPEC-774.2 §1-2 — the name in any position or spelling, except inside a read-only search.
1865
+ (authorityMention(command) && !readOnlySearch(command));
1866
+ const dumpsEnv = AGENT_LAUNCH ||
1867
+ usesSecret ||
1453
1868
  dumpsEnvInCommandPosition(command) || // env/printenv as a COMMAND
1454
1869
  // @implements A-SPEC-728 (round 4) — `[ \t]` where `\s` spanned newlines: 190 000 newlines made
1455
1870
  // every start re-scan the rest (23 s); a newline is itself a separator, so the verdict is the same.
1456
1871
  /(^|[;&|\n][ \t]*)(?:set|export[ \t]+-p|declare[ \t]+-x|typeset[ \t]+-x)[ \t]*(?:$|[;&|\n>])/.test(command) ||
1457
1872
  /\$\{!\s*\w/.test(command) || // ${!VAR*} indirection
1458
1873
  /\/proc\/(?:self|\d+|\$\$|\$\{?\w+\}?)\/environ/.test(command) || // /proc/*/environ incl. $$
1459
- tailAfterFirst(command, /[;&|\n]/, /\bps\b/, /\s-?e\w*\b/) || // ps e / ps -e www
1874
+ psShowsEnvironment(command) || // ps e / ps -e www / ps -E (A-SPEC-747.3)
1460
1875
  // Interpreter access to the environment, in any dash form (-e/-c/-p/--eval/--print/eval).
1461
1876
  // @implements A-SPEC-163
1462
1877
  // The bare `\bENV\b` alternative is GONE. It was narrowed once already (it denied
@@ -1497,11 +1912,15 @@ function evaluateHook(input, specsDir, opts) {
1497
1912
  };
1498
1913
  }
1499
1914
  if (dumpsEnv) {
1500
- const reason = GRANTS_SELF
1501
- ? '[Holmes-Kit] the command accesses Holmes authority or semantic-egress configuration — requires operator approval'
1502
- : providerCredential
1503
- ? '[Holmes-Kit] the command accesses a protected provider credential — requires operator approval'
1504
- : '[Holmes-Kit] command reads or dumps process environment (holds out-of-band approval secrets) — requires operator approval';
1915
+ const reason = GATE_OFF !== null
1916
+ ? `[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`
1917
+ : AGENT_LAUNCH
1918
+ ? `[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`
1919
+ : GRANTS_SELF
1920
+ ? '[Holmes-Kit] the command accesses Holmes authority or semantic-egress configuration — requires operator approval'
1921
+ : providerCredential
1922
+ ? '[Holmes-Kit] the command accesses a protected provider credential — requires operator approval'
1923
+ : '[Holmes-Kit] command reads or dumps process environment (holds out-of-band approval secrets) — requires operator approval';
1505
1924
  const resolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, approval, { kind: 'config-write', target: command }, nowTs);
1506
1925
  if (!resolved) {
1507
1926
  let hint = (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: command, why: reason });
@@ -1563,9 +1982,10 @@ function evaluateHook(input, specsDir, opts) {
1563
1982
  // of the path, not an argument boundary. `[^'"\s]*` stopped at the first space and missed
1564
1983
  // `open('C:\Users\Given Family\a.ts','w')`; `[^'"]*` keeps the space and still cannot cross a quote.
1565
1984
  const NOT_QUOTE = String.raw `[^'"]*`;
1566
- const QUOTED_PATH = new RegExp(
1567
- // @implements A-SPEC-728 — plus the Codex user-level files, judged by identity below.
1568
- String.raw `['"](` + NOT_QUOTE + String.raw `\.` + CODE_EXT + '|' + NOT_QUOTE + CONFIG_FILE + '|' + NOT_QUOTE + String.raw `(?:config\.toml|hooks\.json)` + String.raw `)['"]`, 'g');
1985
+ // @implements A-SPEC-728 — plus the Codex user-level files, judged by identity below (USER_CFG_RE).
1986
+ // @implements A-SPEC-774.1 — every quoted path-like literal (a superset of the code, config and Codex
1987
+ // spellings it listed); the config rule keeps its own CFG_RE filter and the code rule asks the classifier.
1988
+ const QUOTED_PATH = new RegExp(String.raw `['"](` + NOT_QUOTE + String.raw `[\w.+-])['"]`, 'g');
1569
1989
  const out = [];
1570
1990
  for (const m of command.matchAll(QUOTED_PATH))
1571
1991
  if (m[1])
@@ -1626,14 +2046,14 @@ function evaluateHook(input, specsDir, opts) {
1626
2046
  // and the caller fails CLOSED — but only when such a candidate exists, so `cd "$X" && npm
1627
2047
  // test` stays free.
1628
2048
  const judgeCand = (c, roots) => {
1629
- if ((0, write_target_1.absoluteKindOf)(c.raw) !== null || isTilde(c.raw))
1630
- return (0, write_target_1.resolvesInside)(c.raw, roots) ? 'in' : 'out';
2049
+ if ((0, write_target_2.absoluteKindOf)(c.raw) !== null || isTilde(c.raw))
2050
+ return (0, write_target_2.resolvesInside)(c.raw, roots) ? 'in' : 'out';
1631
2051
  if (c.base === null)
1632
2052
  return 'unknown';
1633
- const pp = (0, write_target_1.pathFlavorFor)(c.base, c.raw);
2053
+ const pp = (0, write_target_2.pathFlavorFor)(c.base, c.raw);
1634
2054
  const abs = pp.resolve(c.base, c.raw);
1635
- const kind = (0, write_target_1.absoluteKindOf)(abs);
1636
- return (0, write_target_1.resolvesInside)(abs, roots, kind === 'drive' || kind === 'unc' ? path.win32 : path.posix) ? 'in' : 'out';
2055
+ const kind = (0, write_target_2.absoluteKindOf)(abs);
2056
+ return (0, write_target_2.resolvesInside)(abs, roots, kind === 'drive' || kind === 'unc' ? path.win32 : path.posix) ? 'in' : 'out';
1637
2057
  };
1638
2058
  const collectSeg = (seg, re, list) => {
1639
2059
  for (const m of seg.text.matchAll(re)) {
@@ -1644,7 +2064,11 @@ function evaluateHook(input, specsDir, opts) {
1644
2064
  };
1645
2065
  // @implements A-SPEC-728 (round 5) — the lazy `VERB[^;|&]*?PATH` extractions, in linear time
1646
2066
  // and as a superset of what the regex captured (110 s measured on 200 KB of repeated `cp`).
1647
- const WRITE_VERB = /\b(?:cp|mv|install|rsync|ln|dd|truncate|chmod|chown)\b/;
2067
+ // @implements A-SPEC-747.3 (C) — a verb only as a shell word in plain text (`grep -ln`, `java -cp`, `a.ln` are not);
2068
+ // any expansion, substitution, eval or IFS keeps the `\b…\b` test the 747.1 review requires.
2069
+ const PLAIN = (0, risk_classifier_1.plainShellText)(command);
2070
+ 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/;
2071
+ const COPY_VERB = PLAIN ? (0, risk_classifier_1.verbWordRe)('cp|mv|install|rsync|ln|dd') : /\b(?:cp|mv|install|rsync|ln|dd)\b/;
1648
2072
  // @implements A-SPEC-728 (rule 37) — a segment without the verb is not read, and each pattern is built once per
1649
2073
  // command, not once per segment (131,000 segments of `a\n` spent over half a second here — measured).
1650
2074
  const collectPaths = (seg, head, tail, list, mid) => {
@@ -1665,7 +2089,7 @@ function evaluateHook(input, specsDir, opts) {
1665
2089
  // over-approximation, sealed in A-SPEC-528.1 §3.
1666
2090
  const detBases = [...new Set(segments.map((s) => s.base).filter((b) => b !== null)), opts.projectRoot];
1667
2091
  const hasUnknownBase = segments.some((s) => s.base === null);
1668
- const expandInterp = (raw) => (0, write_target_1.absoluteKindOf)(raw) !== null || isTilde(raw)
2092
+ const expandInterp = (raw) => (0, write_target_2.absoluteKindOf)(raw) !== null || isTilde(raw)
1669
2093
  ? [{ raw, base: opts.projectRoot }]
1670
2094
  : [...detBases.map((b) => ({ raw, base: b })), ...(hasUnknownBase ? [{ raw, base: null }] : [])];
1671
2095
  // @implements A-SPEC-447 — one containment predicate, shared with the code rule below.
@@ -1702,7 +2126,7 @@ function evaluateHook(input, specsDir, opts) {
1702
2126
  if (userCfgList === null)
1703
2127
  return TOO_MANY_CANDIDATES;
1704
2128
  const userCfgKind = userCfgList
1705
- .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)))
2129
+ .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)))
1706
2130
  .find((k) => k !== null);
1707
2131
  // One config-write approval (env or a granted queue request for this exact command) lifts both
1708
2132
  // rules below; the refusal files that request, as the Write/Edit config gate does.
@@ -1727,14 +2151,30 @@ function evaluateHook(input, specsDir, opts) {
1727
2151
  // ways in one adversarial round. Data heredoc bodies are not commands and are not judged.
1728
2152
  if (!hardHitlCovered && !configWriteLifted) {
1729
2153
  // Every segment, heredoc bodies included (round 2: a `<<` in quotes hid the lines after it).
1730
- const act = (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase);
2154
+ let act = (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase);
2155
+ // @implements A-SPEC-476.3 — a shell write to ax.config.json cannot be read, so it asks only where a cap could rise
2156
+ // (the disk sets one below its widest value); in a run it is refused outright, with no approval to lift it.
2157
+ if (act && act.includes(write_target_1.PROJECT_CAPS_LABEL)) {
2158
+ const onDisk = (0, project_caps_1.readProjectCaps)(opts.projectRoot);
2159
+ if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2160
+ 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)` };
2161
+ }
2162
+ if (!(0, project_caps_1.capsAtWidest)(onDisk)) {
2163
+ 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)`);
2164
+ if (refusal)
2165
+ return refusal;
2166
+ }
2167
+ // @implements A-SPEC-476.7 — the cap act is settled; the rest of the command is judged with the caps file out of the
2168
+ // wiring set (the scan stops at its first act, and an allowed cap write hid an unlink of the hook wiring after it).
2169
+ act = (0, write_target_1.withoutProjectCaps)(() => (0, shell_words_1.harnessWiringActOfCommand)(opts.projectRoot, command, process.env, os.homedir(), shellBase));
2170
+ }
1731
2171
  if (act) {
1732
2172
  // @implements A-SPEC-728 (round 9) — `.ax` is named for what it is: the spec store and ledger.
1733
2173
  // @implements A-SPEC-728 (rule 38) — an input too large to judge is refused as such (a large loop read "… is the wiring
1734
2174
  // that loads this session's gate").
1735
2175
  const refusal = liftByConfigWrite(/too (?:large|long|complex) to judge|too many calls to judge/.test(act)
1736
2176
  ? `${act}: it is refused rather than judged, because deleting, moving or rewriting the wiring that loads this session's gate turns governance off`
1737
- : act.includes(write_target_1.GOVERNANCE_STORE_LABEL) || /^\.ax\//.test(act)
2177
+ : act.includes(write_target_2.GOVERNANCE_STORE_LABEL) || /^\.ax\//.test(act)
1738
2178
  ? `${act} is this project's governance state — moving, deleting or bulk-replacing it turns No-Spec-No-Code off`
1739
2179
  : `${act} is the wiring that loads this session's gate — deleting, moving or rewriting it turns governance off`);
1740
2180
  if (refusal)
@@ -1754,8 +2194,11 @@ function evaluateHook(input, specsDir, opts) {
1754
2194
  // `> ../elsewhere/a.ts`, which leaves the governed tree entirely.
1755
2195
  // @implements A-SPEC-463 — same quoted-space fix as the config rule; `EXT_TAIL` is the
1756
2196
  // extension part and `pathAlt` supplies the prefix and the quoting alternatives.
1757
- const EXT_TAIL = `\\.${CODE_EXT}`;
1758
- const CODE_TAIL_RE_SED = new RegExp(`${EXT_TAIL}$`);
2197
+ // @implements A-SPEC-774.1 — every path in write position is collected (`ANY_TAIL`: a path ends on a path
2198
+ // character), and `governedCode` below keeps those the Write tool's classifier calls code or test. The private
2199
+ // extension list this replaced let `deploy.sh`, `Makefile`, `Dockerfile`, a CI workflow and `src/a.c` through
2200
+ // while `src/a.ts` was refused (measured 2026-10-17): two judges disagreed about what code is.
2201
+ const EXT_TAIL = '[\\w.+-]';
1759
2202
  const candidates = [];
1760
2203
  const CODE_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(EXT_TAIL)}`, 'g');
1761
2204
  for (const seg of segments) {
@@ -1765,8 +2208,7 @@ function evaluateHook(input, specsDir, opts) {
1765
2208
  // `sed -i` segment was a candidate, so `sed -i '' 's#a.test.ts#src/x.ts#' <outside>/notes.md` was denied as a
1766
2209
  // project code write (measured 2026-10-01).
1767
2210
  for (const raw of sedInPlaceFiles(seg.text))
1768
- if (CODE_TAIL_RE_SED.test(raw))
1769
- candidates.push({ raw, base: seg.base });
2211
+ candidates.push({ raw, base: seg.base });
1770
2212
  }
1771
2213
  // @implements A-SPEC-449 — the copy/move family. The CONFIG rule has carried it since
1772
2214
  // A-SPEC-191 §28 ("a gate that names one syntax for an act is a gate over that syntax, not
@@ -1775,10 +2217,11 @@ function evaluateHook(input, specsDir, opts) {
1775
2217
  // which is an ordinary backup and not this gate's business.
1776
2218
  // (A data heredoc body may still carry separators inside one segment, so the per-segment
1777
2219
  // text is split the way the whole command used to be — the base is the segment's either way.)
1778
- const CODE_TAIL_RE = new RegExp(`\\.${CODE_EXT}$`);
2220
+ // A-SPEC-774.1: any destination is a candidate; the classifier filter decides which are code.
2221
+ const CODE_TAIL_RE = { test: (_p) => true };
1779
2222
  for (const seg of segments) {
1780
2223
  for (const sub of seg.text.split(/[;|&]+/)) {
1781
- if (!/\b(?:cp|mv|install|rsync|ln|dd)\b/.test(sub))
2224
+ if (!COPY_VERB.test(sub))
1782
2225
  continue;
1783
2226
  const of = sub.match(new RegExp(`\\bof=${pathAlt(EXT_TAIL)}`));
1784
2227
  if (of) {
@@ -1836,7 +2279,7 @@ function evaluateHook(input, specsDir, opts) {
1836
2279
  if (/[/\\]$/.test(d))
1837
2280
  return true; // trailing separator = explicit dir
1838
2281
  try {
1839
- 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));
2282
+ 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));
1840
2283
  return abs !== undefined && fs.statSync(abs).isDirectory();
1841
2284
  }
1842
2285
  catch {
@@ -1849,17 +2292,79 @@ function evaluateHook(input, specsDir, opts) {
1849
2292
  }
1850
2293
  else if (argv.length >= 2) {
1851
2294
  const dest = argv[argv.length - 1];
1852
- if (CODE_TAIL_RE.test(dest))
1853
- candidates.push({ raw: dest, base: seg.base }); // dest is a code file
1854
- else if (looksLikeDir(dest))
2295
+ // A-SPEC-774.1: a directory first — every destination is now a candidate, so the order decides.
2296
+ if (looksLikeDir(dest))
1855
2297
  pushLanding(dest, argv.slice(0, -1)); // dest is a directory
2298
+ else if (CODE_TAIL_RE.test(dest))
2299
+ candidates.push({ raw: dest, base: seg.base }); // dest is a file
1856
2300
  }
1857
2301
  }
1858
2302
  }
1859
2303
  // @implements A-SPEC-447 — same predicate as the config rule; it lived in two copies, which
1860
2304
  // is how one of two gets fixed.
1861
- const CODE_RE = new RegExp(`\\.${CODE_EXT}$`);
1862
- const codeList = distinct([...candidates, ...interpreterWrites.filter((p) => CODE_RE.test(p)).flatMap(expandInterp)]);
2305
+ // @implements A-SPEC-774.1 — kept when the Write tool's classifier calls the landing file code or test. It is
2306
+ // judged project-relative where the candidate resolves inside the root (a CI folder is a location, not a
2307
+ // name), else as spelled; the filter runs before `distinct`, so the limit counts only governed targets.
2308
+ const judgedPath = (c) => {
2309
+ if (c.base === null && (0, write_target_2.absoluteKindOf)(c.raw) === null && !isTilde(c.raw))
2310
+ return c.raw;
2311
+ const abs = (0, write_target_2.absoluteKindOf)(c.raw) !== null || isTilde(c.raw) || c.base === null
2312
+ ? c.raw : (0, write_target_2.pathFlavorFor)(c.base, c.raw).resolve(c.base, c.raw);
2313
+ const rel = path.relative(opts.projectRoot, abs);
2314
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : abs;
2315
+ };
2316
+ // @implements A-SPEC-775.1 — judged in the mode the Write tool judges in (a run or the owner's strict opt-in).
2317
+ const shellClassify = (0, classification_mode_1.classifyOptionsFor)(opts.projectRoot, (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run);
2318
+ const governedCode = (c) => {
2319
+ const kind = (0, phase_1.classifyAction)(judgedPath(c).replace(/\\/g, '/'), undefined, shellClassify);
2320
+ return kind === 'WRITE_CODE' || kind === 'WRITE_TEST';
2321
+ };
2322
+ // @implements A-SPEC-774.5 §2 — under a role policy EVERY in-project shell write asks the role, as the Write
2323
+ // tool does: a WRITE_TEST-only reviewer wrote config/profile.yaml and requirements.txt through printf
2324
+ // (supervisor probe, 2026-10-17) because only code/test candidates were ever judged.
2325
+ const shellPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2326
+ if (shellPolicy !== null) {
2327
+ const shellIdentity = new identity_1.EnvIdentityProvider().current();
2328
+ for (const c of [...candidates, ...interpreterWrites.flatMap(expandInterp)]) {
2329
+ if (judgeCand(c, [opts.projectRoot]) !== 'in')
2330
+ continue;
2331
+ // @implements A-SPEC-774.10 — a legacy policy outside a run keeps the 0.35.25 freedom for WRITE_OTHER.
2332
+ 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 });
2333
+ if (issue)
2334
+ return { permissionDecision: 'deny', permissionDecisionReason: issue };
2335
+ }
2336
+ }
2337
+ // @implements A-SPEC-774.23 — a scoped run's shell writes stay inside its plan, as its file tool writes do.
2338
+ {
2339
+ const inProject = [...candidates, ...interpreterWrites.flatMap(expandInterp)]
2340
+ .filter((c) => judgeCand(c, [opts.projectRoot]) === 'in').map((c) => path.resolve(opts.projectRoot, judgedPath(c)));
2341
+ const outside = (0, run_plan_scope_1.planScopeRefusal)({ projectRoot: opts.projectRoot, specsDir, env: process.env, cwd: input.cwd, sessionId: input.session_id }, inProject);
2342
+ if (outside)
2343
+ return { permissionDecision: 'deny', permissionDecisionReason: outside };
2344
+ }
2345
+ // @implements A-SPEC-747.4 — a write whose destination or command word is computed at run time (xargs input, find's
2346
+ // `{}`, a variable, an IFS join) never reached the literal-destination rule above: 19 such writes to code files
2347
+ // were allowed on 0.35.25 and here (census 2026-10-19). A runner's literal destination joins the candidates; a
2348
+ // computed one is refused unless every literal path in the segment lies outside the project.
2349
+ let computedWrite = null;
2350
+ const commandTokens = segments.flatMap((seg) => (0, dynamic_write_1.pathTokensOf)(seg.text).map((raw) => ({ raw, base: seg.base })));
2351
+ const writeContext = (0, dynamic_write_1.commandContext)(command);
2352
+ for (const seg of segments) {
2353
+ const dw = (0, dynamic_write_1.dynamicWrites)(seg.text, writeContext);
2354
+ for (const raw of dw.statics)
2355
+ candidates.push({ raw, base: seg.base });
2356
+ if (dw.dynamic === null || computedWrite !== null)
2357
+ continue;
2358
+ if (!(commandTokens.length > 0 && commandTokens.every((c) => judgeCand(c, [opts.projectRoot]) === 'out')))
2359
+ computedWrite = dw.dynamic.why;
2360
+ }
2361
+ if (computedWrite === null && writeContext.computed && commandTokens.some((c) => governedCode(c) && judgeCand(c, [opts.projectRoot]) === 'in')) {
2362
+ computedWrite = 'computed command';
2363
+ }
2364
+ if (computedWrite !== null && readSpecsSync(specsDir).length > 0) {
2365
+ return { permissionDecision: 'deny', permissionDecisionReason: `${SHELL_CODE_WRITE_REASON} (its target is computed at run time: ${computedWrite}, A-SPEC-747.4)` };
2366
+ }
2367
+ const codeList = distinct([...candidates, ...interpreterWrites.flatMap(expandInterp)].filter(governedCode));
1863
2368
  // Rule 43: only a governed project judges this list — an ungoverned one was refused for nothing it would check.
1864
2369
  if (codeList === null && readSpecsSync(specsDir).length > 0)
1865
2370
  return TOO_MANY_CANDIDATES;
@@ -1881,7 +2386,7 @@ function evaluateHook(input, specsDir, opts) {
1881
2386
  const governed = readSpecsSync(specsDir).length > 0;
1882
2387
  if (governed) {
1883
2388
  return codeVerdicts.includes('in')
1884
- ? { 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' }
2389
+ ? { permissionDecision: 'deny', permissionDecisionReason: SHELL_CODE_WRITE_REASON }
1885
2390
  : { permissionDecision: 'deny', permissionDecisionReason: UNRESOLVED_BASE_DENY };
1886
2391
  }
1887
2392
  }
@@ -1932,10 +2437,38 @@ function evaluateHook(input, specsDir, opts) {
1932
2437
  (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, approval.nonce);
1933
2438
  }
1934
2439
  }
2440
+ // @implements A-SPEC-774.13 — an allowed interactive launch inherits this session's authority variables; a hook
2441
+ // cannot change a command's environment, so it names them (never their values) and gives the operator's re-run.
2442
+ if (agentCliLaunch(command) && !(0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2443
+ const inherited = ['HOLMES_APPROVAL', 'HOLMES_ROLE', 'HOLMES_GATE_BYPASS', 'HOLMES_AUTONOMOUS_APPROVAL', 'HOLMES_LEDGER_KEY']
2444
+ .filter((n) => typeof process.env[n] === 'string' && process.env[n] !== '');
2445
+ if (inherited.length > 0) {
2446
+ return { permissionDecision: 'allow', permissionDecisionReason: `[Holmes-Kit] the agent this command launches inherits `
2447
+ + `${inherited.join(', ')} from this session. To start it without that authority, the operator runs it from their own `
2448
+ + `terminal: env ${inherited.map((n) => `-u ${n}`).join(' ')} ${command.length > 200 ? `${command.slice(0, 200)}…` : command} (A-SPEC-774.13)` };
2449
+ }
2450
+ }
1935
2451
  // auto/notify/confirm, or hard-hitl with a valid approval: this slice blocks only
1936
2452
  // hard-hitl; confirm is advisory here.
1937
2453
  return { permissionDecision: 'allow' };
1938
2454
  }
2455
+ // @implements A-SPEC-776 — a foreign MCP tool that is not a read is judged as a Write of every path it names,
2456
+ // whatever the field is called; a location that is not a file path is refused rather than skipped.
2457
+ const foreign = input.tool_input.foreign_paths ?? (0, write_target_2.foreignMcpPaths)(input.tool_name, input.tool_input);
2458
+ if (foreign && (foreign.paths.length > 0 || foreign.unresolvable.length > 0)) {
2459
+ if (foreign.unresolvable.length > 0) {
2460
+ 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)` };
2461
+ }
2462
+ if (foreign.paths.length > 64) {
2463
+ 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)` };
2464
+ }
2465
+ for (const fp of foreign.paths) {
2466
+ const v = evaluateHook({ tool_name: 'Write', tool_input: { file_path: fp, content: '' }, ...(input.cwd === undefined ? {} : { cwd: input.cwd }) }, specsDir, opts);
2467
+ if (v.permissionDecision === 'deny') {
2468
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} → ${fp.slice(0, 120)}: ${v.permissionDecisionReason ?? ''}` };
2469
+ }
2470
+ }
2471
+ }
1939
2472
  // @implements A-SPEC-191 §27 (round 13) — `PATH_FIELDS` exists because `notebook_path` slipped
1940
2473
  // past a gate that knew only `file_path`, and this line still knew only `file_path`: a valid
1941
2474
  // NotebookEdit was denied in EVERY project with "cannot read the edit target path", which names
@@ -1959,7 +2492,7 @@ function evaluateHook(input, specsDir, opts) {
1959
2492
  permissionDecisionReason: '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)',
1960
2493
  };
1961
2494
  }
1962
- const writesCode = (0, write_target_1.writesFiles)(input.tool_name, input.tool_input);
2495
+ const writesCode = (0, write_target_2.writesFiles)(input.tool_name, input.tool_input);
1963
2496
  // @implements A-SPEC-144
1964
2497
  // A code-writing tool with NO readable target must not pass in a governed project. Measured
1965
2498
  // end-to-end after normalization landed: dropping a non-string `file_path` stopped the exception
@@ -2042,7 +2575,7 @@ function evaluateHook(input, specsDir, opts) {
2042
2575
  // "is this POSIX-absolute" while meaning "is this absolute". `C:/proj/src/app.ts` answers false,
2043
2576
  // so identity resolution, case folding and containment were all skipped on native Windows — the
2044
2577
  // very filesystem (NTFS) the case-folding comment below names.
2045
- const absKind = (0, write_target_1.absoluteKindOf)(norm);
2578
+ const absKind = (0, write_target_2.absoluteKindOf)(norm);
2046
2579
  if (absKind === 'unc') {
2047
2580
  // A network path has no local filesystem identity to resolve, so containment cannot be decided.
2048
2581
  // A-SPEC-191 §17/§29 both began as "the gate did not refuse to govern — it concluded there was
@@ -2068,7 +2601,7 @@ function evaluateHook(input, specsDir, opts) {
2068
2601
  // A drive letter means NTFS or FAT, both case-folding; that is carried by the syntax, so it is
2069
2602
  // a fact here rather than a guess about the host.
2070
2603
  if (flipped === projectRoot)
2071
- return (0, write_target_1.foldsCaseBySyntax)(absKind) || process.platform === 'darwin' || process.platform === 'win32';
2604
+ return (0, write_target_2.foldsCaseBySyntax)(absKind) || process.platform === 'darwin' || process.platform === 'win32';
2072
2605
  if (flipped === projectRoot)
2073
2606
  return false;
2074
2607
  try {
@@ -2083,7 +2616,7 @@ function evaluateHook(input, specsDir, opts) {
2083
2616
  // project reached over a path this process cannot resolve is the same situation. Only the
2084
2617
  // syntax fact is used here — a drive letter is NTFS or FAT, both case-folding — so POSIX
2085
2618
  // inputs, for which this is always false, keep their previous verdict exactly.
2086
- return (0, write_target_1.foldsCaseBySyntax)(absKind);
2619
+ return (0, write_target_2.foldsCaseBySyntax)(absKind);
2087
2620
  }
2088
2621
  })();
2089
2622
  const fold = (s) => (caseBlind ? s.toLowerCase() : s);
@@ -2097,7 +2630,7 @@ function evaluateHook(input, specsDir, opts) {
2097
2630
  if (canonical === null) {
2098
2631
  // @implements A-SPEC-728 — outside the project is free, EXCEPT the user-level harness config
2099
2632
  // that loads this session's gate (`~/.claude/settings*.json`, Codex `config.toml`/`hooks.json`).
2100
- const userKind = (0, write_target_1.userHarnessConfigKindOf)(norm, projectRoot);
2633
+ const userKind = (0, write_target_2.userHarnessConfigKindOf)(norm, projectRoot);
2101
2634
  if (userKind === null)
2102
2635
  return { permissionDecision: 'allow' };
2103
2636
  const userResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
@@ -2141,7 +2674,7 @@ function evaluateHook(input, specsDir, opts) {
2141
2674
  // that may do everything, or a `default:` granting it without any claim at all. REQ-152 identified
2142
2675
  // this threat and closed only the shell entrance; a plain Write was measured as ALLOWED. Unlike
2143
2676
  // specs, no approval seal covers this file, so the write itself must be the thing that is gated.
2144
- if ((0, write_target_1.protectedKindOf)(opts.projectRoot, norm) === path.join('.ax', 'roles')) {
2677
+ if ((0, write_target_2.protectedKindOf)(opts.projectRoot, norm) === path.join('.ax', 'roles')) {
2145
2678
  // @implements A-SPEC-245 — grant files answer here too; consumed on the allowed write below.
2146
2679
  const rolesResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2147
2680
  if (rolesResolved === undefined) {
@@ -2157,24 +2690,43 @@ function evaluateHook(input, specsDir, opts) {
2157
2690
  }
2158
2691
  // @implements A-SPEC-191 §22 — ask by identity. A spelling regex was defeated by a single in-project link.
2159
2692
  // @implements A-SPEC-728 — a project that itself sits in a harness home still protects those files.
2160
- const configKind = (0, write_target_1.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_1.userHarnessConfigKindOf)(norm, opts.projectRoot);
2693
+ const configKind = (0, write_target_2.protectedFileKindOf)(opts.projectRoot, norm) ?? (0, write_target_2.userHarnessConfigKindOf)(norm, opts.projectRoot);
2161
2694
  // @implements A-SPEC-163 — identity, not spelling. Measured: `.ax//ledger//p.jsonl`,
2162
2695
  // `.ax/./ledger/p.jsonl` and `.AX/roles/policy.yaml` all reached the protected file while the
2163
2696
  // regex saw a different string. Adding `//` to the pattern would only move the next variant.
2164
- if (configKind !== null || (0, write_target_1.isProtectedTarget)(opts.projectRoot, norm)) {
2697
+ if (configKind !== null || (0, write_target_2.isProtectedTarget)(opts.projectRoot, norm)) {
2165
2698
  // @implements A-SPEC-133 — a token scoped to config-write authorizes this; a spec-only or
2166
2699
  // out-of-scope token does not, so config forgery cannot ride a narrow grant.
2167
2700
  const cfgResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2168
2701
  if (cfgResolved === undefined) {
2169
2702
  // @implements A-SPEC-193 §8 — name what was blocked. Baking a list into the sentence makes the
2170
2703
  // wording false as harnesses grow (REQ-155: a diagnosis that points at the wrong file has negative value).
2171
- const kindName = configKind ?? (0, write_target_1.protectedKindOf)(opts.projectRoot, norm) ?? 'config';
2704
+ const kindName = configKind ?? (0, write_target_2.protectedKindOf)(opts.projectRoot, norm) ?? 'config';
2172
2705
  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`
2173
2706
  + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: norm, why: `writing ${kindName}` }) };
2174
2707
  }
2175
2708
  if (cfgResolved.source === 'grant' && cfgResolved.approval.nonce)
2176
2709
  (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, cfgResolved.approval.nonce);
2177
2710
  }
2711
+ // @implements A-SPEC-476.3 — the owner's caps in ax.config.json narrow this agent: raising or removing one is the owner's
2712
+ // act (owner decision 2026-10-19), lowering stays free, and in a run no write changes one.
2713
+ if ((0, write_target_1.isProjectConfigTarget)(opts.projectRoot, norm)) {
2714
+ const capsAct = projectCapsWriteAct(opts.projectRoot, input);
2715
+ if (capsAct !== null) {
2716
+ if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2717
+ 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)` };
2718
+ }
2719
+ if (capsAct !== 'lowered') {
2720
+ const capsResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2721
+ if (capsResolved === undefined) {
2722
+ 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)`
2723
+ + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'config-write', target: norm, why: `raising a project cap (${capsAct})` }) };
2724
+ }
2725
+ if (capsResolved.source === 'grant' && capsResolved.approval.nonce)
2726
+ (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, capsResolved.approval.nonce);
2727
+ }
2728
+ }
2729
+ }
2178
2730
  // Spec-file edit → graph-aware blast-radius risk (Tier-2 push-feed): a change to a widely-depended-on
2179
2731
  // or foundational (REQ) spec ripples across the graph, so its risk is assessed from the spec
2180
2732
  // dependency graph and escalated to out-of-band approval when the impact reaches the hard-hitl
@@ -2182,9 +2734,23 @@ function evaluateHook(input, specsDir, opts) {
2182
2734
  // @implements A-SPEC-191 §23 (round 12) — identity, like every other protected surface. The
2183
2735
  // resolved path is also what the disk is read with below: `existsSync(p)` on the caller's raw
2184
2736
  // spelling answered "not approved" for `<file>/` and skipped the seal-breaking branch entirely.
2185
- const specTarget = (0, write_target_1.specTargetOf)(opts.projectRoot, specsDir, norm);
2737
+ const specTarget = (0, write_target_2.specTargetOf)(opts.projectRoot, specsDir, norm);
2186
2738
  if (specTarget !== null) {
2187
2739
  const p = specTarget;
2740
+ // @implements A-SPEC-774 §1 — the role is asked first. This branch returned `allow` long before `roleCheck`
2741
+ // was reached, so a reviewer allowed only WRITE_TEST wrote A-SPEC and T-SPEC files (measured 2026-10-17).
2742
+ // A spec-write approval does not lift it: an approval changes what is approved, not who the caller is.
2743
+ const specPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2744
+ if (specPolicy !== null) {
2745
+ // The resolved path, not one made relative: the store's real path and the root's spelling can differ
2746
+ // (`/var` vs `/private/var`), and the authoring folders are matched as segments either way.
2747
+ const specAction = (0, phase_1.classifyAction)(p.replace(/\\/g, '/')) ?? 'AUTHOR_REQ';
2748
+ // @implements A-SPEC-774.14 — amends 774.8: the run carries its run-only default-breadth check here. 774.10's
2749
+ // legacy reading uses the same value.
2750
+ 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 });
2751
+ if (specRoleIssue)
2752
+ return { permissionDecision: 'deny', permissionDecisionReason: specRoleIssue };
2753
+ }
2188
2754
  // F1: a spec cannot SELF-APPROVE. `status: approved` is what unlocks every downstream gate
2189
2755
  // (phaseCheck trusts the on-disk status). If the incoming write promotes a spec to approved and it
2190
2756
  // is not ALREADY approved on disk, that is a new approval — an out-of-band act, never a raw tool
@@ -2268,9 +2834,18 @@ function evaluateHook(input, specsDir, opts) {
2268
2834
  }
2269
2835
  // @implements A-SPEC-167 — the body is passed so a shebang can be seen. `Edit` carries only a
2270
2836
  // fragment, so the shebang check simply does not fire there; the path signals still answer.
2271
- const action = (0, phase_1.classifyAction)(relPath, input.tool_input.content);
2272
- if (!action)
2273
- return { permissionDecision: 'allow' };
2837
+ // @implements A-SPEC-775.1 — a run or the owner's strict opt-in narrows test folders and makes unclassified writes
2838
+ // code; interactively without strict the options change nothing but the owner's declared test folders.
2839
+ const writeClassify = (0, classification_mode_1.classifyOptionsFor)(opts.projectRoot, (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run);
2840
+ const action = (0, phase_1.classifyAction)(relPath, input.tool_input.content, writeClassify);
2841
+ if (!action) {
2842
+ // @implements A-SPEC-774 §2 — a write the classifier does not name is still a write. With no role policy it
2843
+ // stays free, as before; with one, the role must list WRITE_OTHER (a reviewer's NotebookEdit was allowed).
2844
+ const otherPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2845
+ // @implements A-SPEC-774.10 — read strictly only in a run or under a vocabulary-2 policy.
2846
+ 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 });
2847
+ return otherIssue ? { permissionDecision: 'deny', permissionDecisionReason: otherIssue } : { permissionDecision: 'allow' };
2848
+ }
2274
2849
  // Read specs synchronously via a fresh walk (hook must be sync)
2275
2850
  const specs = readSpecsSync(specsDir);
2276
2851
  // @implements A-SPEC-230 — structural constraints move from "checked by the suite" to "enforced at
@@ -2286,7 +2861,7 @@ function evaluateHook(input, specsDir, opts) {
2286
2861
  : typeof input.tool_input.new_string === 'string'
2287
2862
  ? { content: input.tool_input.new_string, mode: 'fragment' }
2288
2863
  : null;
2289
- if (proposed && (0, write_target_1.specTargetOf)(opts.projectRoot, specsDir, p) === null) {
2864
+ if (proposed && (0, write_target_2.specTargetOf)(opts.projectRoot, specsDir, p) === null) {
2290
2865
  const forbidden = [];
2291
2866
  const required = [];
2292
2867
  // @implements A-SPEC-691 — the allowances travel with the rules. They come out of the SAME
@@ -2333,15 +2908,30 @@ function evaluateHook(input, specsDir, opts) {
2333
2908
  // an existing one, because the gate looked at the file's anchors rather than the change's. Only
2334
2909
  // ADDED claims are checked — re-judging the file's existing ones would block the very edits
2335
2910
  // needed to fix a spec that moved back to draft.
2336
- if (typeof input.tool_input.content === 'string') {
2911
+ // @implements A-SPEC-166.1 — judged on what the write LEAVES, for Edit and MultiEdit as for Write: an Edit added a
2912
+ // draft spec's anchor to an anchored test file, was allowed, and locked the file (measured 2026-10-17). A file
2913
+ // that exists but cannot be read is refused — the payload never stands in for the disk (M2).
2914
+ const ti166 = input.tool_input;
2915
+ const writesText = typeof ti166.content === 'string' || typeof ti166.new_string === 'string' || Array.isArray(ti166.edits);
2916
+ if (writesText) {
2337
2917
  let previous;
2338
- try {
2339
- previous = fs.readFileSync(norm, 'utf8');
2918
+ if (fs.existsSync(norm)) {
2919
+ try {
2920
+ previous = fs.readFileSync(norm, 'utf8');
2921
+ }
2922
+ catch {
2923
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] cannot read ${relPath} to judge its anchors — the write is refused rather than judged by its own payload` };
2924
+ }
2340
2925
  }
2341
- catch {
2342
- previous = undefined;
2926
+ const edited = editedResult(previous ?? null, ti166);
2927
+ if (edited === TOO_LARGE) {
2928
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] the result of this write to ${relPath} is too large to judge its anchors` };
2343
2929
  }
2344
- const added = (0, anchors_1.newlyClaimed)(input.tool_input.content, previous);
2930
+ // An edit that does not apply: the incoming fragments are judged (over-inclusion is the safe direction).
2931
+ const leaves = edited ?? [ti166.content, ti166.new_string, ...(Array.isArray(ti166.edits)
2932
+ ? ti166.edits.map((e) => e.new_string) : [])]
2933
+ .filter((s) => typeof s === 'string').join('\n');
2934
+ const added = (0, anchors_1.newlyClaimed)(leaves, previous);
2345
2935
  // An anchor naming a spec that does not exist is worse than one naming a draft — it claims
2346
2936
  // authority from a document nobody can read. Unknown is treated as unapproved, the direction
2347
2937
  // REQ-144 established for everything the gate cannot resolve.
@@ -2480,6 +3070,14 @@ function evaluateHook(input, specsDir, opts) {
2480
3070
  const defaultSpecsAbs = path.resolve(opts.projectRoot, exports.DEFAULT_SPECS_DIR);
2481
3071
  if (specs.length === 0 && specsDirAbs === defaultSpecsAbs && !fs.existsSync(specsDirAbs)
2482
3072
  && !(0, governance_history_1.hasGovernanceHistory)(opts.projectRoot)) {
3073
+ // @implements A-SPEC-774.15 — the role gate does not depend on specs: a project that configured roles and has no
3074
+ // specs yet still asks the role (the shell and MCP paths already did). With no policy this is the old free allow.
3075
+ const ungovernedPolicy = (0, role_policy_1.loadRolePolicy)(projectRoot);
3076
+ if (ungovernedPolicy !== null) {
3077
+ 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 });
3078
+ if (issue)
3079
+ return { permissionDecision: 'deny', permissionDecisionReason: issue };
3080
+ }
2483
3081
  return { permissionDecision: 'allow' };
2484
3082
  }
2485
3083
  // Extract @implements A-SPEC-xxx from all available marker sources:
@@ -2584,8 +3182,13 @@ function evaluateHook(input, specsDir, opts) {
2584
3182
  // exists it is fail-closed: no role, an unregistered role, and a role without the action are all
2585
3183
  // refusals. The claim comes from the ENVIRONMENT only; a role in the payload would be the session
2586
3184
  // asserting its own authority, which is what ART-5 forbids on the spec axis.
2587
- const roleIssue = (0, role_policy_1.roleCheck)(action, new identity_1.EnvIdentityProvider().current(), (0, role_policy_1.loadRolePolicy)(projectRoot));
2588
- if (roleIssue && !codeWriteCovered) {
3185
+ // @implements A-SPEC-774.14 — amends 774.8: the run is passed here too (774.10's legacy reading uses it as well).
3186
+ const roleRun = (0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run;
3187
+ const roleIssue = (0, role_policy_1.roleCheck)(action, new identity_1.EnvIdentityProvider().current(), (0, role_policy_1.loadRolePolicy)(projectRoot), { run: roleRun });
3188
+ // @implements A-SPEC-774.15 — a code-write approval answers the spec gate, not who the caller is: in a run only a
3189
+ // role-override approval lifts a role refusal. Interactively a code-write approval still lifts it (0.35.25).
3190
+ const roleOverride = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'role-override', target: relPath }, nowTs);
3191
+ if (roleIssue && !roleOverride && (roleRun || !codeWriteCovered)) {
2589
3192
  return { permissionDecision: 'deny', permissionDecisionReason: roleIssue };
2590
3193
  }
2591
3194
  // @implements A-SPEC-134
@@ -2666,7 +3269,7 @@ function evaluateHook(input, specsDir, opts) {
2666
3269
  // dispensation (ART-4 asks for coverage — the gate must not refuse it), or the out-of-band
2667
3270
  // code-write approval. Anchor deletion never blocks but rides the allow as a warning — silent
2668
3271
  // RTM loss is the C12 failure mode, made audible.
2669
- const { judgeScope, fttPathTokens: fttTokens } = require('../guardrail/scope-judgment');
3272
+ const { judgeScope, fttPathTokens: fttTokens, matchesFtt } = require('../guardrail/scope-judgment');
2670
3273
  const { anchorSpecIds, stripStringLiterals } = require('../rtm/anchor-ids');
2671
3274
  const oldStr = input.tool_input.old_string ?? '';
2672
3275
  const newPayload = [input.tool_input.content ?? '', input.tool_input.new_string ?? ''].join('\n');
@@ -2688,8 +3291,43 @@ function evaluateHook(input, specsDir, opts) {
2688
3291
  fttTokensOf: (id) => fttTokens(specs.find((s) => s.id === id)?.sections['Files to Touch'] ?? ''),
2689
3292
  removedAnchorIds: beforeIds.filter((id) => !afterIds.has(id)),
2690
3293
  });
2691
- const scopeWarnings = scopeVerdict.warnings.map((w) => `[Holmes-Kit] ${w}`).join('\n');
3294
+ let scopeWarnings = scopeVerdict.warnings.map((w) => `[Holmes-Kit] ${w}`).join('\n');
3295
+ // @implements A-SPEC-166.2 — anchor self-selection after a scope refusal: the gate refused admitting this file to X,
3296
+ // and this write adds an anchor SITE naming another spec instead (the 774.14 case: a new `@implements` line for a
3297
+ // spec the disk already carried is tenure, so nothing else asks). Refused in a run or under strict; warned otherwise.
3298
+ if (scopeVerdict.decision !== 'admission-required' && !codeWriteCovered) {
3299
+ const refused = (0, scope_refusal_memory_1.recentScopeRefusals)(projectRoot, relPath.replace(/\\/g, '/'))
3300
+ .filter((x) => !fttTokens(specs.find((s) => s.id === x)?.sections['Files to Touch'] ?? '').some((t) => matchesFtt(t, relPath)));
3301
+ if (refused.length > 0) {
3302
+ const { anchorSpecSites } = require('../rtm/anchor-ids');
3303
+ const disk = onDiskContent;
3304
+ const leftRaw = editedResult(disk === '' && !fs.existsSync(p) ? null : disk, input.tool_input);
3305
+ const left = typeof leftRaw === 'string' ? leftRaw : newPayload;
3306
+ const beforeSites = anchorSpecSites(disk);
3307
+ const afterSites = anchorSpecSites(left);
3308
+ const beforeCount = new Map();
3309
+ for (const s of beforeSites)
3310
+ beforeCount.set(s.spec, (beforeCount.get(s.spec) ?? 0) + 1);
3311
+ const added = new Set();
3312
+ for (const s of afterSites) {
3313
+ const n = beforeCount.get(s.spec) ?? 0;
3314
+ if (n > 0)
3315
+ beforeCount.set(s.spec, n - 1);
3316
+ else
3317
+ added.add(s.spec);
3318
+ }
3319
+ const others = [...added].filter((y) => !refused.includes(y));
3320
+ if (afterSites.length > beforeSites.length && others.length > 0) {
3321
+ 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`;
3322
+ if (writeClassify.strict)
3323
+ return { permissionDecision: 'deny', permissionDecisionReason: why };
3324
+ scopeWarnings = [scopeWarnings, why].filter(Boolean).join('\n');
3325
+ }
3326
+ }
3327
+ }
2692
3328
  if (scopeVerdict.decision === 'admission-required' && !codeWriteCovered) { // @implements A-SPEC-133 — same code-write coverage as the stale gate
3329
+ // @implements A-SPEC-166.2 — remembered, so a following re-anchor to another spec is seen.
3330
+ (0, scope_refusal_memory_1.recordScopeRefusals)(projectRoot, relPath.replace(/\\/g, '/'), scopeVerdict.failedAdmissions.map((f) => f.id));
2693
3331
  const failed = scopeVerdict.failedAdmissions
2694
3332
  .map((f) => `${relPath} is anchored to ${f.id} but falls outside its 'Files to Touch' scope (${f.reason})`).join('; ');
2695
3333
  return {
@@ -2854,12 +3492,32 @@ if (require.main === module) {
2854
3492
  const wired = wiredSpecsDir(process.argv, process.env);
2855
3493
  return path.isAbsolute(wired) ? wired : path.join(hookProjectRoot, wired);
2856
3494
  })();
2857
- const out = evaluateHook(input, specsDirWired, {
3495
+ const judged = evaluateHook(input, specsDirWired, {
2858
3496
  projectRoot: hookProjectRoot,
2859
3497
  approval: readApprovalFromEnv(),
2860
3498
  // Round 17: rm targets resolve from the directory the shell runs in (inside the project).
2861
- resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_1.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3499
+ resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3500
+ resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
2862
3501
  });
3502
+ // @implements A-SPEC-102.5 — a scoped run writes only inside its plan, whatever the text it read asks.
3503
+ const planned = hookRoot.anchored
3504
+ ? (0, run_plan_scope_1.applyPlanScope)(judged, { projectRoot: hookProjectRoot, specsDir: specsDirWired, env: process.env, cwd: input.cwd, sessionId: input.session_id,
3505
+ tool: input.tool_name, toolInput: input.tool_input })
3506
+ : judged;
3507
+ // @implements A-SPEC-781.1 — the run's stage decides which kinds of write it may make.
3508
+ const staged = hookRoot.anchored
3509
+ ? (0, run_stages_1.applyStageGate)(planned, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id,
3510
+ tool: input.tool_name, toolInput: input.tool_input })
3511
+ : planned;
3512
+ // @implements A-SPEC-774.19 — and the role acts only in the stages it declares.
3513
+ const roled = hookRoot.anchored
3514
+ ? (0, run_stages_1.applyRoleStage)(staged, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id,
3515
+ tool: input.tool_name, toolInput: input.tool_input })
3516
+ : staged;
3517
+ // @implements A-SPEC-778 — in a run, refusals are logged and a repeated code stops the run; elsewhere unchanged.
3518
+ const out = (hookRoot.anchored
3519
+ ? (0, run_refusals_1.applyRunRefusalStop)(roled, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id, tool: input.tool_name })
3520
+ : judged);
2863
3521
  io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor(input.tool_name, out) }));
2864
3522
  // N3 provenance: record the audit-critical decision classes on the tamper-evident chain —
2865
3523
  // every DENY, and every ALLOW that was unlocked by an out-of-band approval. Fail-open: a
@@ -2889,7 +3547,8 @@ if (require.main === module) {
2889
3547
  projectRoot: hookProjectRoot,
2890
3548
  approval: undefined,
2891
3549
  // A-SPEC-734 (round 17): the same base, project and spec directory as the decision it re-asks.
2892
- resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_1.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3550
+ resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3551
+ resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
2893
3552
  })
2894
3553
  : undefined;
2895
3554
  const unlocked = withoutApproval?.permissionDecision === 'deny';