@holmes-lab/holmes-kit 0.39.0 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/CHANGELOG.md +578 -6
  2. package/README.md +120 -41
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/admission/core/admission-policy.d.ts +37 -0
  5. package/dist/holmes/admission/core/admission-policy.js +147 -0
  6. package/dist/holmes/admission/core/bounded-reader.d.ts +56 -0
  7. package/dist/holmes/admission/core/bounded-reader.js +135 -0
  8. package/dist/holmes/admission/core/change-classifier.d.ts +34 -0
  9. package/dist/holmes/admission/core/change-classifier.js +278 -0
  10. package/dist/holmes/admission/core/config-loader.d.ts +30 -0
  11. package/dist/holmes/admission/core/config-loader.js +145 -0
  12. package/dist/holmes/admission/core/event-judgement.d.ts +37 -0
  13. package/dist/holmes/admission/core/event-judgement.js +251 -0
  14. package/dist/holmes/admission/core/path-rules.d.ts +35 -0
  15. package/dist/holmes/admission/core/path-rules.js +88 -0
  16. package/dist/holmes/admission/core/pin.d.ts +7 -0
  17. package/dist/holmes/admission/core/pin.js +29 -0
  18. package/dist/holmes/admission/core/ports.d.ts +48 -0
  19. package/dist/holmes/admission/core/ports.js +11 -0
  20. package/dist/holmes/admission/core/range-resolver.d.ts +32 -0
  21. package/dist/holmes/admission/core/range-resolver.js +51 -0
  22. package/dist/holmes/admission/core/self-containment.d.ts +1 -0
  23. package/dist/holmes/admission/core/self-containment.js +125 -0
  24. package/dist/holmes/admission/core/signature-source.d.ts +9 -0
  25. package/dist/holmes/admission/core/signature-source.js +4 -0
  26. package/dist/holmes/admission/core/transition-planner.d.ts +15 -0
  27. package/dist/holmes/admission/core/transition-planner.js +14 -0
  28. package/dist/holmes/admission/core/verdict.d.ts +38 -0
  29. package/dist/holmes/admission/core/verdict.js +17 -0
  30. package/dist/holmes/admission/core/wiring.d.ts +44 -0
  31. package/dist/holmes/admission/core/wiring.js +618 -0
  32. package/dist/holmes/admission/forge/git-object-port.d.ts +4 -0
  33. package/dist/holmes/admission/forge/git-object-port.js +132 -0
  34. package/dist/holmes/assoc/assoc-arm.d.ts +1 -1
  35. package/dist/holmes/assoc/assoc-arm.js +1 -1
  36. package/dist/holmes/cli/agents.d.ts +8 -0
  37. package/dist/holmes/cli/agents.js +9 -5
  38. package/dist/holmes/cli/approve-cli.d.ts +2 -0
  39. package/dist/holmes/cli/approve-cli.js +392 -0
  40. package/dist/holmes/cli/approve-ref.d.ts +13 -7
  41. package/dist/holmes/cli/approve-ref.js +30 -10
  42. package/dist/holmes/cli/approve-status.d.ts +26 -2
  43. package/dist/holmes/cli/approve-status.js +98 -18
  44. package/dist/holmes/cli/approve-watch.d.ts +5 -0
  45. package/dist/holmes/cli/approve-watch.js +10 -5
  46. package/dist/holmes/cli/approve.d.ts +49 -13
  47. package/dist/holmes/cli/approve.js +249 -67
  48. package/dist/holmes/cli/attest.js +2 -1
  49. package/dist/holmes/cli/autonomy.d.ts +4 -1
  50. package/dist/holmes/cli/autonomy.js +17 -10
  51. package/dist/holmes/cli/codex-oracle.d.ts +11 -0
  52. package/dist/holmes/cli/codex-oracle.js +5 -1
  53. package/dist/holmes/cli/codex-toml.d.ts +10 -0
  54. package/dist/holmes/cli/codex-toml.js +36 -2
  55. package/dist/holmes/cli/doctor-boundary.d.ts +76 -0
  56. package/dist/holmes/cli/doctor-boundary.js +308 -0
  57. package/dist/holmes/cli/doctor-locks.d.ts +15 -0
  58. package/dist/holmes/cli/doctor-locks.js +119 -0
  59. package/dist/holmes/cli/doctor.d.ts +2 -0
  60. package/dist/holmes/cli/doctor.js +34 -5
  61. package/dist/holmes/cli/flags.d.ts +23 -0
  62. package/dist/holmes/cli/flags.js +89 -0
  63. package/dist/holmes/cli/index.d.ts +5 -1
  64. package/dist/holmes/cli/index.js +226 -442
  65. package/dist/holmes/cli/init.js +33 -0
  66. package/dist/holmes/cli/interactive-prompt.d.ts +39 -2
  67. package/dist/holmes/cli/interactive-prompt.js +98 -16
  68. package/dist/holmes/cli/lock-recover.d.ts +5 -0
  69. package/dist/holmes/cli/lock-recover.js +126 -0
  70. package/dist/holmes/cli/mcp-processes.js +1 -1
  71. package/dist/holmes/cli/release-docs.js +1 -1
  72. package/dist/holmes/cli/run-exec.d.ts +141 -0
  73. package/dist/holmes/cli/run-exec.js +1435 -0
  74. package/dist/holmes/cli/run-provision.d.ts +3 -1
  75. package/dist/holmes/cli/run-provision.js +255 -44
  76. package/dist/holmes/cli/run-wiring.d.ts +69 -0
  77. package/dist/holmes/cli/run-wiring.js +270 -0
  78. package/dist/holmes/cli/run.d.ts +21 -0
  79. package/dist/holmes/cli/run.js +341 -92
  80. package/dist/holmes/cli/runtime-binding-approval.js +32 -19
  81. package/dist/holmes/cli/screen-safe.d.ts +3 -92
  82. package/dist/holmes/cli/screen-safe.js +18 -756
  83. package/dist/holmes/config/config.d.ts +19 -0
  84. package/dist/holmes/config/config.js +18 -3
  85. package/dist/holmes/cpg/foundation/language-matrix.js +2 -2
  86. package/dist/holmes/cpg/import-resolver.js +1 -1
  87. package/dist/holmes/governance/approval-decisions.d.ts +47 -0
  88. package/dist/holmes/governance/approval-decisions.js +29 -0
  89. package/dist/holmes/governance/approval-grants.d.ts +220 -1
  90. package/dist/holmes/governance/approval-grants.js +612 -33
  91. package/dist/holmes/governance/approval-queue.d.ts +26 -0
  92. package/dist/holmes/governance/approval-queue.js +109 -11
  93. package/dist/holmes/governance/approval-spend.d.ts +95 -0
  94. package/dist/holmes/governance/approval-spend.js +191 -0
  95. package/dist/holmes/governance/autonomous-shell.d.ts +61 -0
  96. package/dist/holmes/governance/autonomous-shell.js +332 -0
  97. package/dist/holmes/governance/autonomy.d.ts +12 -0
  98. package/dist/holmes/governance/autonomy.js +51 -15
  99. package/dist/holmes/governance/constitution.d.ts +5 -0
  100. package/dist/holmes/governance/constitution.js +32 -12
  101. package/dist/holmes/governance/full-autonomy.d.ts +10 -0
  102. package/dist/holmes/governance/full-autonomy.js +103 -7
  103. package/dist/holmes/governance/harness-catalog.d.ts +103 -0
  104. package/dist/holmes/governance/harness-catalog.js +348 -0
  105. package/dist/holmes/governance/human-channel.d.ts +38 -0
  106. package/dist/holmes/governance/human-channel.js +49 -0
  107. package/dist/holmes/governance/install-manifest.d.ts +22 -0
  108. package/dist/holmes/governance/install-manifest.js +160 -0
  109. package/dist/holmes/governance/ledger-rechain.js +2 -0
  110. package/dist/holmes/governance/ledger-store.conformance.d.ts +7 -1
  111. package/dist/holmes/governance/ledger-store.conformance.js +66 -0
  112. package/dist/holmes/governance/ledger-store.d.ts +88 -11
  113. package/dist/holmes/governance/ledger-store.js +186 -8
  114. package/dist/holmes/governance/provenance-chain.d.ts +16 -4
  115. package/dist/holmes/governance/provenance-chain.js +19 -4
  116. package/dist/holmes/governance/provenance-ledger.d.ts +6 -3
  117. package/dist/holmes/governance/provenance-ledger.js +53 -18
  118. package/dist/holmes/governance/push-gate-runner.d.ts +2 -0
  119. package/dist/holmes/governance/push-gate-runner.js +50 -9
  120. package/dist/holmes/governance/push-gate.d.ts +13 -2
  121. package/dist/holmes/governance/push-gate.js +106 -14
  122. package/dist/holmes/governance/recorded-pairs.d.ts +96 -0
  123. package/dist/holmes/governance/recorded-pairs.js +522 -0
  124. package/dist/holmes/governance/replica-id.d.ts +1 -1
  125. package/dist/holmes/governance/replica-id.js +1 -1
  126. package/dist/holmes/governance/spec-seam.d.ts +59 -0
  127. package/dist/holmes/governance/spec-seam.js +587 -0
  128. package/dist/holmes/governance/spend-kinds.d.ts +16 -0
  129. package/dist/holmes/governance/spend-kinds.js +18 -0
  130. package/dist/holmes/guardrail/advisory-line.d.ts +102 -0
  131. package/dist/holmes/guardrail/advisory-line.js +718 -0
  132. package/dist/holmes/guardrail/decision-ledger.d.ts +2 -1
  133. package/dist/holmes/guardrail/decision-ledger.js +2 -1
  134. package/dist/holmes/guardrail/impact-gate.d.ts +7 -0
  135. package/dist/holmes/guardrail/impact-gate.js +33 -6
  136. package/dist/holmes/guardrail/line-continuation.d.ts +8 -0
  137. package/dist/holmes/guardrail/line-continuation.js +39 -0
  138. package/dist/holmes/guardrail/operator-person.d.ts +28 -4
  139. package/dist/holmes/guardrail/operator-person.js +57 -11
  140. package/dist/holmes/guardrail/refusal-codes.d.ts +8 -3
  141. package/dist/holmes/guardrail/refusal-codes.js +64 -10
  142. package/dist/holmes/guardrail/risk-classifier.d.ts +15 -9
  143. package/dist/holmes/guardrail/risk-classifier.js +228 -16
  144. package/dist/holmes/guardrail/risk-gate.d.ts +2 -8
  145. package/dist/holmes/guardrail/risk-gate.js +7 -34
  146. package/dist/holmes/guardrail/risk-types.d.ts +10 -0
  147. package/dist/holmes/guardrail/run-plan-scope.js +3 -1
  148. package/dist/holmes/guardrail/run-refusals.js +24 -8
  149. package/dist/holmes/guardrail/run-stages.d.ts +5 -0
  150. package/dist/holmes/guardrail/run-stages.js +25 -5
  151. package/dist/holmes/guardrail/scope-judgment.js +1 -1
  152. package/dist/holmes/guardrail/shell-words.js +24 -3
  153. package/dist/holmes/guardrail/unresolved-write.d.ts +40 -0
  154. package/dist/holmes/guardrail/unresolved-write.js +556 -0
  155. package/dist/holmes/guardrail/write-target.d.ts +3 -0
  156. package/dist/holmes/guardrail/write-target.js +26 -5
  157. package/dist/holmes/hooks/pre-tool-use.d.ts +116 -1
  158. package/dist/holmes/hooks/pre-tool-use.js +1176 -170
  159. package/dist/holmes/hooks/rtm-refresh-child.d.ts +1 -1
  160. package/dist/holmes/hooks/rtm-refresh-child.js +1 -1
  161. package/dist/holmes/hooks/session-start.js +17 -1
  162. package/dist/holmes/hooks/stop.d.ts +23 -0
  163. package/dist/holmes/hooks/stop.js +86 -33
  164. package/dist/holmes/mcp/approval-adapters.js +3 -1
  165. package/dist/holmes/mcp/approval-commit.js +3 -2
  166. package/dist/holmes/mcp/approval-policy.d.ts +2 -1
  167. package/dist/holmes/mcp/approval-policy.js +3 -1
  168. package/dist/holmes/mcp/handlers/adoption.d.ts +1 -1
  169. package/dist/holmes/mcp/handlers/approval-ask.d.ts +3 -0
  170. package/dist/holmes/mcp/handlers/approval-ask.js +18 -7
  171. package/dist/holmes/mcp/handlers/entity-integration.d.ts +3 -3
  172. package/dist/holmes/mcp/handlers/entity-integration.js +29 -11
  173. package/dist/holmes/mcp/handlers/entity-renumber.d.ts +4 -4
  174. package/dist/holmes/mcp/handlers/entity-renumber.js +29 -11
  175. package/dist/holmes/mcp/handlers/entity-store.d.ts +2 -2
  176. package/dist/holmes/mcp/handlers/entity-store.js +133 -59
  177. package/dist/holmes/mcp/handlers/maintenance-analysis.d.ts +13 -0
  178. package/dist/holmes/mcp/handlers/maintenance-analysis.js +59 -2
  179. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +9 -5
  180. package/dist/holmes/mcp/handlers/operator-inspection.js +79 -16
  181. package/dist/holmes/mcp/handlers/phase-queries.d.ts +1 -1
  182. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +4 -4
  183. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -2
  184. package/dist/holmes/mcp/handlers/review-evidence.js +35 -11
  185. package/dist/holmes/mcp/handlers/review-queries.d.ts +5 -0
  186. package/dist/holmes/mcp/handlers/review-queries.js +8 -1
  187. package/dist/holmes/mcp/handlers/review-verdict.d.ts +3 -0
  188. package/dist/holmes/mcp/handlers/review-verdict.js +10 -3
  189. package/dist/holmes/mcp/handlers/risk-assessment.d.ts +7 -2
  190. package/dist/holmes/mcp/handlers/risk-assessment.js +34 -12
  191. package/dist/holmes/mcp/handlers/runtime-binding-tool.d.ts +2 -2
  192. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +6 -1
  193. package/dist/holmes/mcp/handlers/slice-orchestration.js +14 -1
  194. package/dist/holmes/mcp/handlers/spec-approval.d.ts +15 -3
  195. package/dist/holmes/mcp/handlers/spec-approval.js +32 -5
  196. package/dist/holmes/mcp/handlers/spec-authoring.d.ts +2 -2
  197. package/dist/holmes/mcp/handlers/spec-authoring.js +19 -2
  198. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +11 -38
  199. package/dist/holmes/mcp/handlers/spec-lifecycle.js +441 -94
  200. package/dist/holmes/mcp/handlers/spec-queries.d.ts +2 -2
  201. package/dist/holmes/mcp/handlers/taint-screening.d.ts +1 -1
  202. package/dist/holmes/mcp/handlers/taint-screening.js +2 -2
  203. package/dist/holmes/mcp/handlers/test-execution.d.ts +471 -4
  204. package/dist/holmes/mcp/handlers/test-execution.js +199 -21
  205. package/dist/holmes/mcp/handlers/workspace-queries.d.ts +2 -2
  206. package/dist/holmes/mcp/handlers.d.ts +557 -82
  207. package/dist/holmes/mcp/handlers.js +74 -23
  208. package/dist/holmes/mcp/harness-attestation.d.ts +78 -5
  209. package/dist/holmes/mcp/harness-attestation.js +325 -53
  210. package/dist/holmes/mcp/maintenance-analyze.d.ts +6 -1
  211. package/dist/holmes/mcp/maintenance-analyze.js +13 -11
  212. package/dist/holmes/mcp/maintenance-evidence.d.ts +9 -0
  213. package/dist/holmes/mcp/maintenance-evidence.js +35 -3
  214. package/dist/holmes/mcp/requirement-triage-evidence.js +22 -13
  215. package/dist/holmes/mcp/server-staleness.js +1 -1
  216. package/dist/holmes/mcp/server.js +9 -8
  217. package/dist/holmes/mcp/spec-id-guard.js +1 -1
  218. package/dist/holmes/mcp/tool-schemas.d.ts +13 -0
  219. package/dist/holmes/mcp/tool-schemas.js +42 -9
  220. package/dist/holmes/project/act-root.d.ts +19 -0
  221. package/dist/holmes/project/act-root.js +100 -0
  222. package/dist/holmes/project/baseline.d.ts +15 -2
  223. package/dist/holmes/project/baseline.js +14 -8
  224. package/dist/holmes/project/bounded-group.d.ts +47 -0
  225. package/dist/holmes/project/bounded-group.js +140 -0
  226. package/dist/holmes/project/bounded-io.d.ts +51 -2
  227. package/dist/holmes/project/bounded-io.js +140 -6
  228. package/dist/holmes/project/change-source.d.ts +4 -0
  229. package/dist/holmes/project/change-source.js +14 -6
  230. package/dist/holmes/project/instance-id.d.ts +10 -0
  231. package/dist/holmes/project/instance-id.js +233 -0
  232. package/dist/holmes/project/machine-identity.d.ts +25 -0
  233. package/dist/holmes/project/machine-identity.js +133 -0
  234. package/dist/holmes/project/owned-lock.d.ts +84 -0
  235. package/dist/holmes/project/owned-lock.js +263 -0
  236. package/dist/holmes/project/plain-lock-fs.d.ts +2 -0
  237. package/dist/holmes/project/plain-lock-fs.js +126 -0
  238. package/dist/holmes/project/request-lock.d.ts +85 -0
  239. package/dist/holmes/project/request-lock.js +459 -0
  240. package/dist/holmes/project/root.d.ts +12 -4
  241. package/dist/holmes/project/root.js +29 -8
  242. package/dist/holmes/project/run-records.d.ts +19 -0
  243. package/dist/holmes/project/run-records.js +94 -12
  244. package/dist/holmes/project/screen-text.d.ts +94 -0
  245. package/dist/holmes/project/screen-text.js +763 -0
  246. package/dist/holmes/project/spend-lock.d.ts +82 -0
  247. package/dist/holmes/project/spend-lock.js +413 -0
  248. package/dist/holmes/refresh/freshness-coordinator.d.ts +1 -1
  249. package/dist/holmes/refresh/freshness-coordinator.js +1 -1
  250. package/dist/holmes/review/condition-hunk-replay.js +4 -2
  251. package/dist/holmes/review/confidence-calibration.d.ts +1 -1
  252. package/dist/holmes/review/confidence-calibration.js +1 -1
  253. package/dist/holmes/review/content-verify.js +1 -1
  254. package/dist/holmes/review/evidence-mode.d.ts +21 -0
  255. package/dist/holmes/review/evidence-mode.js +33 -0
  256. package/dist/holmes/review/head-worktree.d.ts +55 -0
  257. package/dist/holmes/review/head-worktree.js +329 -0
  258. package/dist/holmes/review/hop-ablation.d.ts +4 -4
  259. package/dist/holmes/review/hop-ablation.js +5 -5
  260. package/dist/holmes/review/mrp.js +13 -3
  261. package/dist/holmes/review/point-in-time-replay.js +12 -3
  262. package/dist/holmes/review/rank-diagnosis.d.ts +2 -2
  263. package/dist/holmes/review/rank-diagnosis.js +1 -1
  264. package/dist/holmes/review/replay-corpus.d.ts +10 -4
  265. package/dist/holmes/review/replay-corpus.js +25 -9
  266. package/dist/holmes/review/requirement-triage.js +2 -2
  267. package/dist/holmes/review/run-provenance.d.ts +45 -0
  268. package/dist/holmes/review/run-provenance.js +314 -0
  269. package/dist/holmes/review/semantic-arm.d.ts +3 -3
  270. package/dist/holmes/review/semantic-arm.js +3 -3
  271. package/dist/holmes/review/test-evidence.d.ts +174 -0
  272. package/dist/holmes/review/test-evidence.js +330 -2
  273. package/dist/holmes/review/test-outcomes.js +3 -1
  274. package/dist/holmes/review/test-reports.d.ts +94 -0
  275. package/dist/holmes/review/test-reports.js +382 -0
  276. package/dist/holmes/review/test-runner.d.ts +180 -58
  277. package/dist/holmes/review/test-runner.js +560 -324
  278. package/dist/holmes/review/test-selection-breadth.js +2 -2
  279. package/dist/holmes/review/test-units.d.ts +159 -0
  280. package/dist/holmes/review/test-units.js +814 -0
  281. package/dist/holmes/review/verdicts.d.ts +105 -8
  282. package/dist/holmes/review/verdicts.js +640 -36
  283. package/dist/holmes/rtm/anchor-census.d.ts +9 -0
  284. package/dist/holmes/rtm/anchor-census.js +151 -0
  285. package/dist/holmes/rtm/anchor-ids.d.ts +25 -1
  286. package/dist/holmes/rtm/anchor-ids.js +45 -2
  287. package/dist/holmes/rtm/comment-ranges.d.ts +2 -0
  288. package/dist/holmes/rtm/comment-ranges.js +104 -0
  289. package/dist/holmes/rtm/counted-tests.d.ts +1 -0
  290. package/dist/holmes/rtm/counted-tests.js +63 -0
  291. package/dist/holmes/rtm/impact-advisory.d.ts +1 -1
  292. package/dist/holmes/rtm/known-defects.js +1 -1
  293. package/dist/holmes/rtm/localize.js +1 -1
  294. package/dist/holmes/rtm/taint-benchmark.d.ts +1 -1
  295. package/dist/holmes/rtm/taint-vocabulary.d.ts +1 -1
  296. package/dist/holmes/rtm/test-scope.d.ts +31 -0
  297. package/dist/holmes/rtm/test-scope.js +166 -5
  298. package/dist/holmes/rtm/trace-gaps.js +1 -1
  299. package/dist/holmes/runtime/dispatch.d.ts +10 -0
  300. package/dist/holmes/runtime/dispatch.js +12 -1
  301. package/dist/holmes/semantic/cloud-usage.d.ts +1 -1
  302. package/dist/holmes/semantic/cloud-usage.js +1 -1
  303. package/dist/holmes/semantic/unreadable-paths.d.ts +1 -1
  304. package/dist/holmes/semantic/unreadable-paths.js +1 -1
  305. package/dist/holmes/spec/approval-blockers.js +1 -1
  306. package/dist/holmes/spec/entity-store.d.ts +6 -1
  307. package/dist/holmes/spec/entity-store.js +16 -2
  308. package/dist/holmes/spec/entity-transaction.d.ts +7 -2
  309. package/dist/holmes/spec/entity-transaction.js +87 -170
  310. package/dist/holmes/spec/spec-store.d.ts +12 -6
  311. package/dist/holmes/spec/spec-store.js +4 -2
  312. package/dist/holmes/spec/spec-types.js +1 -1
  313. package/dist/holmes/spec/succession-guard.d.ts +56 -0
  314. package/dist/holmes/spec/succession-guard.js +187 -0
  315. package/dist/holmes/spec/succession.d.ts +70 -0
  316. package/dist/holmes/spec/succession.js +171 -0
  317. package/dist/holmes/spec/transition-policy.d.ts +2 -2
  318. package/docs/install-guide.md +9 -3
  319. package/docs/language-support.md +78 -0
  320. package/package.json +4 -3
  321. package/playbooks/author-slice/PLAYBOOK.md +1 -1
  322. package/playbooks/promote-slice/PLAYBOOK.md +5 -1
  323. package/playbooks/publish/PLAYBOOK.md +47 -34
  324. package/dist/holmes/review/manual-baseline.d.ts +0 -209
  325. package/dist/holmes/review/manual-baseline.js +0 -2847
@@ -33,17 +33,23 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DEFAULT_SPECS_DIR = void 0;
36
+ exports.anchorMoveOnly = exports.DEFAULT_SPECS_DIR = void 0;
37
37
  exports.resolveRmSignals = resolveRmSignals;
38
38
  exports.resolveStagedStore = resolveStagedStore;
39
39
  exports.readApprovalFromEnv = readApprovalFromEnv;
40
40
  exports.sedInPlaceFiles = sedInPlaceFiles;
41
+ exports.lockRecoverAct = lockRecoverAct;
42
+ exports.lockRecoverAdvisory = lockRecoverAdvisory;
41
43
  exports.hookOutputFor = hookOutputFor;
42
44
  exports.authorityMention = authorityMention;
43
45
  exports.readOnlySearch = readOnlySearch;
44
46
  exports.psShowsEnvironment = psShowsEnvironment;
45
47
  exports.agentCliLaunch = agentCliLaunch;
48
+ exports.agentLaunchSegments = agentLaunchSegments;
49
+ exports.hereDocWord = hereDocWord;
50
+ exports.scanShell = scanShell;
46
51
  exports.dumpsEnvInCommandPosition = dumpsEnvInCommandPosition;
52
+ exports.patchMarked = patchMarked;
47
53
  exports.ledgerSummaryOf = ledgerSummaryOf;
48
54
  exports.normalizeHookInput = normalizeHookInput;
49
55
  exports.preEditEvidenceGate = preEditEvidenceGate;
@@ -51,9 +57,12 @@ exports.decideOnGateError = decideOnGateError;
51
57
  exports.isGovernedProject = isGovernedProject;
52
58
  exports.gateErrorDecision = gateErrorDecision;
53
59
  exports.wiredSpecsDir = wiredSpecsDir;
60
+ exports.settleVerdict = settleVerdict;
61
+ exports.settleOnMainThread = settleOnMainThread;
62
+ exports.auditApprovalFor = auditApprovalFor;
54
63
  exports.evaluateHook = evaluateHook;
55
64
  exports.readSpecsSync = readSpecsSync;
56
- // @implements A-SPEC-476.7, A-SPEC-226.3, A-SPEC-774.28, A-SPEC-747.4, A-SPEC-747.7, A-SPEC-774.23, A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1, A-SPEC-747.3, A-SPEC-774.26, A-SPEC-163.8, A-SPEC-790, A-SPEC-790.2, A-SPEC-790.7, A-SPEC-790.8, A-SPEC-792.5
65
+ // @implements A-SPEC-333.9, A-SPEC-794.57, A-SPEC-794.55, A-SPEC-794.54, A-SPEC-794.53, A-SPEC-794.52, A-SPEC-794.49, A-SPEC-222.12, A-SPEC-222.13, A-SPEC-476.7, A-SPEC-226.3, A-SPEC-774.28, A-SPEC-747.4, A-SPEC-747.7, A-SPEC-774.23, A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1, A-SPEC-747.3, A-SPEC-774.26, A-SPEC-163.8, A-SPEC-790, A-SPEC-790.2, A-SPEC-790.7, A-SPEC-790.8, A-SPEC-792.5, A-SPEC-245.9, A-SPEC-245.15, A-SPEC-245.17
57
66
  const powershell_shell_1 = require("../guardrail/powershell-shell");
58
67
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
59
68
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
@@ -82,6 +91,8 @@ const run_mode_1 = require("../governance/run-mode");
82
91
  const classification_mode_1 = require("../guardrail/classification-mode");
83
92
  const scope_refusal_memory_1 = require("../guardrail/scope-refusal-memory");
84
93
  const agent_launch_policy_1 = require("../guardrail/agent-launch-policy");
94
+ const line_continuation_1 = require("../guardrail/line-continuation");
95
+ const unresolved_write_1 = require("../guardrail/unresolved-write");
85
96
  const risk_classifier_1 = require("../guardrail/risk-classifier");
86
97
  const refusal_codes_1 = require("../guardrail/refusal-codes");
87
98
  const run_refusals_1 = require("../guardrail/run-refusals");
@@ -102,7 +113,6 @@ const governance_history_1 = require("../guardrail/governance-history");
102
113
  const rtm_check_1 = require("../rtm/rtm-check");
103
114
  const ledger_store_1 = require("../governance/ledger-store");
104
115
  const provenance_chain_1 = require("../governance/provenance-chain");
105
- const ledger_lock_1 = require("../governance/ledger-lock");
106
116
  // @implements A-SPEC-574.3 — the caller owns the store and hands the chain the question.
107
117
  const ledger_store_2 = require("../governance/ledger-store");
108
118
  const risk_gate_1 = require("../guardrail/risk-gate");
@@ -112,7 +122,10 @@ const linear_match_1 = require("../guardrail/linear-match");
112
122
  const approval_grants_1 = require("../governance/approval-grants");
113
123
  const approval_blockers_1 = require("../spec/approval-blockers");
114
124
  const impact_gate_1 = require("../guardrail/impact-gate");
125
+ const advisory_line_1 = require("../guardrail/advisory-line");
126
+ const heartbeat_1 = require("./heartbeat");
115
127
  const bounded_io_1 = require("../project/bounded-io");
128
+ const flags_1 = require("../cli/flags"); // @implements A-SPEC-245.18 — the CLI's own flag reading, one source
116
129
  // Resolve per-rm-target git facts (H1 git-aware guardrail): is each recursive-rm target a
117
130
  // regenerable build artifact (gitignored), version-controlled source (tracked), or escaping the
118
131
  // project? This is the I/O half — the classifier stays pure and merely consumes these signals.
@@ -187,27 +200,41 @@ function resolveStagedStore(command, projectRoot, specsDir) {
187
200
  return undefined;
188
201
  if (!fs.existsSync(specsDir))
189
202
  return undefined;
190
- 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)() });
203
+ // the repository question first (one bounded child); the change list itself is computed without `git status`
204
+ const r = (0, bounded_io_1.gitOnce)(projectRoot, ['--no-optional-locks', '-c', 'core.fsmonitor=false', 'rev-parse', '--show-toplevel'], 'repo', { env: (0, root_1.cleanSubprocessEnv)() });
191
205
  const answer = (0, bounded_io_1.gitAnswerOf)(r, projectRoot);
192
206
  if (answer === 'no-repository')
193
207
  return undefined;
208
+ // @implements A-SPEC-222.12 (N1) — and another replica's ledger file (any provenance*.jsonl but this writer's own)
209
+ const ledgerDir = path.join(projectRoot, '.ax', 'ledger');
194
210
  if (answer !== 'answered')
195
- return { specsDir, unanswered: true };
196
- let tracked = false;
197
- let untracked = false;
198
- const entries = String(r.stdout).split('\0');
199
- for (let i = 0; i < entries.length; i++) {
200
- const e = entries[i];
201
- if (e.length < 3)
202
- continue;
203
- if (e[0] === 'R' || e[0] === 'C')
204
- i++; // a rename or copy carries its source path as the next entry
205
- if (e.startsWith('??'))
206
- untracked = true;
207
- else if (e[1] !== ' ')
208
- tracked = true;
209
- }
210
- return { specsDir, tracked, untracked };
211
+ return { specsDir, unanswered: true, ledgerDir };
212
+ // @implements A-SPEC-792.32 — `git status` re-hashes a racily clean file through its clean filter, which ran the
213
+ // agent's filter command inside this hook (measured 2026-10-26); worktreeChanges compares bytes without git's filters
214
+ let changes;
215
+ let foreign = [];
216
+ try {
217
+ const { worktreeChanges } = require('../governance/spec-seam');
218
+ changes = worktreeChanges(projectRoot, [path.relative(projectRoot, specsDir)]);
219
+ if (fs.existsSync(ledgerDir)) {
220
+ let own = null;
221
+ try {
222
+ own = new ledger_store_1.FileLedgerStore(ledgerDir).replicaId();
223
+ }
224
+ catch {
225
+ own = null;
226
+ }
227
+ foreign = worktreeChanges(projectRoot, [path.relative(projectRoot, ledgerDir)]).filter((c) => {
228
+ const m = /^provenance(?:\.([^/]+))?\.jsonl$/i.exec(path.posix.basename(c.path));
229
+ return m !== null && !(own !== null && m[1] === own);
230
+ });
231
+ }
232
+ }
233
+ catch {
234
+ return { specsDir, unanswered: true, ledgerDir };
235
+ }
236
+ return { specsDir, tracked: changes.some((c) => !c.untracked), untracked: changes.some((c) => c.untracked),
237
+ ledgerDir, foreignLedger: { tracked: foreign.some((c) => !c.untracked), untracked: foreign.some((c) => c.untracked) } };
211
238
  }
212
239
  /**
213
240
  * @implements A-SPEC-476.3 — what a file tool's write does to the caps in `<root>/ax.config.json`: `null` leaves both as
@@ -647,6 +674,138 @@ function wrappedServerWord(normalized) {
647
674
  }
648
675
  return false;
649
676
  }
677
+ /**
678
+ * @implements A-SPEC-245.9 (1b-5, item 7) — `holmes-kit lock recover` retires a lock another process may hold: the
679
+ * operator's act. The CLI refuses it from an agent by the environment and the process ancestry, which a process
680
+ * reparented away from the harness escapes, so the gate refuses the command itself. A segment counts when its command
681
+ * word (after env, nohup, time, command, exec, builtin and NAME=value) runs the CLI — `holmes-kit`, `npx [-y]
682
+ * [@holmes-lab/]holmes-kit[@v]`, or `node <…/holmes/cli/index.js | …holmes-kit[.js]>` — and its next words are
683
+ * `lock recover`; a mention as an argument (echo, grep) is not the act.
684
+ */
685
+ function lockRecoverAct(command) {
686
+ // @implements A-SPEC-245.17 (item 1) — read through the gate's own shell reading, as the agent-CLI launch is: segments
687
+ // split on unquoted separators (so `{`, `then`, `do`, `!` lead a segment), quoting removed (joined quotes and
688
+ // backslashes read as the word they make), a -c body, an eval argument, a command substitution and a here-document
689
+ // read as words of a command, an inert text command's arguments (echo, grep …) left as data. By word, not by wrapper:
690
+ // sudo, timeout, nice, time, setsid, screen, tmux, xargs, env options, command -p and the package runners need no
691
+ // list. Named limits: a word made by variable expansion ($H lock recover) and an eval body built at run time — both
692
+ // refused since A-SPEC-245.18 when the command's text names holmes-kit, lock and recover.
693
+ // the reading hands the predicate a word's basename, so index.js finds the segment; the full word is judged below
694
+ // @implements A-SPEC-245.19 (item 2) — the hook is early refusal of the direct forms only; the authority boundary is
695
+ // the CLI's operator judgement (operatorActGuard: the inherited harness marker or the process ancestry). Text that
696
+ // names the act and is handed to a shell, an interpreter or a run-time word is advised on (lockRecoverAdvisory), not
697
+ // refused: it refused commit messages, PR bodies and prose. Named limit: the hook does not read interpreter source,
698
+ // package scripts, aliases or run-time words.
699
+ const segments = agentLaunchSegments(command, 0, { test: (w) => isHolmesKitWord(w) || w === 'index.js' });
700
+ return segments.some(({ words, spans }) => !lockRecoverDataLead(words, spans) && words.some((w, i) => {
701
+ if (!isHolmesKitWord(w))
702
+ return false;
703
+ let j = i + 1;
704
+ while (j < words.length && (words[j].startsWith('-') || isHolmesKitWord(words[j])))
705
+ j++; // npx -p pkg holmes-kit, npm exec pkg --
706
+ if (words[j] !== 'lock')
707
+ return false;
708
+ // @implements A-SPEC-245.18 (item 4) — xargs or parallel fills the arguments at run time
709
+ if (words.slice(0, i).some((p) => /^(?:xargs|parallel)$/.test(baseWord(p))))
710
+ return true;
711
+ // @implements A-SPEC-245.18 (item 2) — the CLI removes flags wherever they stand (parseFlags): judge what is left
712
+ const after = words.slice(j + 1);
713
+ try {
714
+ return (0, flags_1.parseFlags)(after).positionals.includes('recover');
715
+ }
716
+ catch {
717
+ return after.includes('recover');
718
+ }
719
+ }));
720
+ }
721
+ const baseWord = (w) => w.split(/[\\/]/).pop() ?? w;
722
+ /**
723
+ * The CLI as a word: its name, a path to it, its .js/.cmd/.ps1/.exe shim, the package, each with an optional
724
+ * `@<version|tag>` (the shell reading hands the predicate `holmes-kit@0.40.0`, a basename — A-SPEC-245.18 item 1); its
725
+ * index.js under holmes/cli, or a relative one (`cd …/cli && node index.js`); the text after `=` and a leading `!`
726
+ * (`git -c alias.x='!holmes-kit …'`).
727
+ */
728
+ const HOLMES_KIT_WORD = /^(?:\S*[\/\\])?holmes-kit(?:\.js|\.cmd|\.ps1|\.exe)?(?:@[^\s\/\\]+)?$|(?:^|[\/\\])holmes[\/\\]cli[\/\\]index\.js$|^(?:\.[\/\\])?index\.js$/i;
729
+ function isHolmesKitWord(w) {
730
+ // @implements A-SPEC-245.19 (item 2) — after a sed delimiter too (`s|x|holmes-kit …|e`); A-SPEC-245.20 — `;` as well
731
+ const cut = Math.max(...['=', '|', '#', ',', ':', ';'].map((c) => w.lastIndexOf(c)));
732
+ return HOLMES_KIT_WORD.test(w.slice(cut + 1).replace(/^!/, ''));
733
+ }
734
+ /**
735
+ * @implements A-SPEC-245.18 (item 3) — a segment whose lead takes the text as data: jest (directly, through npx, or by a
736
+ * path to it), tee, and sed whose script carries no GNU execute (the `e` command, the `s///e` flag).
737
+ */
738
+ function lockRecoverDataLead(words, spans) {
739
+ let i = 0;
740
+ while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))
741
+ i++;
742
+ if (words[i] === 'npx') {
743
+ // @implements A-SPEC-245.19 (item 2) — a -p/--package value is not the command (a -c/--call string's words follow as
744
+ // the command, so it needs no rule of its own: A-SPEC-245.20 removed the duplicate)
745
+ i++;
746
+ while (words[i]?.startsWith('-'))
747
+ i += /^(?:-p|--package)$/.test(words[i]) ? 2 : 1;
748
+ }
749
+ const lead = baseWord(words[i] ?? '');
750
+ if (lead === 'jest' || lead === 'tee')
751
+ return true;
752
+ if (lead !== 'sed')
753
+ return false;
754
+ // @implements A-SPEC-245.23 (item 1) — a script given through --expression= or attached to -e is read as a script
755
+ // @implements A-SPEC-245.24 (items 2, 6d) — the words of one quoted span are one script again (the shell reading split a
756
+ // pattern address at its spaces), and GNU's abbreviated --expression spellings are stripped like the full one
757
+ const script = sedScriptWords(words.slice(i + 1), (spans ?? []).slice(i + 1))
758
+ // A-SPEC-245.25 (item 2, N2) — up to the bundle's first e only: `-e'e …'` and `-ne'e …'` keep the script's own e
759
+ .map((w) => w.replace(/^(?:--e[a-z]*=|-[a-zA-Z]*?e)/, '')).join(' ');
760
+ // @implements A-SPEC-245.19 (item 2) — the s command's flags after its third delimiter, whatever the delimiter
761
+ // @implements A-SPEC-245.24 (items 2, 3) — the e command is recognised by the character before it — an address's last
762
+ // character (a delimiter, a digit, $, !, ~, `,`, an I or M flag) or a command's start — with no nested quantifier, so
763
+ // the judgement is linear (245.23's address class took 2.7 s on 36 slashes). Measured against the 245.19 build by
764
+ // the differential corpus (sed-early-refusal-corpus.test.ts): no input it refused early passes here.
765
+ // Named limits, refused by the CLI and outside this early refusal: a custom-delimited address, GNU +N ranges, a script
766
+ // assembled at run time (one s command writing the command, another running it). It can refuse sed data that names
767
+ // the act: an input file named e, an i/a text of e, a pattern of " e ", a path ending in M or I before e.
768
+ // A-SPEC-245.25 (item 2) — 245.19's second alternative ORed back unchanged (it covered a command word attached to e:
769
+ // the 245.22-245.24 rewrites each fell below the 245.19 baseline); the s command takes ASCII punctuation delimiters
770
+ // only (item 4: many non-ASCII delimiters made the alternative quadratic). Named limits, refused by the CLI: no address
771
+ // or a line-number address with an attached command, `1e{ …;}`, an absolute path after e, an alphanumeric or
772
+ // non-ASCII delimiter. A-SPEC-245.26 (item 3) — and, passing since 245.19: the CLI word attached to a pattern
773
+ // address's e; a space or ! between the address and an attached command; an s command attached to an address; an s
774
+ // delimiter (@ ! % _ ~ ^) the CLI-word reading does not cut at. The early refusal's direction waits for the owner.
775
+ // A-SPEC-245.26 (item 2) — the same alternative in a form that does not backtrack quadratically on a long run of e
776
+ // (the review's equivalent: an e somewhere in the alphanumeric run after the slash, then the run to its end)
777
+ return !/(?:^|[\s;{}\/0-9$!~,IM])e(?:\s|$)|\/(?=[A-Za-z0-9]*e)[A-Za-z0-9]*(?:\s|$|;)|(?:^|[\s;{}])s([!-\/:-@[\]^_`{-~])(?:(?!\1).)*\1(?:(?!\1).)*\1[A-Za-z0-9]*e/.test(script);
778
+ }
779
+ /** @implements A-SPEC-245.24 (item 2) — consecutive words of one quoted span joined back with a space. */
780
+ function sedScriptWords(words, spans) {
781
+ const out = [];
782
+ words.forEach((w, k) => {
783
+ if (k > 0 && spans[k] !== undefined && spans[k] >= 0 && spans[k] === spans[k - 1])
784
+ out[out.length - 1] += ` ${w}`;
785
+ else
786
+ out.push(w);
787
+ });
788
+ return out;
789
+ }
790
+ /** A shell that reads its program from a pipe, a here-string or a process substitution. */
791
+ const SHELL_FED = /(?:[|(]|<<<)\s*(?:\S+\s+)*?(?:\S*\/)?(?:sh|bash|zsh|dash|ksh|mksh|ash|fish)\b|(?:^|[\s\/;&|(])(?:sh|bash|zsh|dash|ksh|mksh|ash|fish)\b[^|;&\n]*<<</;
792
+ /** A command word built at run time: an expansion or a substitution where a command starts. */
793
+ const RUNTIME_COMMAND_WORD = /(?:^|[;&|\n({]|\b(?:then|do|else|sudo|env|nohup|time|command|exec)\s)\s*["']?(?:\$[({A-Za-z_]|`)/;
794
+ /**
795
+ * @implements A-SPEC-245.19 (item 2) — the advisory an allowed Bash command carries when its text names the act and
796
+ * hands it to something that runs text: the CLI will refuse it from a session.
797
+ */
798
+ function lockRecoverAdvisory(command) {
799
+ return lockRecoverTextRuns(command)
800
+ ? '[Holmes-Kit] advisory: this command names holmes-kit lock recover and hands text to a shell or an interpreter — if it runs the recovery, the CLI refuses it from an agent session; the operator runs it from their own terminal (A-SPEC-245.19).'
801
+ : null;
802
+ }
803
+ function lockRecoverTextRuns(command) {
804
+ const text = command.replace(/["'\\]/g, '');
805
+ if (!/holmes-kit/i.test(text) || !/\block\b/.test(text) || !/\brecover\b/.test(text))
806
+ return false;
807
+ return interpreterSpawns(command) || SHELL_FED.test(command) || RUNTIME_COMMAND_WORD.test(command);
808
+ }
650
809
  function startsHolmesServer(command) {
651
810
  command = (0, shell_argument_roles_1.shellArgumentRoles)(command).serverText;
652
811
  if (SERVER_RUNNERS.some((t) => t.test(command)))
@@ -668,10 +827,15 @@ function startsHolmesServer(command) {
668
827
  * Round-1 A-SPEC-718's approval_commit exception is now the rule for every tool.
669
828
  */
670
829
  function hookOutputFor(_toolName, out) {
671
- const { permissionDecision, permissionDecisionReason, ...rest } = out;
830
+ // @implements A-SPEC-245.23 (item 3) — a verdict's `refusal` is the deny site's own code; the harness never sees the field
831
+ // A-SPEC-245.25 — `request` is the run path's, never the harness's
832
+ const { permissionDecision, permissionDecisionReason, refusal, request: _request, ...rest } = out;
672
833
  if (permissionDecision === 'deny') {
673
834
  // @implements A-SPEC-777 — every deny carries its refusal code as one machine-readable line.
674
- return { hookEventName: 'PreToolUse', ...rest, permissionDecision, permissionDecisionReason: (0, refusal_codes_1.withRefusalLine)(permissionDecisionReason) };
835
+ // A-SPEC-245.26 (4a) — a site that carries `refusal` but leaves it unset names no registered code: unclassified,
836
+ // never the reason's words
837
+ const code = 'refusal' in out ? (typeof refusal === 'string' ? refusal : '') : undefined;
838
+ return { hookEventName: 'PreToolUse', ...rest, permissionDecision, permissionDecisionReason: (0, refusal_codes_1.withRefusalLine)(permissionDecisionReason, code) };
675
839
  }
676
840
  const context = [typeof rest.additionalContext === 'string' ? rest.additionalContext : '', permissionDecisionReason ?? ''].filter((t) => t !== '').join('\n');
677
841
  const { additionalContext: _c, ...others } = rest;
@@ -992,17 +1156,102 @@ function agentCliLaunch(command) {
992
1156
  }
993
1157
  /** @implements A-SPEC-774.9 — an interpreter that spawns an agent by name (the 774.2 rule, kept apart for reuse). */
994
1158
  function interpreterSpawnsAgent(command) {
995
- return /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b/.test(command)
996
- && /\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|subprocess|system|popen|Popen)\b/.test(command)
1159
+ return interpreterSpawns(command)
997
1160
  && /['"](?:claude|codex|gemini|agy|aider|cursor-agent|opencode|goose|qwen)(?:\.exe|\.cmd)?['"]/.test(command);
998
1161
  }
1162
+ /** @implements A-SPEC-245.18 (item 4) — an interpreter with a spawn call: the half of 774.9's rule the lock-recover judgement reuses. */
1163
+ function interpreterSpawns(command) {
1164
+ return /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b/.test(command)
1165
+ && /\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|subprocess|system|popen|Popen)\b/.test(command);
1166
+ }
1167
+ /**
1168
+ * @implements A-SPEC-774.67 — exactly the product's report command: the Holmes CLI (as installed, through npx, or the
1169
+ * package's bin under node), `report`, then only `--message <word>`, `--harness <harness>` and `--open`, each at most once.
1170
+ */
1171
+ function isHolmesReport(rawWords, rawSpans = [], spanQuote = []) {
1172
+ // @implements A-SPEC-774.68 — a word holding $ or a backtick is never text here: it may be a command substitution
1173
+ // @implements A-SPEC-774.69 — unless its quoting keeps it text: wholly single-quoted, or wholly double-quoted with
1174
+ // neither $( nor a backtick (`'costs $5'`, `"home $HOME"`; review 18:43, F1.2-e)
1175
+ const text = (w, k) => {
1176
+ if (!/[$`]/.test(w))
1177
+ return true;
1178
+ const q = rawSpans[k] !== undefined && rawSpans[k] >= 0 ? spanQuote[rawSpans[k]] : undefined;
1179
+ return q === "'" || (q === '"' && !/\$\(|`/.test(w));
1180
+ };
1181
+ if (!rawWords.every(text))
1182
+ return false;
1183
+ // one quoted value is one word (`--message "ART-4 zero"`): words sharing a quoted span are joined
1184
+ const words = [];
1185
+ for (let k = 0; k < rawWords.length; k++) {
1186
+ if (k > 0 && rawSpans[k] !== undefined && rawSpans[k] >= 0 && rawSpans[k] === rawSpans[k - 1])
1187
+ words[words.length - 1] += ` ${rawWords[k]}`;
1188
+ else
1189
+ words.push(rawWords[k]);
1190
+ }
1191
+ let i = 0;
1192
+ if (words[0] === 'npx') {
1193
+ i = 1;
1194
+ if (words[i] === '-y' || words[i] === '--yes')
1195
+ i++;
1196
+ }
1197
+ const prog = words[i] ?? '';
1198
+ const isCli = prog === 'holmes-kit' || (words[0] === 'npx' && /^@holmes-lab\/holmes-kit(?:@[\w.-]+)?$/.test(prog));
1199
+ const isBin = words[0] === 'node' && i === 0 && /(?:^|\/)bin\/holmes-kit\.js$/.test(words[1] ?? '');
1200
+ if (isBin)
1201
+ i = 1;
1202
+ else if (!isCli)
1203
+ return false;
1204
+ if (words[i + 1] !== 'report')
1205
+ return false;
1206
+ const seen = new Set();
1207
+ for (let k = i + 2; k < words.length; k++) {
1208
+ const w = words[k];
1209
+ if (seen.has(w))
1210
+ return false;
1211
+ seen.add(w);
1212
+ if (w === '--open')
1213
+ continue;
1214
+ if (w === '--message' && k + 1 < words.length) {
1215
+ k++;
1216
+ continue;
1217
+ }
1218
+ if (w === '--harness' && /^(?:claude|codex|agy|antigravity)$/.test(words[k + 1] ?? '')) {
1219
+ k++;
1220
+ continue;
1221
+ }
1222
+ return false;
1223
+ }
1224
+ return true;
1225
+ }
999
1226
  /** The words of every segment that launches an agent CLI (A-SPEC-774.5 §1), quote-aware. */
1000
1227
  /**
1001
1228
  * @implements A-SPEC-774.26 — with each word, the quoted span it came from (-1: unquoted or mixed), so the option check
1002
1229
  * can tell a quoted prompt (`-p "… cut -d= …"`) from options, and a quoted program (`tmux new -d 'claude …'`) from both.
1003
1230
  */
1004
- function agentLaunchSegments(command) {
1231
+ // @implements A-SPEC-774.88 — the program pattern is a parameter: the test runtime's kill seam reads shell strings for
1232
+ // kill, pkill and killall with the same word scanner (the default, and so the code gate, is unchanged)
1233
+ function agentLaunchSegments(command, depth = 0, program = AGENT_CLI) {
1005
1234
  const found = [];
1235
+ const scan = scanShell(command); // @implements A-SPEC-774.75 — computed once, read by the substitution scan too
1236
+ // @implements A-SPEC-774.68 — a command substitution runs whatever quoting surrounds it: its body is a command too
1237
+ const subs = substitutionBodies(command, scan);
1238
+ const nested = depth < 8 ? subs.bodies.flatMap((b) => agentLaunchSegments(b, depth + 1, program)) : [];
1239
+ // @implements A-SPEC-774.69 — what the limits leave unread is judged a launch, with an option no list allows (F1.2-b)
1240
+ if (subs.overflow || (depth >= 8 && subs.bodies.length > 0))
1241
+ nested.push({ words: ['codex', '--holmes-unjudged-substitutions'], spans: [-1, -1] });
1242
+ // @implements A-SPEC-774.72 — the one scanner; a here-document fed to anything but an inert text command (`bash <<'EOF'`)
1243
+ // runs its lines, which are judged as commands; an inert one's body (`cat <<'EOF'`) is data (A-SPEC-774.69)
1244
+ // @implements A-SPEC-774.75 — unless it never ends: an unterminated body is judged as commands under any lead, and
1245
+ // here-documents nested past depth 8 are judged a launch, as substitutions are
1246
+ for (const h of scan.docs) {
1247
+ if (INERT_TEXT_COMMANDS.has(h.lead) && h.terminated)
1248
+ continue;
1249
+ if (depth >= 8) {
1250
+ nested.push({ words: ['codex', '--holmes-unjudged-here-documents'], spans: [-1, -1] });
1251
+ break;
1252
+ }
1253
+ nested.push(...agentLaunchSegments(command.slice(h.bodyStart, h.bodyEnd), depth + 1, program));
1254
+ }
1006
1255
  // @implements A-SPEC-774.5 §1 — by WORD, not by wrapper. The wrapper list (774.2) was walked through by `tmux new -d
1007
1256
  // '…'`, `script -q /dev/null …` and `watch …` (supervisor probe, 2026-10-17): launchers have no end. Quoting is
1008
1257
  // removed first, so a program inside a quoted argument is read as words of the same segment; the exceptions are a
@@ -1012,44 +1261,74 @@ function agentLaunchSegments(command) {
1012
1261
  const segs = [];
1013
1262
  let cur = '';
1014
1263
  let curSpans = [];
1015
- let quote = null;
1016
1264
  let span = -1;
1017
1265
  let spans = 0;
1266
+ let open = false;
1267
+ let ansi = false; // the open span is $'…'
1268
+ let undecodable = false;
1269
+ const spanQuote = []; // @implements A-SPEC-774.69 — the quote kind of each quoted span, for the report exemption
1018
1270
  const add = (s, at) => { for (const c of s) {
1019
1271
  cur += c;
1020
1272
  curSpans.push(at);
1021
1273
  } };
1274
+ const cut = () => { segs.push({ text: cur, spanOf: curSpans }); cur = ''; curSpans = []; };
1275
+ const { kind } = scan;
1022
1276
  for (let k = 0; k < command.length; k++) {
1023
1277
  const ch = command[k];
1024
- if (quote) {
1025
- if (ch === quote)
1026
- quote = null;
1027
- else if (ch === '\\' && quote === '"') {
1028
- add(command[++k] ?? '', span);
1029
- continue;
1278
+ const t = kind[k];
1279
+ // @implements A-SPEC-774.72 — quoting from the scan: a delimiter opens or closes a span (quoting joins, as the shell
1280
+ // does: cl'aude' is claude); $'…' is a single-quote span with its escapes decoded; comments and bodies are dropped
1281
+ if (t === 7 /* Ch.Delim */) {
1282
+ if (!open) {
1283
+ open = true;
1284
+ span = spans++;
1285
+ spanQuote[span] = ch === '"' ? '"' : "'";
1286
+ ansi = ch === '$';
1287
+ if (ansi)
1288
+ k++;
1030
1289
  }
1031
1290
  else
1032
- add(ch, span);
1291
+ open = false;
1033
1292
  continue;
1034
1293
  }
1035
- if (ch === '\\') {
1036
- add(command[++k] ?? '', -1);
1294
+ // @implements A-SPEC-774.75 — inside $'…' an escape is decoded as bash 5 decodes it (`\x63odex` is codex); one that
1295
+ // names no character is judged a launch
1296
+ if (t === 8 /* Ch.Escape */ && open && ansi) {
1297
+ const d = ansiEscape(command, k + 1);
1298
+ if (d === null) {
1299
+ undecodable = true;
1300
+ k++;
1301
+ continue;
1302
+ }
1303
+ add(d.text, span);
1304
+ k += d.length;
1305
+ continue;
1306
+ }
1307
+ if (t === 8 /* Ch.Escape */) {
1308
+ const next = command[++k] ?? '';
1309
+ add(next, open ? span : -1);
1310
+ continue;
1311
+ }
1312
+ if (t === 1 /* Ch.Single */ || t === 2 /* Ch.Double */ || t === 3 /* Ch.Ansi */) {
1313
+ add(ch, span);
1037
1314
  continue;
1038
1315
  }
1039
- if (ch === "'" || ch === '"') {
1040
- quote = ch;
1041
- span = spans++;
1316
+ if (t === 4 /* Ch.Comment */)
1042
1317
  continue;
1043
- } // quoting joins, as the shell does: cl'aude' is claude
1318
+ if (t === 5 /* Ch.Body */ || t === 6 /* Ch.QuotedBody */) {
1319
+ if (cur !== '')
1320
+ cut();
1321
+ continue;
1322
+ }
1044
1323
  if (/[|;&\n()]/.test(ch)) {
1045
- segs.push({ text: cur, spanOf: curSpans });
1046
- cur = '';
1047
- curSpans = [];
1324
+ cut();
1048
1325
  continue;
1049
1326
  }
1050
1327
  add(ch, -1);
1051
1328
  }
1052
1329
  segs.push({ text: cur, spanOf: curSpans });
1330
+ if (undecodable)
1331
+ nested.push({ words: ['codex', '--holmes-unjudged-escape'], spans: [-1, -1] });
1053
1332
  for (const seg of segs) {
1054
1333
  // A quote of the other kind inside a quoted span stays in the text (`'… "claude -p x"'`); it is not part of a name.
1055
1334
  const rawWords = [];
@@ -1069,10 +1348,33 @@ function agentLaunchSegments(command) {
1069
1348
  continue;
1070
1349
  }
1071
1350
  const s = seg.spanOf[k];
1351
+ // @implements A-SPEC-774.69 — an unquoted ${IFS} or $IFS splits words, as field splitting does (F1.2-c)
1352
+ if (s === -1 && c === '$') {
1353
+ const ifs = /^\$(?:\{IFS\}|IFS(?![A-Za-z0-9_]))/.exec(seg.text.slice(k));
1354
+ if (ifs && seg.spanOf.slice(k, k + ifs[0].length).every((x) => x === -1)) {
1355
+ flush();
1356
+ k += ifs[0].length - 1;
1357
+ continue;
1358
+ }
1359
+ }
1072
1360
  wspan = wspan === null ? s : wspan === s ? s : -1;
1073
1361
  wcur += c;
1074
1362
  }
1075
1363
  flush();
1364
+ // @implements A-SPEC-774.69 — an agent name followed by an expansion runs whatever the expansion holds: the name, then
1365
+ // an option no list allows
1366
+ const AGENT_BEFORE_EXPANSION = (w) => {
1367
+ const at = w.indexOf('$');
1368
+ if (at <= 0)
1369
+ return null;
1370
+ const name = w.slice(0, at);
1371
+ return program.test(name.split(/[\\/]/).pop() ?? name) ? name : null;
1372
+ };
1373
+ for (let r = rawWords.length - 1; r >= 0; r--) {
1374
+ const name = rawWords[r].span === -1 ? AGENT_BEFORE_EXPANSION(rawWords[r].w) : null;
1375
+ if (name !== null)
1376
+ rawWords.splice(r, 1, { w: name, span: -1 }, { w: '--holmes-unjudged-expansion', span: -1 });
1377
+ }
1076
1378
  const words = rawWords.map((r) => r.w);
1077
1379
  const wordSpans = rawWords.map((r) => r.span);
1078
1380
  let i = 0;
@@ -1081,10 +1383,12 @@ function agentLaunchSegments(command) {
1081
1383
  const rest = words.slice(i);
1082
1384
  if (rest.length === 0)
1083
1385
  continue;
1386
+ if (isHolmesReport(rest, wordSpans.slice(i), spanQuote))
1387
+ continue; // @implements A-SPEC-774.67 — the product's own report command
1084
1388
  const base = (w) => w.split(/[\\/]/).pop() ?? w;
1085
1389
  const pkgOf = (w) => (/^(@?[^@]+)/.exec(w) ?? ['', ''])[1];
1086
1390
  // An option value names a program too (`git -c core.pager=claude`), so the text after the last `=` counts.
1087
- const isAgent = (w) => [w, w.slice(w.lastIndexOf('=') + 1)].some((v) => AGENT_CLI.test(base(v)) || AGENT_PACKAGES.has(pkgOf(v)));
1391
+ const isAgent = (w) => [w, w.slice(w.lastIndexOf('=') + 1)].some((v) => program.test(base(v)) || (program === AGENT_CLI && AGENT_PACKAGES.has(pkgOf(v))));
1088
1392
  if (!rest.some(isAgent))
1089
1393
  continue;
1090
1394
  const lead = base(rest[0]);
@@ -1116,7 +1420,263 @@ function agentLaunchSegments(command) {
1116
1420
  continue;
1117
1421
  found.push({ words, spans: wordSpans }); // with the leading NAME=value words: the interactive allowlist judges them (774.11)
1118
1422
  }
1119
- return found;
1423
+ return [...found, ...nested];
1424
+ }
1425
+ /**
1426
+ * @implements A-SPEC-774.75 — one `$'…'` escape from `at` (the character after the backslash), as bash 5 decodes it: its
1427
+ * text and how many characters it consumed; null when it names no character (above U+10FFFF, a surrogate, `\c` at the end).
1428
+ */
1429
+ function ansiEscape(text, at) {
1430
+ const n = text[at] ?? '';
1431
+ if (n === 'x' || n === 'u' || n === 'U') {
1432
+ const d = ((n === 'x' ? /^[0-9A-Fa-f]{1,2}/ : n === 'u' ? /^[0-9A-Fa-f]{1,4}/ : /^[0-9A-Fa-f]{1,8}/).exec(text.slice(at + 1, at + 9)) ?? [''])[0];
1433
+ if (d === '')
1434
+ return { text: `\\${n}`, length: 1 }; // no digits: as written
1435
+ const code = parseInt(d, 16);
1436
+ if (code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff))
1437
+ return null;
1438
+ return { text: String.fromCodePoint(code), length: 1 + d.length };
1439
+ }
1440
+ if (n >= '0' && n <= '7') {
1441
+ const d = /^[0-7]{1,3}/.exec(text.slice(at, at + 3))[0];
1442
+ return { text: String.fromCharCode(parseInt(d, 8) & 0xff), length: d.length };
1443
+ }
1444
+ if (n === 'c')
1445
+ return at + 1 < text.length && text[at + 1] !== "'" ? { text: String.fromCharCode(text.charCodeAt(at + 1) & 0x1f), length: 2 } : null;
1446
+ const simple = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
1447
+ return { text: simple[n] ?? `\\${n}`, length: 1 };
1448
+ }
1449
+ /**
1450
+ * @implements A-SPEC-774.75 — a here-document's delimiter word from `at` (after `<<`): read to a blank or `;&|<>()`, its
1451
+ * quotes removed; any quoting makes the body quoted (`E"O"F` waits for `EOF`). Null when there is no word or a quote is
1452
+ * left open before the newline.
1453
+ */
1454
+ function hereDocWord(text, at) {
1455
+ let i = at;
1456
+ const strip = text[i] === '-';
1457
+ if (strip)
1458
+ i++;
1459
+ while (text[i] === ' ' || text[i] === '\t')
1460
+ i++;
1461
+ const start = i;
1462
+ let delim = '';
1463
+ let quoted = false;
1464
+ while (i < text.length && !/[\s;&|<>()]/.test(text[i])) {
1465
+ const c = text[i];
1466
+ if (c === "'" || c === '"') {
1467
+ const close = text.indexOf(c, i + 1);
1468
+ const nl = text.indexOf('\n', i + 1);
1469
+ if (close < 0 || (nl >= 0 && nl < close))
1470
+ return null;
1471
+ delim += text.slice(i + 1, close);
1472
+ quoted = true;
1473
+ i = close + 1;
1474
+ continue;
1475
+ }
1476
+ if (c === '\\') {
1477
+ if (i + 1 >= text.length || text[i + 1] === '\n')
1478
+ return null;
1479
+ delim += text[i + 1];
1480
+ quoted = true;
1481
+ i += 2;
1482
+ continue;
1483
+ }
1484
+ delim += c;
1485
+ i++;
1486
+ }
1487
+ return i === start ? null : { delim, quoted, strip, end: i };
1488
+ }
1489
+ /**
1490
+ * @implements A-SPEC-774.72 — the one quote state machine (F1.3-e, f): single quotes, double quotes, `$'…'` with its
1491
+ * backslash escapes, a `#` comment from a word start to the newline, and here-document bodies after the newline that
1492
+ * ends their `<<` line. The substitution scan, the here-document list and the segment lexer all read this.
1493
+ */
1494
+ // @implements A-SPEC-774.81 — exported so each branch can be pinned directly
1495
+ function scanShell(command) {
1496
+ const kind = new Array(command.length).fill(0 /* Ch.Code */);
1497
+ const docs = [];
1498
+ const pending = [];
1499
+ let segStart = 0;
1500
+ // @implements A-SPEC-774.75 — the separator before `#` must itself be unescaped (`a\ #x` is one word; a line
1501
+ // continuation is not taken to start a comment either, the conservative reading)
1502
+ const wordStart = (k) => k === 0 || (/[\s;&|()]/.test(command[k - 1]) && kind[k - 2] !== 8 /* Ch.Escape */);
1503
+ let inBacktick = false; // a comment inside backticks ends before the closing backtick
1504
+ let leadAt = -1; // a segment's lead word, read once per segment
1505
+ let lead = '';
1506
+ for (let k = 0; k < command.length; k++) {
1507
+ const ch = command[k];
1508
+ if (ch === '\\') {
1509
+ kind[k] = 8 /* Ch.Escape */;
1510
+ k++;
1511
+ continue;
1512
+ }
1513
+ if (ch === '`') {
1514
+ inBacktick = !inBacktick;
1515
+ continue;
1516
+ }
1517
+ if (ch === "'") {
1518
+ kind[k] = 7 /* Ch.Delim */;
1519
+ let j = k + 1;
1520
+ for (; j < command.length && command[j] !== "'"; j++)
1521
+ kind[j] = 1 /* Ch.Single */;
1522
+ if (j < command.length)
1523
+ kind[j] = 7 /* Ch.Delim */;
1524
+ k = j;
1525
+ continue;
1526
+ }
1527
+ if (ch === '$' && command[k + 1] === "'") {
1528
+ kind[k] = 7 /* Ch.Delim */;
1529
+ kind[k + 1] = 7 /* Ch.Delim */;
1530
+ let j = k + 2;
1531
+ for (; j < command.length && command[j] !== "'"; j++) {
1532
+ if (command[j] === '\\') {
1533
+ kind[j] = 8 /* Ch.Escape */;
1534
+ j++;
1535
+ if (j < command.length)
1536
+ kind[j] = 3 /* Ch.Ansi */;
1537
+ continue;
1538
+ }
1539
+ kind[j] = 3 /* Ch.Ansi */;
1540
+ }
1541
+ if (j < command.length)
1542
+ kind[j] = 7 /* Ch.Delim */;
1543
+ k = j;
1544
+ continue;
1545
+ }
1546
+ if (ch === '"') {
1547
+ kind[k] = 7 /* Ch.Delim */;
1548
+ let j = k + 1;
1549
+ for (; j < command.length && command[j] !== '"'; j++) {
1550
+ if (command[j] === '\\') {
1551
+ kind[j] = 8 /* Ch.Escape */;
1552
+ j++;
1553
+ if (j < command.length)
1554
+ kind[j] = 2 /* Ch.Double */;
1555
+ continue;
1556
+ }
1557
+ kind[j] = 2 /* Ch.Double */;
1558
+ }
1559
+ if (j < command.length)
1560
+ kind[j] = 7 /* Ch.Delim */;
1561
+ k = j;
1562
+ continue;
1563
+ }
1564
+ if (ch === '#' && wordStart(k)) {
1565
+ let j = k;
1566
+ for (; j < command.length && command[j] !== '\n' && !(inBacktick && command[j] === '`'); j++)
1567
+ kind[j] = 4 /* Ch.Comment */;
1568
+ k = j - 1;
1569
+ continue;
1570
+ }
1571
+ if (/[|;&()]/.test(ch)) {
1572
+ segStart = k + 1;
1573
+ continue;
1574
+ }
1575
+ // @implements A-SPEC-774.75 — `<<<` is a here-string, never a here-document at its second `<`
1576
+ if (ch === '<' && command[k + 1] === '<' && command[k + 2] === '<') {
1577
+ k += 2;
1578
+ continue;
1579
+ }
1580
+ if (ch === '<' && command[k + 1] === '<') {
1581
+ const w = hereDocWord(command, k + 2);
1582
+ if (w) {
1583
+ if (leadAt !== segStart) {
1584
+ leadAt = segStart;
1585
+ lead = ((/^\s*(\S*)/.exec(command.slice(segStart, k)) ?? ['', ''])[1]).split('/').pop() ?? '';
1586
+ }
1587
+ pending.push({ delim: w.delim, quoted: w.quoted, strip: w.strip, lead });
1588
+ k = w.end - 1;
1589
+ }
1590
+ continue;
1591
+ }
1592
+ if (ch === '\n') {
1593
+ segStart = k + 1;
1594
+ let at = k + 1;
1595
+ for (const h of pending.splice(0)) {
1596
+ let line = at;
1597
+ let bodyEnd = command.length;
1598
+ let next = command.length;
1599
+ let terminated = false;
1600
+ for (;;) {
1601
+ const nl = command.indexOf('\n', line);
1602
+ const text = command.slice(line, nl < 0 ? command.length : nl);
1603
+ if ((h.strip ? text.replace(/^\t+/, '') : text) === h.delim) {
1604
+ bodyEnd = line;
1605
+ next = nl < 0 ? command.length : nl + 1;
1606
+ terminated = true;
1607
+ break;
1608
+ }
1609
+ if (nl < 0)
1610
+ break;
1611
+ line = nl + 1;
1612
+ }
1613
+ for (let b = at; b < next; b++)
1614
+ kind[b] = b < bodyEnd && !h.quoted ? 5 /* Ch.Body */ : 6 /* Ch.QuotedBody */;
1615
+ docs.push({ bodyStart: at, bodyEnd, next, quoted: h.quoted, lead: h.lead, terminated });
1616
+ at = next;
1617
+ }
1618
+ if (at > k + 1) {
1619
+ k = at - 1;
1620
+ segStart = at;
1621
+ }
1622
+ }
1623
+ }
1624
+ return { kind, docs };
1625
+ }
1626
+ /**
1627
+ * @implements A-SPEC-774.68 — the bodies of the command substitutions outside single quotes: `$(…)` to its balanced `)`
1628
+ * and `` `…` `` to the next unescaped backtick, each to the end of the text when unclosed; nested bodies are found when
1629
+ * their body is judged in turn.
1630
+ * @implements A-SPEC-774.69 — read as the shell quotes: an apostrophe inside double quotes is a character, `$'…'` ends at
1631
+ * its first unescaped `'`, an unquoted here-document body is text in which substitutions run and a quoted one is skipped.
1632
+ * At most 64; `overflow` says a 65th was left unread, which the caller judges as a launch (review 18:43, F1.2-a, b).
1633
+ */
1634
+ function substitutionBodies(command, scan = scanShell(command)) {
1635
+ const out = [];
1636
+ let overflow = false;
1637
+ const take = (body) => { if (out.length >= 64)
1638
+ overflow = true;
1639
+ else
1640
+ out.push(body); };
1641
+ const { kind } = scan; // @implements A-SPEC-774.72 — the one scanner (774.75: handed over, not computed again)
1642
+ /** `$(…)` from `k` (at `$`), or a backtick span from `k`; the index of its last character. */
1643
+ const substitutionAt = (text, k) => {
1644
+ if (text[k] === '$') {
1645
+ let depth = 0;
1646
+ let j = k + 1;
1647
+ for (; j < text.length; j++) {
1648
+ if (text[j] === '\\') {
1649
+ j++;
1650
+ continue;
1651
+ }
1652
+ if (text[j] === '(')
1653
+ depth++;
1654
+ else if (text[j] === ')' && --depth === 0)
1655
+ break;
1656
+ }
1657
+ take(text.slice(k + 2, j));
1658
+ return j;
1659
+ }
1660
+ let j = k + 1;
1661
+ while (j < text.length && text[j] !== '`')
1662
+ j += text[j] === '\\' ? 2 : 1;
1663
+ take(text.slice(k + 1, j));
1664
+ return j;
1665
+ };
1666
+ for (let k = 0; k < command.length; k++) {
1667
+ const t = kind[k];
1668
+ if (t === 8 /* Ch.Escape */) {
1669
+ k++;
1670
+ continue;
1671
+ }
1672
+ // substitutions run in code, in double quotes and in an unquoted here-document body; nowhere else
1673
+ if (t !== 0 /* Ch.Code */ && t !== 2 /* Ch.Double */ && t !== 5 /* Ch.Body */)
1674
+ continue;
1675
+ const ch = command[k];
1676
+ if ((ch === '$' && command[k + 1] === '(') || ch === '`')
1677
+ k = substitutionAt(command, k);
1678
+ }
1679
+ return { bodies: out, overflow };
1120
1680
  }
1121
1681
  function dumpsEnvInCommandPosition(command, depth = 0) {
1122
1682
  if (depth > 3)
@@ -1273,8 +1833,8 @@ function shellPatchOf(command) {
1273
1833
  const PATCH_MARKERS = ['apply_patch', 'applypatch', '*** begin patch', '*** add file:', '*** update file:', '*** delete file:', '*** move to:'];
1274
1834
  /** Whether a text shows a marker once its quotes and backslashes are removed and its letters lowered. Substring tests only. */
1275
1835
  function patchMarked(text) {
1276
- // A backslash before a line feed is a line continuation: the shell removes both, so both are removed here.
1277
- const plain = text.split('\\\n').join('').split('"').join('').split("'").join('').split('\\').join('').toLowerCase();
1836
+ // A backslash before a line feed is a line continuation: the shell removes both, so both are removed here (A-SPEC-794.52).
1837
+ const plain = (0, line_continuation_1.joinLineContinuations)(text).split('"').join('').split("'").join('').split('\\').join('').toLowerCase();
1278
1838
  // `$'…'` and `$"…"` leave their `$` behind once the quotes are gone (`apply$'_patch'` reads `apply$_patch`), so the
1279
1839
  // text is tested with the dollars removed as well.
1280
1840
  const undollared = plain.split('$').join('');
@@ -1491,7 +2051,8 @@ function normalizeHookInput(raw, host = process.platform) {
1491
2051
  }
1492
2052
  }
1493
2053
  const sessionId = str(r.session_id);
1494
- return { tool_name: psShell !== undefined ? 'Bash' : str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(sessionId ? { session_id: sessionId } : {}), ...(malformed ? { malformed: true } : {}),
2054
+ const agentId = str(r.agent_id);
2055
+ return { tool_name: psShell !== undefined ? 'Bash' : str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(sessionId ? { session_id: sessionId } : {}), ...(agentId ? { agent_id: agentId } : {}), ...(malformed ? { malformed: true } : {}),
1495
2056
  ...(ps !== null && 'unjudgeable' in ps ? { powershellUnjudgeable: ps.unjudgeable } : {}),
1496
2057
  ...(codexPs !== null ? { codexPowerShell: codexPs } : {}),
1497
2058
  ...(patchUnreadable ? { patchUnreadable: true } : {}), ...(shellMarked && !otherUnreadable ? { patchUnreadableCause: 'shell-marker' } : {}),
@@ -1531,8 +2092,20 @@ function preEditEvidenceGate(o) {
1531
2092
  return null;
1532
2093
  if (o.covered)
1533
2094
  return null;
1534
- const verdict = (0, impact_gate_1.evaluateEditEvidence)((0, impact_gate_1.loadEditEvidence)(o.projectRoot, o.relPath, o.declaredDigest, o.currentHead));
1535
- return (0, impact_gate_1.preEditEvidenceDecision)(verdict, o.mode);
2095
+ const evidence = (0, impact_gate_1.loadEditEvidence)(o.projectRoot, o.relPath, o.declaredDigest, o.currentHead);
2096
+ const verdict = (0, impact_gate_1.evaluateEditEvidence)(evidence);
2097
+ const decision = (0, impact_gate_1.preEditEvidenceDecision)(verdict, o.mode);
2098
+ // @implements A-SPEC-333.4 — a clean allow clears the file from the commit reminder (recorded with the final allow)
2099
+ if (decision === null && verdict.decision === 'allow' && o.advisory)
2100
+ (0, advisory_line_1.adviseClean)(o.projectRoot, o.advisory, o.relPath);
2101
+ // @implements A-SPEC-333.2 — only a warn allow is shaped; a deny is said in full and touches no store
2102
+ if (decision?.permissionDecision !== 'allow' || !o.advisory)
2103
+ return decision;
2104
+ const detail = (0, advisory_line_1.advisoryDetail)({ artifactDigest: evidence.artifactDigest, traceGaps: evidence.traceGaps, head: o.currentHead, codes: verdict.reasons.map((r) => r.code) });
2105
+ const said = (0, advisory_line_1.adviseWarn)(o.projectRoot, o.advisory, verdict, o.relPath, detail, decision.permissionDecisionReason ?? '');
2106
+ if (said === undefined)
2107
+ return decision;
2108
+ return said === null ? { permissionDecision: 'allow' } : { ...decision, permissionDecisionReason: said };
1536
2109
  }
1537
2110
  function decideOnGateError(opts) {
1538
2111
  if (opts.bypass) {
@@ -1544,6 +2117,7 @@ function decideOnGateError(opts) {
1544
2117
  // spec chain that was never the problem.
1545
2118
  return {
1546
2119
  permissionDecision: 'deny',
2120
+ refusal: 'gate.unjudgeable', // A-SPEC-245.24 (item 1) — the message is the error's, so the code is the site's
1547
2121
  permissionDecisionReason: `[Holmes-Kit] cannot judge due to an internal error — the gate does not allow when it cannot decide: ${opts.message}`
1548
2122
  + ' → check the install with `holmes-kit doctor`. To let it through by operator judgment, set HOLMES_GATE_BYPASS=1 in the environment (an out-of-band channel a session cannot set itself).',
1549
2123
  };
@@ -1635,8 +2209,85 @@ function wiredSpecsDir(argv, env) {
1635
2209
  }
1636
2210
  /** Default spec root. Used to tell "never governed" apart from an explicitly configured HOLMES_SPECS. */
1637
2211
  exports.DEFAULT_SPECS_DIR = '.ax/specs';
2212
+ // @implements A-SPEC-222.4, A-SPEC-222.6 — the anchor-move judgment; A-SPEC-222.9 (SD1 1) moved it to succession-guard,
2213
+ // re-exported here for its callers
2214
+ var succession_guard_1 = require("../spec/succession-guard");
2215
+ Object.defineProperty(exports, "anchorMoveOnly", { enumerable: true, get: function () { return succession_guard_1.anchorMoveOnly; } });
1638
2216
  // @implements A-SPEC-100.2
1639
- function evaluateHook(input, specsDir, opts) {
2217
+ /**
2218
+ * @implements A-SPEC-245.2 — the grants one judgement resolved, settled once at its final decision. Each branch that
2219
+ * resolves a grant holds it here instead of spending it: an `.ax/roles` Write spent its grant at the roles branch and
2220
+ * was then denied by the protected-directory branch, which resolved the same approval again and found it gone (one
2221
+ * grant: denied and gone; two: allowed and both gone — measured).
2222
+ */
2223
+ /**
2224
+ * @implements A-SPEC-245.4 — the settlement is an explicit value in `opts`, settled once at the FINAL decision: the
2225
+ * entry point creates it and settles it after the plan-scope, stage, role and run-refusal passes (each can still turn
2226
+ * the allow into a deny, and a run-stage deny spent the grant of an act that never happened), and the counterfactual
2227
+ * audit reading passes one that never spends. A caller that passes none is settled at this function's return.
2228
+ */
2229
+ function settleVerdict(verdict, settlement) {
2230
+ const allowed = verdict.permissionDecision === 'allow';
2231
+ // @implements A-SPEC-245.9 (1b-2) — in the hook's worker, the spend is the main thread's (settleOnMainThread)
2232
+ const pending = settlement.pending();
2233
+ const outcome = allowed && settlement.spends && (pending.held.length > 0 || pending.env.length > 0)
2234
+ ? settlement.adopt((mainThreadSettler ?? settleOnMainThread)(pending))
2235
+ : settlement.settle(allowed);
2236
+ if (outcome === 'settled')
2237
+ return verdict;
2238
+ if (outcome === 'refused') {
2239
+ // A-SPEC-245.24 (item 1) — a spent, revoked or conflicting single-use approval needs a new one from the person
2240
+ return { ...verdict, permissionDecision: 'deny', refusal: 'approval.required', permissionDecisionReason: `[Holmes-Kit] ${settlement.refusal ?? 'the single-use approval could not be spent once'} (A-SPEC-245.9)` };
2241
+ }
2242
+ return { ...verdict, permissionDecision: 'deny', refusal: 'grant.in-use', permissionDecisionReason: '[Holmes-Kit] the approval grant this act needs is in use by another act — nothing was spent and nothing was done; retry (A-SPEC-245.4)' };
2243
+ }
2244
+ /**
2245
+ * @implements A-SPEC-245.9 (1b-2) — set in the hook's worker: hands a final allow's pending spends to the main thread and
2246
+ * waits for its answer. The worker can be terminated at the deadline at any instruction; the main thread is not.
2247
+ */
2248
+ let mainThreadSettler = null;
2249
+ /** @implements A-SPEC-245.9 (1b-2) — the main thread's half: settle the pending spends here and answer. */
2250
+ function settleOnMainThread(p) {
2251
+ // test seam (A-SPEC-245.15, 6c): which thread spent — a boolean switch writing one fixed file inside the judged project
2252
+ // (the pending spends' root, where `.ax` exists), never a path taken from the environment
2253
+ const probeRoot = [...p.held, ...p.env][0]?.root;
2254
+ if (process.env.HOLMES_HOOK_TEST_SPEND_THREAD === '1' && probeRoot && fs.existsSync(path.join(probeRoot, '.ax'))) {
2255
+ try {
2256
+ fs.mkdirSync(path.join(probeRoot, '.ax', 'state'), { recursive: true });
2257
+ fs.writeFileSync(path.join(probeRoot, '.ax', 'state', 'spend-thread-probe'), require('node:worker_threads').isMainThread ? 'main' : 'worker');
2258
+ }
2259
+ catch { /* a seam */ }
2260
+ }
2261
+ const s = approval_grants_1.GrantSettlement.fromPending(p);
2262
+ const outcome = s.settle(true);
2263
+ return { outcome, committed: [...s.committed], ...(s.refusal !== undefined ? { refusal: s.refusal } : {}) };
2264
+ }
2265
+ /** @implements A-SPEC-245.4 (f) — the approval an audit line names: a grant this decision spent, else the counterfactual's environment approval. */
2266
+ function auditApprovalFor(envApproval, counterfactualDenied, settlement) {
2267
+ return settlement.committed[0] ?? (counterfactualDenied ? envApproval : undefined);
2268
+ }
2269
+ function evaluateHook(...args) {
2270
+ const [input, specsDir, opts] = args;
2271
+ // @implements A-SPEC-245.26 (item 1) — a nested reading is one that shares the top reading's `filed` holder (through
2272
+ // `...opts`); a caller's settlement is not that sign: runHookProcess gives one, and taking it for a nested reading lost
2273
+ // the filed request (no run wait) and the advisory on the path every harness runs
2274
+ if (opts.filed !== undefined)
2275
+ return judgeHook(input, specsDir, opts);
2276
+ const filed = {};
2277
+ const settlement = opts.settlement ?? new approval_grants_1.GrantSettlement();
2278
+ const judged = judgeHook(input, specsDir, { ...opts, settlement, filed });
2279
+ // the caller that brought its own settlement settles it (runHookProcess, after the run path); otherwise it is settled here
2280
+ const settled = opts.settlement !== undefined ? judged : settleVerdict(judged, settlement);
2281
+ // @implements A-SPEC-245.25 (item 5a) — a deny carries the request the gate filed; the run path waits on that id only
2282
+ const verdict = settled.permissionDecision === 'deny' && filed.request !== undefined ? { ...settled, request: filed.request } : settled;
2283
+ // @implements A-SPEC-245.19 (item 2) — an allowed command whose text names the act carries the advisory
2284
+ const advice = input.tool_name === 'Bash' && verdict.permissionDecision === 'allow' && typeof input.tool_input.command === 'string'
2285
+ ? lockRecoverAdvisory(input.tool_input.command) : null;
2286
+ if (advice === null)
2287
+ return verdict;
2288
+ return { ...verdict, permissionDecisionReason: [verdict.permissionDecisionReason, advice].filter((t) => typeof t === 'string' && t !== '').join('\n') };
2289
+ }
2290
+ function judgeHook(input, specsDir, opts) {
1640
2291
  // @implements A-SPEC-790.2 — a Codex shell payload on Windows: the Bash reading first (a denial there is the decision,
1641
2292
  // and nothing more is filed); then the PowerShell text Codex actually runs. Only ever stricter than the Bash reading.
1642
2293
  const codexPs = input.codexPowerShell;
@@ -1650,7 +2301,7 @@ function evaluateHook(input, specsDir, opts) {
1650
2301
  return bashVerdict;
1651
2302
  if ('unjudgeable' in codexPs) {
1652
2303
  const who = codexPs.harness === 'antigravity' ? 'an Antigravity' : 'a Codex';
1653
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${who} command that PowerShell runs and the gate cannot judge (${codexPs.unjudgeable}) is refused (REQ-790)` };
2304
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] ${who} command that PowerShell runs and the gate cannot judge (${codexPs.unjudgeable}) is refused (REQ-790)` };
1654
2305
  }
1655
2306
  return evaluateHook({ ...bashInput, tool_input: { ...bashInput.tool_input, command: codexPs.shell } }, specsDir, { ...opts, carriedApprovals: { command: String(bashInput.tool_input?.command ?? ''), reading: codexPs.shell, approvals: spent } });
1656
2307
  }
@@ -1666,13 +2317,14 @@ function evaluateHook(input, specsDir, opts) {
1666
2317
  // @implements A-SPEC-790 — a PowerShell command whose text cannot be read is refused rather than judged.
1667
2318
  const psUnjudgeable = input.powershellUnjudgeable;
1668
2319
  if (psUnjudgeable !== undefined) {
1669
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a PowerShell command that cannot be judged (${psUnjudgeable}) is refused (REQ-790)` };
2320
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] a PowerShell command that cannot be judged (${psUnjudgeable}) is refused (REQ-790)` };
1670
2321
  }
1671
2322
  if (input.patchUnreadable) {
1672
2323
  const cause = input;
1673
2324
  // @implements A-SPEC-769.7 — four conditions, four sentences: shell marker, no-op update, and (below) the
1674
2325
  // path-missing sentence for a payload whose targets cannot be read; non-application has its own site.
1675
- return { permissionDecision: 'deny', permissionDecisionReason: cause.patchUnreadableCause === 'shell-marker'
2326
+ return { permissionDecision: 'deny', refusal: cause.patchUnreadableCause === 'shell-marker' || cause.patchUnreadableCause === 'no-op' ? 'patch.unreadable' : 'target.unresolvable',
2327
+ permissionDecisionReason: cause.patchUnreadableCause === 'shell-marker'
1676
2328
  ? SHELL_MARKED_REASON : cause.patchUnreadableCause === 'no-op' ? patchNoopReason(cause.patchNoopPaths ?? []) : PATCH_UNREADABLE_REASON };
1677
2329
  }
1678
2330
  const patchTargets = input.tool_input.patch_targets;
@@ -1696,7 +2348,8 @@ function evaluateHook(input, specsDir, opts) {
1696
2348
  return null;
1697
2349
  }
1698
2350
  };
1699
- const judged = (file, r) => r === null ? { deny: PATCH_UNREADABLE_REASON } : 'failure' in r ? { deny: patchNotAppliedReason(file, r.failure) } : { content: r.result };
2351
+ // A-SPEC-245.24 (item 1) — each deny with its code: an unreadable target, or a patch that does not apply
2352
+ const judged = (file, r) => r === null ? { deny: PATCH_UNREADABLE_REASON, refusal: 'target.unresolvable' } : 'failure' in r ? { deny: patchNotAppliedReason(file, r.failure), refusal: 'patch.unreadable' } : { content: r.result };
1700
2353
  // @implements A-SPEC-163.3 (rule 1), A-SPEC-163.4 (rule 5) — two targets on one file have no one result: the tool
1701
2354
  // applies them in sequence, the gate reads the disk once. One file is one key whatever link or letter case names it.
1702
2355
  // (What a shell could rewrite is settled before this point: only the one quoted-heredoc form reaches here.)
@@ -1704,7 +2357,7 @@ function evaluateHook(input, specsDir, opts) {
1704
2357
  for (const t of patchTargets) {
1705
2358
  const file = patchFileKey(at(t.path));
1706
2359
  if (files.has(file))
1707
- return { permissionDecision: 'deny', permissionDecisionReason: PATCH_UNREADABLE_REASON };
2360
+ return { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: PATCH_UNREADABLE_REASON };
1708
2361
  files.add(file);
1709
2362
  }
1710
2363
  for (const t of patchTargets) {
@@ -1714,13 +2367,13 @@ function evaluateHook(input, specsDir, opts) {
1714
2367
  else if (t.kind === 'update' && t.movedTo === undefined) {
1715
2368
  const j = judged(at(t.path), resultOf(at(t.path), t.hunk ?? ''));
1716
2369
  if ('deny' in j)
1717
- return { permissionDecision: 'deny', permissionDecisionReason: j.deny };
2370
+ return { permissionDecision: 'deny', refusal: j.refusal, permissionDecisionReason: j.deny };
1718
2371
  content = j.content;
1719
2372
  }
1720
2373
  else if (t.kind === 'move') {
1721
2374
  const j = judged(at(t.from ?? t.path), t.from === undefined ? null : resultOf(at(t.from), t.hunk ?? ''));
1722
2375
  if ('deny' in j)
1723
- return { permissionDecision: 'deny', permissionDecisionReason: j.deny };
2376
+ return { permissionDecision: 'deny', refusal: j.refusal, permissionDecisionReason: j.deny };
1724
2377
  content = j.content;
1725
2378
  }
1726
2379
  // Judged as a patch tool's write whichever tool carried the patch, so the shell branch below is not re-entered.
@@ -1750,7 +2403,22 @@ function evaluateHook(input, specsDir, opts) {
1750
2403
  }
1751
2404
  return fullCache;
1752
2405
  };
1753
- const hintOrRoute = (req, extra) => (fullEntry() !== null ? (0, full_autonomy_1.fullModeRefusalTail)(req.kind) : (0, approval_queue_1.queueHint)(opts.projectRoot, req, extra));
2406
+ const hintOrRoute = (req, extra) => (fullEntry() !== null ? (0, full_autonomy_1.fullModeRefusalTail)(req.kind) : fileHint(req, extra));
2407
+ // @implements A-SPEC-245.25 (item 5a) — the request the gate filed (or found already pending: the queue drops the
2408
+ // duplicate, and its hint then names no id), recorded for the verdict by its own id, never read from text
2409
+ function fileHint(req, extra) {
2410
+ const hint = (0, approval_queue_1.queueHint)(opts.projectRoot, req, extra);
2411
+ if (opts.filed !== undefined) {
2412
+ // A-SPEC-245.26 (4b) — the id the queue derives from the request itself, never one parsed from the hint
2413
+ const id = (0, approval_queue_1.approvalRequestId)(req.kind, req.target);
2414
+ if (hint !== '' || (0, approval_queue_1.readQueue)(opts.projectRoot).pending.some((p) => p.id === id))
2415
+ opts.filed.request = id;
2416
+ }
2417
+ return hint;
2418
+ }
2419
+ // @implements A-SPEC-245.24 (item 1) — the code of a deny that ends with hintOrRoute: under a full profile the tail is
2420
+ // the full-autonomy refusal (nothing was filed), otherwise the site's own code
2421
+ const routeCode = (base) => (fullEntry() !== null ? 'full-autonomy.refused' : base);
1754
2422
  // @implements A-SPEC-125.4
1755
2423
  // Bash/shell risk gate: this branch runs BEFORE the Write/Edit phaseCheck logic below and
1756
2424
  // is intentionally fail-CLOSED — a classifier throw on the Bash surface denies, never
@@ -1768,7 +2436,30 @@ function evaluateHook(input, specsDir, opts) {
1768
2436
  // shapes of repeated separators took 2.4–6.1 s at 256 KB, their cost spread over every segment of every rule (measured).
1769
2437
  const segmentsOnce = (0, write_target_2.shellSegments)(command, shellBase);
1770
2438
  if (segmentsOnce.length > SHELL_SEGMENTS_MAX) {
1771
- 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)` };
2439
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', 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)` };
2440
+ }
2441
+ // @implements A-SPEC-792.14 — a push cannot carry a spec change no grant accounts for off the machine
2442
+ // A-SPEC-794.52, A-SPEC-794.53 — a push written across a line continuation is still a push; comments and
2443
+ // here-document bodies go first, in the order the flag judgement reads. A-SPEC-794.54 — only a command that names git
2444
+ // and push is read further (the reader only removes text and a `$` before a quote, so it adds no word), and one the
2445
+ // reader cannot finish is read whole
2446
+ const joined = (0, line_continuation_1.joinLineContinuations)(command);
2447
+ if (/\bgit\b/.test(joined) && /\bpush\b/.test(joined) && /\bgit\b[^;&|\n]*\bpush\b/.test((0, line_continuation_1.joinLineContinuations)((0, unresolved_write_1.readableText)(command)))) {
2448
+ try {
2449
+ const seam = require('../governance/spec-seam').unexplainedSpecChanges(opts.projectRoot, specsDir);
2450
+ // @implements A-SPEC-222.15 (item 5) — a scan finding is refused with its own reason and no unstage or reset advice
2451
+ const scans = seam.filter((u) => u.where === 'scan');
2452
+ if (scans.length > 0) {
2453
+ return { permissionDecision: 'deny', refusal: 'governance.path', permissionDecisionReason: `[Holmes-Kit] push refused: the spec seam could not judge the governance store's specs — ${scans.map((u) => u.detail ?? 'the scan could not finish').join('; ')} (A-SPEC-792.14)` };
2454
+ }
2455
+ if (seam.length > 0) {
2456
+ const named = seam.slice(0, 5).map((u) => u.where === 'index' ? `staged ${u.path}` : `commit ${(u.commit ?? '').slice(0, 12)} changes ${u.path}`).join('; ');
2457
+ return { permissionDecision: 'deny', refusal: 'governance.path', permissionDecisionReason: `[Holmes-Kit] push refused: changes to the governance store's specs entered the index or a commit with no granted staging act (${named}) — unstage them, move the branch back past the commit, or stage them again with the plain git add the gate files for approval_ask (A-SPEC-792.14)` };
2458
+ }
2459
+ }
2460
+ catch {
2461
+ return { permissionDecision: 'deny', refusal: 'governance.path', permissionDecisionReason: '[Holmes-Kit] push refused: the governance store\'s spec seam could not be judged (A-SPEC-792.14)' };
2462
+ }
1772
2463
  }
1773
2464
  // Git-aware rm signals (H1): resolved only when a resolver is injected (the CLI wires the real
1774
2465
  // git-backed one; unit tests omit it and exercise the pure static path). Fail-open: a throwing
@@ -1805,9 +2496,9 @@ function evaluateHook(input, specsDir, opts) {
1805
2496
  catch (e) {
1806
2497
  // @implements A-SPEC-728 (rule 44) — a classifier bound says what it is: too large to judge, not a classifier failure.
1807
2498
  if (e instanceof RangeError && /too large to judge/.test(e.message)) {
1808
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${e.message} — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
2499
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] ${e.message} — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
1809
2500
  }
1810
- return { permissionDecision: 'deny', permissionDecisionReason: '[Holmes-Kit] risk classification failed on a shell command — denied (fail-closed)' };
2501
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: '[Holmes-Kit] risk classification failed on a shell command — denied (fail-closed)' };
1811
2502
  }
1812
2503
  // @implements A-SPEC-133
1813
2504
  // Hard-hitl needs an approval that COVERS this specific command (scope + not expired), and if
@@ -1828,52 +2519,105 @@ function evaluateHook(input, specsDir, opts) {
1828
2519
  const legacySessionApproval = approval?.scope === undefined
1829
2520
  && (0, risk_gate_1.approvalCovers)(approval, { kind: 'config-write', target: command }, nowTs);
1830
2521
  let hardHitlCovered = false;
2522
+ // @implements A-SPEC-792.32 — the staging approvals this act carries, recorded only at the final allow
2523
+ let autonomousStaging = null;
2524
+ let personStaging = false;
2525
+ // @implements A-SPEC-794.49 — REQ-792: push and publish follow the profile's flags, and no grant lifts it
2526
+ const outwardEntry = fullEntry();
2527
+ const outwardRoute = outwardEntry === null ? null : (0, full_autonomy_1.fullModeOutwardRefusal)((0, risk_classifier_1.outwardActsOf)(command), outwardEntry);
2528
+ if (outwardRoute !== null) {
2529
+ return { permissionDecision: 'deny', refusal: 'full-autonomy.refused', permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: a push or a publish is irreversible and outward — refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', outwardRoute)}` };
2530
+ }
1831
2531
  if (assessment.level === 'hard-hitl') {
1832
2532
  // @implements A-SPEC-245 — env first, then the grant files. The grant's mandatory nonce rides
1833
2533
  // the SAME atomic ledger consumption below, so hard-hitl single-use needs no new machinery.
1834
2534
  const resolved = resolveForCommand('shell');
1835
2535
  const covers = resolved !== undefined;
1836
- const deny = (why) => ({
2536
+ // @implements A-SPEC-245.24 (item 1, R1) — the reasons quote agent-chosen names (an alias, a hook name), so the code
2537
+ // is the site's: approval.required, or the full-autonomy refusal on the full-profile paths
2538
+ const deny = (why, refusal = 'approval.required') => ({
1837
2539
  permissionDecision: 'deny',
2540
+ refusal,
1838
2541
  permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: ${assessment.reasons.join('; ')} — ${why}`,
1839
2542
  });
1840
2543
  // @implements A-SPEC-244 — the refusal itself files the review request. The queue kind is the
1841
2544
  // approval SCOPE kind ('shell'), so the reviewing CLI can mint a covering grant mechanically.
1842
2545
  hardHitlCovered = covers;
1843
- const full = covers ? null : fullEntry();
1844
- if (full !== null) {
2546
+ const fullScope = covers ? null : fullEntry();
2547
+ // @implements A-SPEC-792.28 — H2-a: governance staging under a full profile is approved by machine conditions
2548
+ // (autonomous-shell.ts judges; this records), and a failed condition is named on today's path
2549
+ let h2Note = '';
2550
+ if (fullScope !== null) {
2551
+ const auto = require('../governance/autonomous-shell');
2552
+ if (auto.governanceStagingOnly(assessment.reasons)) {
2553
+ // @implements A-SPEC-792.31 — the verdict is told where the spec store is
2554
+ const specsRel = path.relative(opts.projectRoot, specsDir).split(path.sep).join('/');
2555
+ // @implements A-SPEC-792.32 — one base (the shell's), and the stop lifted only by a caller's programmatic option
2556
+ const verdict = auto.autonomousShellVerdict({ command, root: opts.projectRoot, shellStaging: (0, config_1.loadConfig)(opts.projectRoot).autonomy.shellStaging, specsRel,
2557
+ base: shellBase, specStaging: opts.autonomySpecStaging === true }, auto.realShellDeps(opts.projectRoot));
2558
+ if (verdict.ok) {
2559
+ // @implements A-SPEC-792.32 — approved here, recorded at the final allow (every later Bash gate first), and
2560
+ // what is recorded is the verdict's proven (path, blob) pairs, computed from the bytes it proved
2561
+ autonomousStaging = { scope: fullScope.scope, paths: verdict.paths, proven: verdict.proven, conditions: verdict.conditions };
2562
+ hardHitlCovered = true;
2563
+ }
2564
+ else
2565
+ h2Note = ` (autonomous shell approval: ${verdict.failed} — ${verdict.detail})`;
2566
+ }
2567
+ }
2568
+ if (autonomousStaging === null) {
1845
2569
  // @implements A-SPEC-792.5 — a full scope approves a scoped destructive act after a recovery point and refuses
1846
2570
  // every other act at once; nothing is filed, so a run never waits on it.
1847
- const v = (0, full_autonomy_1.fullModeShellVerdict)({ command, reasons: assessment.reasons, cwd: shellBase, workspace: opts.projectRoot, scratchRoot: (0, scratch_root_1.trustedScratchRoot)(), entry: full });
1848
- if (v.outcome === 'refuse')
1849
- return deny(`refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', v.route)}`);
1850
- let recoveryRef;
1851
- if (v.recovery) {
1852
- const r = (0, full_autonomy_1.writeRecoveryRef)(opts.projectRoot, nowTs);
1853
- if ('error' in r)
1854
- return deny(`refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', r.error)}`);
1855
- recoveryRef = r.ref;
2571
+ // @implements A-SPEC-792.10 — except spec staging, which goes to the person's form like it does without a profile.
2572
+ const v = fullScope === null ? null
2573
+ : (0, full_autonomy_1.fullModeShellVerdict)({ command, reasons: assessment.reasons, cwd: shellBase, workspace: opts.projectRoot, scratchRoot: (0, scratch_root_1.trustedScratchRoot)(), entry: fullScope });
2574
+ const full = v === null || v.outcome === 'ask' ? null : fullScope;
2575
+ if (full !== null && v !== null && v.outcome !== 'ask') {
2576
+ if (v.outcome === 'refuse')
2577
+ return deny(`refused${h2Note}${(0, full_autonomy_1.fullModeRefusalTail)('shell', v.route)}`, 'full-autonomy.refused');
2578
+ let recoveryRef;
2579
+ if (v.recovery) {
2580
+ const r = (0, full_autonomy_1.writeRecoveryRef)(opts.projectRoot, nowTs);
2581
+ if ('error' in r)
2582
+ return deny(`refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', r.error)}`, 'full-autonomy.refused');
2583
+ recoveryRef = r.ref;
2584
+ }
2585
+ try {
2586
+ new ledger_store_1.FileLedgerStore(path.join(opts.projectRoot, '.ax', 'ledger')).append({
2587
+ ts: nowTs, actor: `full-autonomy:${full.scope}`, kind: 'full-autonomy-approved',
2588
+ summary: `hard-hitl shell act approved under full autonomy${recoveryRef ? ` (recovery ${recoveryRef})` : ''}`.slice(0, 200),
2589
+ inputs: [crypto.createHash('sha256').update(command).digest('hex')],
2590
+ rationale: assessment.reasons.join('; ').slice(0, 300),
2591
+ });
2592
+ }
2593
+ catch { /* the act is approved; the audit row is best effort like the other gate records */ }
2594
+ hardHitlCovered = true;
1856
2595
  }
1857
- try {
1858
- new ledger_store_1.FileLedgerStore(path.join(opts.projectRoot, '.ax', 'ledger')).append({
1859
- ts: nowTs, actor: `full-autonomy:${full.scope}`, kind: 'full-autonomy-approved',
1860
- summary: `hard-hitl shell act approved under full autonomy${recoveryRef ? ` (recovery ${recoveryRef})` : ''}`.slice(0, 200),
1861
- inputs: [crypto.createHash('sha256').update(command).digest('hex')],
1862
- rationale: assessment.reasons.join('; ').slice(0, 300),
1863
- });
2596
+ else if (!covers) {
2597
+ // @implements A-SPEC-564.2 — the base reason's length rides along so the refusal record
2598
+ // knows the FULL feedback cost (base + hint), not just the hint's half.
2599
+ const base = `requires an approval that covers this command${h2Note}`;
2600
+ const refused = deny(base
2601
+ + fileHint({ kind: 'shell', target: command, why: assessment.reasons.join('; ') }, { baseReasonBytes: base.length }));
2602
+ // @implements A-SPEC-794.55 — staging spec files by their paths is a request for a person, not a read gone wrong:
2603
+ // the person's route comes first, and the classifier's reason follows unchanged
2604
+ if ((0, full_autonomy_1.onlyStagesSpecs)(command, shellBase, opts.projectRoot)) {
2605
+ refused.permissionDecisionReason = refused.permissionDecisionReason.replace('[Holmes-Kit] hard-hitl risk: ', '[Holmes-Kit] hard-hitl risk: staging spec files is a person\'s decision — call approval_ask with the request id below so the person decides in the session form, then retry this same command once; the gate\'s reading: ');
2606
+ }
2607
+ return refused;
2608
+ }
2609
+ else {
2610
+ pendingApprovals.push(resolved);
2611
+ // @implements A-SPEC-792.13 — a granted act that stages records what it stages, so the seam can tell it apart (a
2612
+ // literal spec path is refused as an opaque .ax act before the staging rule names it)
2613
+ // @implements A-SPEC-792.15 — only an act the gate judged as spec staging (or an opaque .ax act): an unrelated
2614
+ // approval that merely holds the words grants nothing
2615
+ // @implements A-SPEC-792.32 — recorded at the final allow, after every later Bash gate
2616
+ if (/\bgit\b/.test(command) && /\b(?:add|stage|commit)\b/.test(command)
2617
+ && assessment.reasons.some((r) => /^staging command reaches changed files in the protected \.ax spec store|^staging command reaches another replica's ledger file|^shell command over a protected \.ax governance path/.test(r))) {
2618
+ personStaging = true;
2619
+ }
1864
2620
  }
1865
- catch { /* the act is approved; the audit row is best effort like the other gate records */ }
1866
- hardHitlCovered = true;
1867
- }
1868
- else if (!covers) {
1869
- // @implements A-SPEC-564.2 — the base reason's length rides along so the refusal record
1870
- // knows the FULL feedback cost (base + hint), not just the hint's half.
1871
- const base = 'requires an approval that covers this command';
1872
- return deny(base
1873
- + (0, approval_queue_1.queueHint)(opts.projectRoot, { kind: 'shell', target: command, why: assessment.reasons.join('; ') }, { baseReasonBytes: base.length }));
1874
- }
1875
- else {
1876
- pendingApprovals.push(resolved);
1877
2621
  }
1878
2622
  }
1879
2623
  // Bash BYPASS gates (adversarial review: `cat > evil.ts` created ungoverned files, `echo x >
@@ -1979,6 +2723,16 @@ function evaluateHook(input, specsDir, opts) {
1979
2723
  // request id is printed: none exists until the operator runs the command, which files it.
1980
2724
  // @implements A-SPEC-753.3 — the exact grammar first; otherwise any command of the line that applies. The
1981
2725
  // operator part is that one command as written, not the whole line.
2726
+ // @implements A-SPEC-245.9 (1b-5) — the operator's act, refused here in every harness's spelling
2727
+ if (lockRecoverAct(command)) {
2728
+ return {
2729
+ permissionDecision: 'deny',
2730
+ // @implements A-SPEC-245.22 (item 5) — the act's name only: the agent's words chose the refusal code (a
2731
+ // command holding "this run stopped" was coded run.stopped), and A-SPEC-792.1 spells no command for a person
2732
+ permissionDecisionReason: '[Holmes-Kit] holmes-kit lock recover retires a lock another process may hold — the operator runs it, not the session (A-SPEC-245.9).',
2733
+ refusal: 'operator-act.refused', // A-SPEC-245.23 (item 3)
2734
+ };
2735
+ }
1982
2736
  const installerExact = legacySessionApproval ? null : (0, shell_argument_roles_1.installerInvocationOf)(command);
1983
2737
  const installerApply = legacySessionApproval ? null
1984
2738
  : installerExact === 'apply' ? command
@@ -1986,12 +2740,14 @@ function evaluateHook(input, specsDir, opts) {
1986
2740
  if (installerApply !== null) {
1987
2741
  return {
1988
2742
  permissionDecision: 'deny',
2743
+ refusal: 'launch.refused', // A-SPEC-245.24
1989
2744
  permissionDecisionReason: '[Holmes-Kit] runtime-binding setup/remove changes which Holmes build governs a workspace (governance wiring); the operator runs it, not the session. It prints the request id to approve; after the grant the operator runs the same command again. Use --dry-run to preview it here. Operator: ' + installerApply,
1990
2745
  };
1991
2746
  }
1992
2747
  if (!legacySessionApproval && startsHolmesServer(command)) {
1993
2748
  return {
1994
2749
  permissionDecision: 'deny',
2750
+ refusal: 'launch.refused', // A-SPEC-245.24
1995
2751
  permissionDecisionReason: '[Holmes-Kit] the command starts the Holmes MCP server (or loads its handlers) itself — a copy the agent drives could answer its own approval (A-SPEC-732). The harness starts the server; use its tools. To run it by operator judgment, an approval that covers this command is required.',
1996
2752
  };
1997
2753
  }
@@ -2013,7 +2769,8 @@ function evaluateHook(input, specsDir, opts) {
2013
2769
  if (!hint && (0, approval_queue_1.readQueue)(opts.projectRoot).pending.some((request) => request.id === id)) {
2014
2770
  hint = ` — approval request ${id} is pending; retry after operator approval`;
2015
2771
  }
2016
- return { permissionDecision: 'deny', permissionDecisionReason: reason
2772
+ // A-SPEC-245.24 (item 1) — a launch with a gate-off setting or in a run is a launch; the others read secrets
2773
+ return { permissionDecision: 'deny', refusal: routeCode(GATE_OFF !== null || AGENT_LAUNCH ? 'launch.refused' : 'secret.access'), permissionDecisionReason: reason
2017
2774
  + (hint || ' — could not persist the approval request; ask the operator to check the project approval queue storage') };
2018
2775
  }
2019
2776
  pendingApprovals.push(resolved);
@@ -2025,7 +2782,8 @@ function evaluateHook(input, specsDir, opts) {
2025
2782
  // `cp`, `mv`, `install`, `ln -f`, `dd of=`, `rsync` and `sed -i` write the same file just as
2026
2783
  // well. A gate that names one syntax for an act is a gate over that syntax, not over the act.
2027
2784
  const CODE_EXT = '(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|go|rs|java|kt|cs|cc|cxx|cpp|hh|hpp|rb|php|swift)';
2028
- const CONFIG_FILE = '(?:\\.claude[\\\\/]settings[\\w.-]*\\.json|\\.mcp\\.json|\\.env(?!\\.(?:example|sample|template|dist))(?:\\.[\\w-]+)?)';
2785
+ // @implements A-SPEC-792.35 — and what git runs: .git/config, .git/info/*, .git/hooks/* and any .gitattributes
2786
+ const CONFIG_FILE = '(?:\\.claude[\\\\/]settings[\\w.-]*\\.json|\\.mcp\\.json|\\.env(?!\\.(?:example|sample|template|dist))(?:\\.[\\w-]+)?|\\.git[\\\\/](?:config|(?:info|hooks)[\\\\/][\\w.-]+)|\\.gitattributes)';
2029
2787
  // @implements A-SPEC-448
2030
2788
  // Paths an INTERPRETER one-liner writes. The residual both shell rules recorded, closed by
2031
2789
  // asking for the evidence of a write rather than for an interpreter's name near a pattern.
@@ -2124,7 +2882,7 @@ function evaluateHook(input, specsDir, opts) {
2124
2882
  }
2125
2883
  return out;
2126
2884
  };
2127
- const TOO_MANY_CANDIDATES = { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a shell command with more than ${SHELL_CANDIDATES_MAX} distinct write targets is too large to judge — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
2885
+ const TOO_MANY_CANDIDATES = { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] a shell command with more than ${SHELL_CANDIDATES_MAX} distinct write targets is too large to judge — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
2128
2886
  const isTilde = (p) => p === '~' || p.startsWith('~/');
2129
2887
  // Relative candidate in a segment whose base is unknowable (dynamic cd argument): 'unknown',
2130
2888
  // and the caller fails CLOSED — but only when such a candidate exists, so `cd "$X" && npm
@@ -2190,13 +2948,15 @@ function evaluateHook(input, specsDir, opts) {
2190
2948
  // tell reading from writing costs more than the hole it closes; the same residual is already
2191
2949
  // recorded for the code-write rule below.
2192
2950
  if (configWrite) {
2193
- return { permissionDecision: 'deny', permissionDecisionReason: registry_1.MESSAGES.INTEGRITY_CONFIG_EDIT('.claude/settings, .env, .mcp.json', 'A-SPEC-191') };
2951
+ return { permissionDecision: 'deny', refusal: 'approval.required', permissionDecisionReason: registry_1.MESSAGES.INTEGRITY_CONFIG_EDIT('.claude/settings, .env, .mcp.json, .git/config, .git/info, .git/hooks, .gitattributes', 'A-SPEC-191, A-SPEC-792.35') };
2194
2952
  }
2195
2953
  // @implements A-SPEC-728 — the harness config that loads THIS session's gate also lives outside
2196
2954
  // the project: `~/.claude/settings*.json` and Codex's user-level `config.toml`/`hooks.json`
2197
2955
  // (the only place codex-cli 0.155 loads Holmes from). Judged by identity after `~`/`$HOME`/
2198
2956
  // `$CODEX_HOME` expansion, so no spelling is a door.
2199
- const CODEX_FILE = String.raw `(?:config\.toml|hooks\.json)`;
2957
+ // @implements A-SPEC-792.39 — and the user's global git config and attributes (`~/.gitconfig`,
2958
+ // `$XDG_CONFIG_HOME/git/config`, `…/git/attributes`), which name programs every git child runs.
2959
+ const CODEX_FILE = String.raw `(?:config\.toml|hooks\.json|\.gitconfig|git[\\/](?:config|attributes))`;
2200
2960
  const userCfgCands = [...cfgCandidates];
2201
2961
  const CODEX_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(CODEX_FILE)}`, 'g');
2202
2962
  for (const seg of segments) {
@@ -2204,13 +2964,13 @@ function evaluateHook(input, specsDir, opts) {
2204
2964
  collectPaths(seg, WRITE_VERB, CODEX_FILE, userCfgCands);
2205
2965
  collectPaths(seg, /\bsed\b/, CODEX_FILE, userCfgCands, /\s-i\b/);
2206
2966
  }
2207
- const USER_CFG_RE = /(?:config\.toml|hooks\.json|settings[\w.-]*\.json)$/;
2967
+ const USER_CFG_RE = /(?:config\.toml|hooks\.json|settings[\w.-]*\.json|\.gitconfig|git[\\/](?:config|attributes))$/;
2208
2968
  userCfgCands.push(...interpreterWrites.filter((p) => USER_CFG_RE.test(p)).flatMap(expandInterp));
2209
2969
  const userCfgList = distinct(userCfgCands);
2210
2970
  if (userCfgList === null)
2211
2971
  return TOO_MANY_CANDIDATES;
2212
2972
  const userCfgKind = userCfgList
2213
- .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)))
2973
+ .map((c) => (c.base === null ? ((0, write_target_2.absoluteKindOf)(c.raw) !== null || /^(?:~|\$\{?(?:HOME|CODEX_HOME|XDG_CONFIG_HOME)\b)/.test(c.raw) ? (0, write_target_2.userHarnessConfigKindOf)(c.raw, opts.projectRoot) : null) : (0, write_target_2.userHarnessConfigKindOf)(c.raw, c.base)))
2214
2974
  .find((k) => k !== null);
2215
2975
  // One config-write approval (env or a granted queue request for this exact command) lifts both
2216
2976
  // rules below; the refusal files that request, as the Write/Edit config gate does.
@@ -2220,7 +2980,7 @@ function evaluateHook(input, specsDir, opts) {
2220
2980
  pendingApprovals.push(r);
2221
2981
  return null;
2222
2982
  }
2223
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${why} — an out-of-band approval that includes config-write is required (A-SPEC-728)`
2983
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), permissionDecisionReason: `[Holmes-Kit] ${why} — an out-of-band approval that includes config-write is required (A-SPEC-728)`
2224
2984
  + hintOrRoute({ kind: 'config-write', target: command, why }) }; // A-SPEC-792.5
2225
2985
  };
2226
2986
  let configWriteLifted = false;
@@ -2241,7 +3001,7 @@ function evaluateHook(input, specsDir, opts) {
2241
3001
  if (act && act.includes(write_target_1.PROJECT_CAPS_LABEL)) {
2242
3002
  const onDisk = (0, project_caps_1.readProjectCaps)(opts.projectRoot);
2243
3003
  if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2244
- 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)` };
3004
+ return { permissionDecision: 'deny', refusal: 'cap.run-fixed', 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)` };
2245
3005
  }
2246
3006
  if (!(0, project_caps_1.capsAtWidest)(onDisk)) {
2247
3007
  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)`);
@@ -2415,7 +3175,7 @@ function evaluateHook(input, specsDir, opts) {
2415
3175
  // @implements A-SPEC-774.10 — a legacy policy outside a run keeps the 0.35.25 freedom for WRITE_OTHER.
2416
3176
  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 });
2417
3177
  if (issue)
2418
- return { permissionDecision: 'deny', permissionDecisionReason: issue };
3178
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: issue };
2419
3179
  }
2420
3180
  }
2421
3181
  // @implements A-SPEC-774.23 — a scoped run's shell writes stay inside its plan, as its file tool writes do.
@@ -2424,7 +3184,7 @@ function evaluateHook(input, specsDir, opts) {
2424
3184
  .filter((c) => judgeCand(c, [opts.projectRoot]) === 'in').map((c) => path.resolve(opts.projectRoot, judgedPath(c)));
2425
3185
  const outside = (0, run_plan_scope_1.planScopeRefusal)({ projectRoot: opts.projectRoot, specsDir, env: process.env, cwd: input.cwd, sessionId: input.session_id }, inProject);
2426
3186
  if (outside)
2427
- return { permissionDecision: 'deny', permissionDecisionReason: outside };
3187
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: outside };
2428
3188
  }
2429
3189
  // @implements A-SPEC-747.4 — a write whose destination or command word is computed at run time (xargs input, find's
2430
3190
  // `{}`, a variable, an IFS join) never reached the literal-destination rule above: 19 such writes to code files
@@ -2446,7 +3206,7 @@ function evaluateHook(input, specsDir, opts) {
2446
3206
  computedWrite = 'computed command';
2447
3207
  }
2448
3208
  if (computedWrite !== null && readSpecsSync(specsDir).length > 0) {
2449
- return { permissionDecision: 'deny', permissionDecisionReason: `${SHELL_CODE_WRITE_REASON} (its target is computed at run time: ${computedWrite}, A-SPEC-747.4)` };
3209
+ return { permissionDecision: 'deny', refusal: 'shell.code-write', permissionDecisionReason: `${SHELL_CODE_WRITE_REASON} (its target is computed at run time: ${computedWrite}, A-SPEC-747.4)` };
2450
3210
  }
2451
3211
  const codeList = distinct([...candidates, ...interpreterWrites.flatMap(expandInterp)].filter(governedCode));
2452
3212
  // Rule 43: only a governed project judges this list — an ungoverned one was refused for nothing it would check.
@@ -2459,7 +3219,7 @@ function evaluateHook(input, specsDir, opts) {
2459
3219
  // has never depended on governance); code candidates stay dormant on a spec-less repo.
2460
3220
  const UNRESOLVED_BASE_DENY = '[Holmes-Kit] shell write to a relative path cannot be located: an earlier cd has a target the gate cannot resolve statically (dynamic argument) — use an absolute path, the gated Write/Edit tools, or out-of-band approval';
2461
3221
  if (cfgVerdicts.includes('unknown')) {
2462
- return { permissionDecision: 'deny', permissionDecisionReason: UNRESOLVED_BASE_DENY };
3222
+ return { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: UNRESOLVED_BASE_DENY };
2463
3223
  }
2464
3224
  if (codeVerdicts.includes('in') || codeVerdicts.includes('unknown')) {
2465
3225
  // @implements A-SPEC-550.1 — governance is "specs EXIST", not "a spec is approved". The old
@@ -2470,15 +3230,16 @@ function evaluateHook(input, specsDir, opts) {
2470
3230
  const governed = readSpecsSync(specsDir).length > 0;
2471
3231
  if (governed) {
2472
3232
  return codeVerdicts.includes('in')
2473
- ? { permissionDecision: 'deny', permissionDecisionReason: SHELL_CODE_WRITE_REASON }
2474
- : { permissionDecision: 'deny', permissionDecisionReason: UNRESOLVED_BASE_DENY };
3233
+ ? { permissionDecision: 'deny', refusal: 'shell.code-write', permissionDecisionReason: SHELL_CODE_WRITE_REASON }
3234
+ : { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: UNRESOLVED_BASE_DENY };
2475
3235
  }
2476
3236
  }
2477
3237
  }
2478
3238
  // @implements A-SPEC-790.8 — a carried approval was spent by the first reading; only the others are spent here.
2479
3239
  const spendable = pendingApprovals.flatMap((p) => (p.source === 'carried' ? [] : [p]));
2480
3240
  if (spendable.length > 0) {
2481
- const deny = (why) => ({ permissionDecision: 'deny',
3241
+ // A-SPEC-245.24 (item 1) — a single-use approval that cannot be spent once needs a new one from the person
3242
+ const deny = (why) => ({ permissionDecision: 'deny', refusal: 'approval.required',
2482
3243
  permissionDecisionReason: `[Holmes-Kit] ${why}` });
2483
3244
  // @implements A-SPEC-477.1 — a later invalid approval must not spend an earlier valid one.
2484
3245
  // Validate the complete set, then check all replays and append under ONE existing ledger hold.
@@ -2489,41 +3250,58 @@ function evaluateHook(input, specsDir, opts) {
2489
3250
  const ledgerFile = (0, ledger_store_2.writerChainFile)(path.join(opts.projectRoot, '.ax', 'ledger'));
2490
3251
  const unique = new Map(spendable.filter(({ approval }) => !!approval.nonce)
2491
3252
  .map(({ approval }) => [approval.nonce, approval]));
2492
- const check = () => {
3253
+ // A read: a conflict or a replay denies here with its reason; the spend itself is the settlement's, below
3254
+ try {
2493
3255
  const conflict = (0, ledger_store_2.ledgerConflictReason)(path.dirname(ledgerFile));
2494
3256
  if (conflict)
2495
- return conflict;
3257
+ return deny(conflict);
2496
3258
  const consumed = (0, ledger_store_2.nonceConsumedIn)(ledgerFile);
2497
3259
  if ([...unique.keys()].some(consumed))
2498
- return 'single-use approval already consumed (replay)';
2499
- return null;
2500
- };
2501
- try {
2502
- const chain = new provenance_chain_1.ProvenanceChain(ledgerFile);
2503
- const failure = unique.size === 0 ? check() : (0, ledger_lock_1.withLedgerLock)(ledgerFile, () => {
2504
- const reason = check();
2505
- if (reason)
2506
- return reason;
2507
- for (const [nonce, acting] of unique)
2508
- chain.appendInsideLock({
2509
- ts: nowTs, actor: acting.actor, kind: 'nonce-consumed',
2510
- summary: `consumed single-use approval for: ${(0, provenance_chain_1.redactTarget)('command', command)}`.slice(0, 200),
2511
- inputs: [(0, provenance_chain_1.nonceFingerprint)(nonce)], rationale: acting.rationale, authorization: (0, provenance_chain_1.authorizationRef)(acting.actor, acting.token),
2512
- });
2513
- return null;
2514
- }, { onStaleBreak: chain.staleBreakRecorder() });
2515
- if (failure)
2516
- return deny(failure);
3260
+ return deny('single-use approval already consumed (replay)');
2517
3261
  }
2518
3262
  catch (err) {
2519
- return deny(`could not obtain exclusive ledger access to spend the single-use approval (${err instanceof Error ? err.message : String(err)})`);
3263
+ return deny(`could not read the ledger to judge the single-use approval (${err instanceof Error ? err.message : String(err)})`);
2520
3264
  }
3265
+ // @implements A-SPEC-245.9 (1b-2) — every single-use approval of this act, a grant's or the environment's, is
3266
+ // spent when the decision is final, on the hook's main thread, through spendApprovals (GrantSettlement.settle)
3267
+ if (opts.settlement === undefined && unique.size > 0)
3268
+ return deny('no settlement holds this single-use approval — it cannot be spent once, so it is denied');
2521
3269
  for (const { source, approval } of spendable) {
2522
- if (source === 'grant' && approval.nonce)
2523
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, approval.nonce);
3270
+ if (!approval.nonce)
3271
+ continue;
3272
+ if (source === 'grant')
3273
+ opts.settlement?.hold(opts.projectRoot, approval.nonce, approval); // A-SPEC-245.2, A-SPEC-245.4
3274
+ else
3275
+ opts.settlement?.holdEnv(opts.projectRoot, approval.nonce, approval, `consumed single-use approval for: ${(0, provenance_chain_1.redactTarget)('command', command)}`.slice(0, 200));
2524
3276
  }
2525
3277
  opts.onApprovalsSpent?.(spendable.map(({ approval }) => approval));
2526
3278
  }
3279
+ // @implements A-SPEC-792.32 — the one place a staging approval is recorded: every Bash gate has passed, the act is
3280
+ // allowed. The autonomous record is the verdict's proven pairs; the person path's names only its add segments.
3281
+ if (autonomousStaging !== null) {
3282
+ const a = autonomousStaging;
3283
+ const sha = (t) => crypto.createHash('sha256').update(t).digest('hex');
3284
+ try {
3285
+ new ledger_store_1.FileLedgerStore(path.join(opts.projectRoot, '.ax', 'ledger')).append({
3286
+ ts: nowTs, actor: `full-autonomy:${a.scope}`, kind: 'autonomous-shell-approved',
3287
+ summary: `governance staging approved by machine conditions (${a.paths.length} path(s))`,
3288
+ inputs: [`command:${sha(command)}`, `paths:${sha(a.paths.join('\n'))}`, `count:${a.paths.length}`, ...Object.entries(a.conditions).map(([k, x]) => `${k}:${x}`)],
3289
+ rationale: 'A-SPEC-792.28: grammar, provenance, integrity and reversibility each held',
3290
+ });
3291
+ }
3292
+ catch { /* the act is approved by its conditions; the audit row is best effort like the other gate records */ }
3293
+ (0, approval_queue_1.appendQueueEvent)(opts.projectRoot, { event: 'auto-approved', id: (0, approval_queue_1.approvalRequestId)('shell', command), kind: 'shell', target: command.slice(0, 500) });
3294
+ try {
3295
+ require('../governance/spec-seam').recordProvenGrant(opts.projectRoot, specsDir, a.proven);
3296
+ }
3297
+ catch { /* unrecorded: the seam then reports the staged change, which fails closed at Stop */ }
3298
+ }
3299
+ if (personStaging) {
3300
+ try {
3301
+ require('../governance/spec-seam').recordGrantedStaging(opts.projectRoot, specsDir, command, shellBase);
3302
+ }
3303
+ catch { /* unrecorded: the seam then reports the staged change, which fails closed at Stop */ }
3304
+ }
2527
3305
  // @implements A-SPEC-774.13 — an allowed interactive launch inherits this session's authority variables; a hook
2528
3306
  // cannot change a command's environment, so it names them (never their values) and gives the operator's re-run.
2529
3307
  if (agentCliLaunch(command) && !(0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
@@ -2544,15 +3322,17 @@ function evaluateHook(input, specsDir, opts) {
2544
3322
  const foreign = input.tool_input.foreign_paths ?? (0, write_target_2.foreignMcpPaths)(input.tool_name, input.tool_input);
2545
3323
  if (foreign && (foreign.paths.length > 0 || foreign.unresolvable.length > 0)) {
2546
3324
  if (foreign.unresolvable.length > 0) {
2547
- 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)` };
3325
+ 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)`, refusal: 'target.unresolvable' }; // A-SPEC-245.23
2548
3326
  }
2549
3327
  if (foreign.paths.length > 64) {
2550
- 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)` };
3328
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} names more than 64 paths — too many to judge, refused rather than judged (A-SPEC-776)` };
2551
3329
  }
2552
3330
  for (const fp of foreign.paths) {
2553
3331
  const v = evaluateHook({ tool_name: 'Write', tool_input: { file_path: fp, content: '' }, ...(input.cwd === undefined ? {} : { cwd: input.cwd }) }, specsDir, opts);
2554
3332
  if (v.permissionDecision === 'deny') {
2555
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} → ${fp.slice(0, 120)}: ${v.permissionDecisionReason ?? ''}` };
3333
+ // A-SPEC-245.23 (item 3) — the nested verdict's code, from its own site or its own text, before the path is prefixed
3334
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} → ${fp.slice(0, 120)}: ${v.permissionDecisionReason ?? ''}`,
3335
+ refusal: (0, refusal_codes_1.refusalFor)(v.permissionDecisionReason ?? '', v.refusal).code };
2556
3336
  }
2557
3337
  }
2558
3338
  }
@@ -2576,6 +3356,7 @@ function evaluateHook(input, specsDir, opts) {
2576
3356
  // has to recognise.
2577
3357
  return {
2578
3358
  permissionDecision: 'deny',
3359
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2579
3360
  permissionDecisionReason: '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)',
2580
3361
  };
2581
3362
  }
@@ -2590,6 +3371,7 @@ function evaluateHook(input, specsDir, opts) {
2590
3371
  if (writesCode && !p) {
2591
3372
  return {
2592
3373
  permissionDecision: 'deny',
3374
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2593
3375
  permissionDecisionReason: '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)'
2594
3376
  + ' — there is no way to check whether an unnamed file overwrites an approved spec, so it is not allowed.',
2595
3377
  };
@@ -2615,7 +3397,7 @@ function evaluateHook(input, specsDir, opts) {
2615
3397
  // is not bounded by a count at all; it ends at the filesystem root, which always terminates.
2616
3398
  // `canonicalPath` (realpathSync.native), not the JS realpath: the root arrives canonicalised by
2617
3399
  // root.ts, which expands Windows 8.3 aliases; the JS realpath does not. Measured 2026-08-23 on
2618
- // the built hook — an in-project target spelled through `%TEMP%`'s alias (`C:\Users\SUNGNA~1\…`)
3400
+ // the built hook — an in-project target spelled through `%TEMP%`'s alias (`C:\Users\FIRSTL~1\…`)
2619
3401
  // resolved to a string the long-name root did not contain, and took the "outside → allow" exit
2620
3402
  // below. Both sides must go through the one canonicaliser, or an alias is a free pass.
2621
3403
  // @implements A-SPEC-728 (rule 37) — the nearest ancestor that resolves is found by halving (whether an ancestor
@@ -2669,6 +3451,7 @@ function evaluateHook(input, specsDir, opts) {
2669
3451
  // nothing to govern"; an undecidable target is refused, not allowed.
2670
3452
  return {
2671
3453
  permissionDecision: 'deny',
3454
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2672
3455
  permissionDecisionReason: '[Holmes-Kit] a network path (UNC) cannot be resolved to a local filesystem identity,'
2673
3456
  + ' so it cannot be judged inside or outside the project — an untellable target is not allowed.'
2674
3457
  + ' Put the project on a local drive, or use a drive-letter-mapped path.',
@@ -2722,11 +3505,11 @@ function evaluateHook(input, specsDir, opts) {
2722
3505
  return { permissionDecision: 'allow' };
2723
3506
  const userResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2724
3507
  if (userResolved === undefined) {
2725
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${userKind} is a hook/approval config — it can forge HOLMES_APPROVAL or turn governance off, so an out-of-band approval that includes config-write is required`
3508
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), permissionDecisionReason: `[Holmes-Kit] ${userKind} is a hook/approval config — it can forge HOLMES_APPROVAL or turn governance off, so an out-of-band approval that includes config-write is required`
2726
3509
  + hintOrRoute({ kind: 'config-write', target: norm, why: `writing ${userKind}` }) }; // A-SPEC-792.5
2727
3510
  }
2728
3511
  if (userResolved.source === 'grant' && userResolved.approval.nonce)
2729
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, userResolved.approval.nonce);
3512
+ opts.settlement?.hold(opts.projectRoot, userResolved.approval.nonce, userResolved.approval); // A-SPEC-245.2
2730
3513
  return { permissionDecision: 'allow' };
2731
3514
  }
2732
3515
  norm = canonical;
@@ -2739,6 +3522,7 @@ function evaluateHook(input, specsDir, opts) {
2739
3522
  if (norm.includes('\u0000')) {
2740
3523
  return {
2741
3524
  permissionDecision: 'deny',
3525
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2742
3526
  permissionDecisionReason: '[Holmes-Kit] the edit target path contains a NUL byte, so which file it is cannot be judged'
2743
3527
  + ' — a target whose name cannot be pinned down is not allowed.',
2744
3528
  };
@@ -2767,13 +3551,15 @@ function evaluateHook(input, specsDir, opts) {
2767
3551
  if (rolesResolved === undefined) {
2768
3552
  return {
2769
3553
  permissionDecision: 'deny',
3554
+ refusal: routeCode('approval.required'), // A-SPEC-245.24
2770
3555
  permissionDecisionReason: '[Holmes-Kit] the role policy (.ax/roles/) defines the very authority this gate enforces —'
2771
3556
  + ' an agent cannot change it itself. An out-of-band approval that includes config-write is required.'
2772
3557
  + hintOrRoute({ kind: 'config-write', target: norm, why: 'writing the role policy (.ax/roles/)' }), // A-SPEC-792.5
2773
3558
  };
2774
3559
  }
3560
+ // A-SPEC-245.2: held, not spent — the protected-directory branch below resolves this same grant again
2775
3561
  if (rolesResolved.source === 'grant' && rolesResolved.approval.nonce)
2776
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, rolesResolved.approval.nonce);
3562
+ opts.settlement?.hold(opts.projectRoot, rolesResolved.approval.nonce, rolesResolved.approval);
2777
3563
  }
2778
3564
  // @implements A-SPEC-191 §22 — ask by identity. A spelling regex was defeated by a single in-project link.
2779
3565
  // @implements A-SPEC-728 — a project that itself sits in a harness home still protects those files.
@@ -2789,11 +3575,11 @@ function evaluateHook(input, specsDir, opts) {
2789
3575
  // @implements A-SPEC-193 §8 — name what was blocked. Baking a list into the sentence makes the
2790
3576
  // wording false as harnesses grow (REQ-155: a diagnosis that points at the wrong file has negative value).
2791
3577
  const kindName = configKind ?? (0, write_target_2.protectedKindOf)(opts.projectRoot, norm) ?? 'config';
2792
- 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`
3578
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), 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`
2793
3579
  + hintOrRoute({ kind: 'config-write', target: norm, why: `writing ${kindName}` }) }; // A-SPEC-792.5
2794
3580
  }
2795
3581
  if (cfgResolved.source === 'grant' && cfgResolved.approval.nonce)
2796
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, cfgResolved.approval.nonce);
3582
+ opts.settlement?.hold(opts.projectRoot, cfgResolved.approval.nonce, cfgResolved.approval); // A-SPEC-245.2
2797
3583
  }
2798
3584
  // @implements A-SPEC-476.3 — the owner's caps in ax.config.json narrow this agent: raising or removing one is the owner's
2799
3585
  // act (owner decision 2026-10-19), lowering stays free, and in a run no write changes one.
@@ -2801,16 +3587,16 @@ function evaluateHook(input, specsDir, opts) {
2801
3587
  const capsAct = projectCapsWriteAct(opts.projectRoot, input);
2802
3588
  if (capsAct !== null) {
2803
3589
  if ((0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
2804
- 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)` };
3590
+ return { permissionDecision: 'deny', refusal: 'cap.run-fixed', 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)` };
2805
3591
  }
2806
3592
  if (capsAct !== 'lowered') {
2807
3593
  const capsResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2808
3594
  if (capsResolved === undefined) {
2809
- 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)`
3595
+ return { permissionDecision: 'deny', refusal: routeCode('approval.required'), 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)`
2810
3596
  + hintOrRoute({ kind: 'config-write', target: norm, why: `raising a project cap (${capsAct})` }) }; // A-SPEC-792.5
2811
3597
  }
2812
3598
  if (capsResolved.source === 'grant' && capsResolved.approval.nonce)
2813
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, capsResolved.approval.nonce);
3599
+ opts.settlement?.hold(opts.projectRoot, capsResolved.approval.nonce, capsResolved.approval); // A-SPEC-245.2
2814
3600
  }
2815
3601
  }
2816
3602
  }
@@ -2836,7 +3622,7 @@ function evaluateHook(input, specsDir, opts) {
2836
3622
  // legacy reading uses the same value.
2837
3623
  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 });
2838
3624
  if (specRoleIssue)
2839
- return { permissionDecision: 'deny', permissionDecisionReason: specRoleIssue };
3625
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: specRoleIssue };
2840
3626
  }
2841
3627
  // F1: a spec cannot SELF-APPROVE. `status: approved` is what unlocks every downstream gate
2842
3628
  // (phaseCheck trusts the on-disk status). If the incoming write promotes a spec to approved and it
@@ -2854,7 +3640,7 @@ function evaluateHook(input, specsDir, opts) {
2854
3640
  const specWriteCovered = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'spec-write', target: norm }, nowTs);
2855
3641
  if (incomingSetsApproved(input.tool_input) && !specWriteCovered) {
2856
3642
  if (!onDiskApproved) {
2857
- return { permissionDecision: 'deny', permissionDecisionReason: registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
3643
+ return { permissionDecision: 'deny', refusal: 'spec.protected', permissionDecisionReason: registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
2858
3644
  }
2859
3645
  }
2860
3646
  // @implements A-SPEC-728 (rule 39) — and judged on the RESULT too: an Edit of `draft` into `approved` carries no
@@ -2876,7 +3662,7 @@ function evaluateHook(input, specsDir, opts) {
2876
3662
  catch { /* not a spec the store would read as approved */ }
2877
3663
  }
2878
3664
  if (approvedAfter || edited === TOO_LARGE) {
2879
- return { permissionDecision: 'deny', permissionDecisionReason: edited === TOO_LARGE
3665
+ return { permissionDecision: 'deny', refusal: edited === TOO_LARGE ? 'gate.unjudgeable' : 'spec.protected', permissionDecisionReason: edited === TOO_LARGE
2880
3666
  ? `[Holmes-Kit] a spec edit too large to judge (its result passes ${EDIT_RESULT_MAX / (1024 * 1024)} MiB, or its edits pass ${EDIT_REPLACEMENTS_MAX / (1024 * 1024)} M replacements or ${EDIT_WORK_MAX / (1024 * 1024)} MiB of work) — refused rather than judged (A-SPEC-728)`
2881
3667
  : registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
2882
3668
  }
@@ -2890,9 +3676,113 @@ function evaluateHook(input, specsDir, opts) {
2890
3676
  if (onDiskApproved && !specWriteCovered) {
2891
3677
  return {
2892
3678
  permissionDecision: 'deny',
3679
+ refusal: 'spec.protected', // A-SPEC-245.24
2893
3680
  permissionDecisionReason: registry_1.MESSAGES.SEAL_APPROVED_SPEC_MUTATION(path.basename(p, '.md'), undefined, 'A-SPEC-132'),
2894
3681
  };
2895
3682
  }
3683
+ // @implements A-SPEC-222.10 — H-B: a retired spec keeps the seal it was approved with, and its successor and anchor
3684
+ // moves are judged on it, so its sealed content and seal fields are as protected as an approved spec's (the rule
3685
+ // above ran only for `approved`, and an Edit rewrote an outdated body together with a recomputed approved_digest)
3686
+ if (!specWriteCovered) {
3687
+ let disk = null;
3688
+ try {
3689
+ disk = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null;
3690
+ }
3691
+ catch {
3692
+ disk = null;
3693
+ }
3694
+ let before = null;
3695
+ try {
3696
+ before = disk !== null ? (0, spec_parser_1.parseSpec)(disk) : null;
3697
+ }
3698
+ catch {
3699
+ before = null;
3700
+ }
3701
+ const edited = editedResult(disk, input.tool_input);
3702
+ let after = null;
3703
+ if (typeof edited === 'string') {
3704
+ try {
3705
+ after = (0, spec_parser_1.parseSpec)(edited);
3706
+ }
3707
+ catch {
3708
+ after = null;
3709
+ }
3710
+ }
3711
+ // @implements A-SPEC-222.12 — N2: and its status, both ways: an edit that leaves `outdated` (to rewrite the body
3712
+ // and come back) or enters it (a retirement is spec_retire's) is refused like a body change
3713
+ // A-SPEC-222.13 (low b): a new file written as outdated enters it too
3714
+ // A-SPEC-222.14 (low b): new means no file on disk; one whose YAML does not parse keeps its `status:` line
3715
+ // @implements A-SPEC-222.15 (item 2) — read from the first frontmatter block only, a trailing comment allowed (a
3716
+ // body line retired a spec by hand, and refused a legitimate repair)
3717
+ const { lenientFrontmatter } = require('../spec/succession-guard');
3718
+ const beforeOutdated = before !== null ? before.status === 'outdated'
3719
+ : disk !== null ? lenientFrontmatter(disk)?.status === 'outdated' : false;
3720
+ const statusMoves = after !== null && beforeOutdated !== (after.status === 'outdated');
3721
+ if (statusMoves) {
3722
+ return {
3723
+ permissionDecision: 'deny',
3724
+ refusal: 'spec.protected',
3725
+ permissionDecisionReason: `[Holmes-Kit] ${path.basename(p, '.md')}: a spec leaves or enters \`outdated\` only through the tools — spec_retire retires it, spec_unseal reopens it with a person's approval (A-SPEC-222.12)`,
3726
+ };
3727
+ }
3728
+ // @implements A-SPEC-222.15 (item 1) — a retired spec whose YAML does not parse has no `before` to compare: its
3729
+ // repair is allowed only back to a seal the trusted ledger records (222.14 let a rewrite with a recomputed digest
3730
+ // through here)
3731
+ if (before === null && disk !== null && beforeOutdated) {
3732
+ const id = path.basename(p, '.md');
3733
+ let toSeal = false;
3734
+ if (edited !== TOO_LARGE && after !== null) {
3735
+ const digest = (0, spec_digest_1.specDigest)(after);
3736
+ if (after.frontmatter.approved_digest === digest) {
3737
+ try {
3738
+ toSeal = require('../governance/recorded-pairs').recordedPairsPort(opts.projectRoot).approved(id, digest);
3739
+ }
3740
+ catch {
3741
+ toSeal = false;
3742
+ }
3743
+ }
3744
+ }
3745
+ if (!toSeal) {
3746
+ return {
3747
+ permissionDecision: 'deny',
3748
+ refusal: 'spec.protected',
3749
+ permissionDecisionReason: `[Holmes-Kit] ${id} is retired (outdated) and its frontmatter does not parse: a repair is allowed only back to the seal the ledger records for it, whole and parsing — a change goes through spec_unseal and a person (A-SPEC-222.15)`,
3750
+ };
3751
+ }
3752
+ }
3753
+ if (before !== null && before.status === 'outdated') {
3754
+ const sealOfSpec = (s) => JSON.stringify(spec_digest_1.SEAL_FIELDS.map((k) => s.frontmatter[k] ?? null));
3755
+ const changed = edited === TOO_LARGE || (after !== null && ((0, spec_digest_1.specDigest)(after) !== (0, spec_digest_1.specDigest)(before) || sealOfSpec(after) !== sealOfSpec(before)));
3756
+ if (changed) {
3757
+ return {
3758
+ permissionDecision: 'deny',
3759
+ refusal: 'spec.protected',
3760
+ permissionDecisionReason: `[Holmes-Kit] ${path.basename(p, '.md')} is retired (outdated): its sealed content and seal fields are kept as approved — successors and anchor moves are judged on them; a change goes through spec_unseal and a person (A-SPEC-222.10)`,
3761
+ };
3762
+ }
3763
+ }
3764
+ }
3765
+ // @implements A-SPEC-222.8 — N2: who succeeds a spec is the tools' record, never a hand edit (the route is spec_retire)
3766
+ // @implements A-SPEC-222.9 — SD1 1: judged in succession-guard; the gate only asks
3767
+ {
3768
+ let disk = null;
3769
+ try {
3770
+ disk = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null;
3771
+ }
3772
+ catch {
3773
+ disk = null;
3774
+ }
3775
+ const edited = editedResult(disk, input.tool_input);
3776
+ const { successionFieldEditRefusal } = require('../spec/succession-guard');
3777
+ const why = successionFieldEditRefusal(disk, edited === TOO_LARGE ? 'too-large' : edited, path.basename(p, '.md'), typeof input.tool_input.new_string === 'string' ? input.tool_input.new_string : undefined);
3778
+ if (why !== null) {
3779
+ return {
3780
+ permissionDecision: 'deny',
3781
+ refusal: 'spec.protected', // A-SPEC-245.24
3782
+ permissionDecisionReason: why,
3783
+ };
3784
+ }
3785
+ }
2896
3786
  // @implements A-SPEC-792.9 — a write that would leave the spec unreadable is refused with the parse error, whatever
2897
3787
  // approval is held. G0 HB-r5: a Write broke REQ-100's YAML, the repair Edit was then refused as a new REQ (below),
2898
3788
  // and the run ended asking a person. A file already unreadable on disk is judged as before.
@@ -2918,6 +3808,7 @@ function evaluateHook(input, specsDir, opts) {
2918
3808
  if (broken !== null && (disk === null || parseError(disk) === null)) {
2919
3809
  return {
2920
3810
  permissionDecision: 'deny',
3811
+ refusal: 'spec.unreadable', // A-SPEC-245.24
2921
3812
  permissionDecisionReason: `[Holmes-Kit] the write would leave ${path.basename(p, '.md')} unreadable to the spec store (${broken}) — nothing was written; fix the frontmatter in this same write (a value holding ' or : goes in double quotes, or in a >- block)`,
2922
3813
  };
2923
3814
  }
@@ -2930,6 +3821,7 @@ function evaluateHook(input, specsDir, opts) {
2930
3821
  if (newReq !== null) {
2931
3822
  return {
2932
3823
  permissionDecision: 'deny',
3824
+ refusal: 'spec.not-approved', // A-SPEC-245.24 — the remedy is the tool, not a person
2933
3825
  permissionDecisionReason: `[Holmes-Kit] ${newReq} — a new REQ is created only by spec_create(type='REQ') or spec_slice_init with triage_evidence from requirement_triage(persist:true) (A-SPEC-729). Editing an existing REQ's body stays free.`,
2934
3826
  };
2935
3827
  }
@@ -2942,6 +3834,7 @@ function evaluateHook(input, specsDir, opts) {
2942
3834
  if (assessment.level === 'hard-hitl' && !(0, risk_gate_1.isValidApproval)(opts.approval)) {
2943
3835
  return {
2944
3836
  permissionDecision: 'deny',
3837
+ refusal: 'spec.protected', // A-SPEC-245.24 — the reasons quote spec text; the code is the site's
2945
3838
  permissionDecisionReason: `[Holmes-Kit] high blast-radius spec edit: ${assessment.reasons.join('; ')} — requires out-of-band approval`,
2946
3839
  };
2947
3840
  }
@@ -2960,7 +3853,7 @@ function evaluateHook(input, specsDir, opts) {
2960
3853
  const otherPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2961
3854
  // @implements A-SPEC-774.10 — read strictly only in a run or under a vocabulary-2 policy.
2962
3855
  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 });
2963
- return otherIssue ? { permissionDecision: 'deny', permissionDecisionReason: otherIssue } : { permissionDecision: 'allow' };
3856
+ return otherIssue ? { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: otherIssue } : { permissionDecision: 'allow' };
2964
3857
  }
2965
3858
  // Read specs synchronously via a fresh walk (hook must be sync)
2966
3859
  const specs = readSpecsSync(specsDir);
@@ -3010,6 +3903,7 @@ function evaluateHook(input, specsDir, opts) {
3010
3903
  if (violations.length > 0) {
3011
3904
  return {
3012
3905
  permissionDecision: 'deny',
3906
+ refusal: 'architecture.violation', // A-SPEC-245.24
3013
3907
  permissionDecisionReason: '[Holmes-Kit] structural-constraint violation — a shape an approved C-SPEC forbids:\n'
3014
3908
  + violations.map((v) => ' - ' + v).join('\n')
3015
3909
  + '\n' + proposed_content_1.CSPEC_GATE_LIMITS,
@@ -3036,12 +3930,12 @@ function evaluateHook(input, specsDir, opts) {
3036
3930
  previous = fs.readFileSync(norm, 'utf8');
3037
3931
  }
3038
3932
  catch {
3039
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] cannot read ${relPath} to judge its anchors — the write is refused rather than judged by its own payload` };
3933
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] cannot read ${relPath} to judge its anchors — the write is refused rather than judged by its own payload`, refusal: 'target.unresolvable' }; // A-SPEC-245.23
3040
3934
  }
3041
3935
  }
3042
3936
  const edited = editedResult(previous ?? null, ti166);
3043
3937
  if (edited === TOO_LARGE) {
3044
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] the result of this write to ${relPath} is too large to judge its anchors` };
3938
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] the result of this write to ${relPath} is too large to judge its anchors`, refusal: 'gate.unjudgeable' }; // A-SPEC-245.23
3045
3939
  }
3046
3940
  // An edit that does not apply: the incoming fragments are judged (over-inclusion is the safe direction).
3047
3941
  const leaves = edited ?? [ti166.content, ti166.new_string, ...(Array.isArray(ti166.edits)
@@ -3156,6 +4050,7 @@ function evaluateHook(input, specsDir, opts) {
3156
4050
  ? ` (${(0, tspec_state_1.listOrCount)(hidden.flatMap(([, ids]) => ids), tspec_state_1.ID_BUDGET, 'items', Infinity)} require individual verification due to distinct reasons)` : '');
3157
4051
  return {
3158
4052
  permissionDecision: 'deny',
4053
+ refusal: 'spec.not-approved', // A-SPEC-245.24
3159
4054
  permissionDecisionReason: `[Holmes-Kit Gate Refusal] Target specification ${(0, tspec_state_1.listOrCount)(unapproved, tspec_state_1.ID_BUDGET, 'spec(s)', Infinity)} is not approved`
3160
4055
  + ` — Claiming unapproved specifications in existing or new files is prohibited.${why}`,
3161
4056
  };
@@ -3192,7 +4087,7 @@ function evaluateHook(input, specsDir, opts) {
3192
4087
  if (ungovernedPolicy !== null) {
3193
4088
  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 });
3194
4089
  if (issue)
3195
- return { permissionDecision: 'deny', permissionDecisionReason: issue };
4090
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: issue };
3196
4091
  }
3197
4092
  return { permissionDecision: 'allow' };
3198
4093
  }
@@ -3222,7 +4117,7 @@ function evaluateHook(input, specsDir, opts) {
3222
4117
  // second id passed). The shared parser is consumed through `stripStringLiterals`, the same
3223
4118
  // preprocessing the claim gate got in S-504.1, so a fixture string anchor no longer governs.
3224
4119
  // Disk-anchor precedence is preserved as a set: a non-empty disk set governs, else the payload.
3225
- const { anchorSpecIds: govAnchorIds, stripStringLiterals: govStrip } = require('../rtm/anchor-ids');
4120
+ const { anchorSpecIdsFor } = require('../rtm/anchor-ids');
3226
4121
  const uniq = (xs) => [...new Set(xs)];
3227
4122
  // @implements A-SPEC-529.2 — the preprocessing branches on FILE FORMAT. A-SPEC-529.1 stripped
3228
4123
  // string literals so a code fixture like `const s = "@implements A-SPEC-999"` could not become
@@ -3231,10 +4126,9 @@ function evaluateHook(input, specsDir, opts) {
3231
4126
  // 2026-09-03, a release package.json edit was refused with "A-SPEC(unspecified)". Code formats
3232
4127
  // (line-comment anchors) still strip; JSON/YAML/TOML/config and unknown extensions read raw
3233
4128
  // (over-inclusion is safe — an anchored-but-unapproved id is still refused downstream).
3234
- const GOV_CODE_EXT = /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|go|rs|java|kt|cs|cc|cxx|cpp|hh|hpp|rb|php|swift)$/i;
3235
- const govPrep = (s) => (GOV_CODE_EXT.test(relPath) ? govStrip(s) : s);
3236
- const diskGovIds = uniq(govAnchorIds(govPrep(onDiskContent)));
3237
- const payloadGovIds = uniq(govAnchorIds(govPrep([input.tool_input.content ?? '', input.tool_input.new_string ?? ''].join('\n'))));
4129
+ // @implements A-SPEC-222.8 — the per-format reading lives in anchor-ids, shared with the census and the move judgment
4130
+ const diskGovIds = uniq(anchorSpecIdsFor(relPath, onDiskContent));
4131
+ const payloadGovIds = uniq(anchorSpecIdsFor(relPath, [input.tool_input.content ?? '', input.tool_input.new_string ?? ''].join('\n')));
3238
4132
  const governingIds = diskGovIds.length > 0 ? diskGovIds : payloadGovIds;
3239
4133
  // The single "primary" id kept for message templates and phaseCheck's targetAspecId default: the
3240
4134
  // first governing id, which is exactly what `m?.[1]` used to be for a single-anchor file.
@@ -3286,7 +4180,7 @@ function evaluateHook(input, specsDir, opts) {
3286
4180
  // @implements A-SPEC-133 — the override is authorized by a token covering the code write.
3287
4181
  const codeWriteCovered = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'code-write', target: relPath }, nowTs);
3288
4182
  if (staleTarget && !codeWriteCovered) {
3289
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${staleTarget} — re-approve with spec_approve, then proceed` };
4183
+ return { permissionDecision: 'deny', refusal: 'spec.not-approved', permissionDecisionReason: `[Holmes-Kit] ${staleTarget} — re-approve with spec_approve, then proceed` };
3290
4184
  }
3291
4185
  // @implements A-SPEC-152
3292
4186
  // Role gate — BEFORE the spec gate on purpose: if this identity may not perform the action at all,
@@ -3305,7 +4199,7 @@ function evaluateHook(input, specsDir, opts) {
3305
4199
  // role-override approval lifts a role refusal. Interactively a code-write approval still lifts it (0.35.25).
3306
4200
  const roleOverride = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'role-override', target: relPath }, nowTs);
3307
4201
  if (roleIssue && !roleOverride && (roleRun || !codeWriteCovered)) {
3308
- return { permissionDecision: 'deny', permissionDecisionReason: roleIssue };
4202
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: roleIssue };
3309
4203
  }
3310
4204
  // @implements A-SPEC-134
3311
4205
  // Constitution-debt gate: after the Stop gate gave up its block cap on an unresolved constitution,
@@ -3340,6 +4234,7 @@ function evaluateHook(input, specsDir, opts) {
3340
4234
  }
3341
4235
  return {
3342
4236
  permissionDecision: 'deny',
4237
+ refusal: 'constitution.debt', // A-SPEC-245.24
3343
4238
  permissionDecisionReason: `[Holmes-Kit] constitution-debt outstanding (${debt.join(', ')}) — resolve the constitution (a clean turn clears it) before writing new code, or supply a covering approval`
3344
4239
  + (hint || ' — could not persist the approval request; ask the operator to check the project approval queue storage'),
3345
4240
  };
@@ -3349,7 +4244,49 @@ function evaluateHook(input, specsDir, opts) {
3349
4244
  // verdict, and its id flows into the refusal template (so the author sees the anchor that is
3350
4245
  // actually unsatisfied, not merely the first one on the file). An empty set keeps the prior
3351
4246
  // single call with an undefined target. Deterministic: governing-set order is document order.
3352
- const phaseTargets = governingIds.length > 0 ? governingIds : [undefined];
4247
+ // @implements A-SPEC-222.4 — the exit from a retired anchor (AU1-b, owner decision 2026-10-25): an Edit whose only
4248
+ // change moves an outdated X to its sealed superseded_by Y on @implements lines is judged under Y, not X; every other
4249
+ // gate still runs. Without it the file refused every edit, the anchor move included (run-exec.ts line 28).
4250
+ // @implements A-SPEC-222.6 — judged on the file: the edit applied to the disk text (absent, or not unique without
4251
+ // replace_all, is no result and no move), and Y must qualify as X's successor (sealed, lineage, coverage)
4252
+ const moveResult = (() => {
4253
+ if (input.tool_name !== 'Edit')
4254
+ return null;
4255
+ const o = input.tool_input.old_string;
4256
+ if (typeof o !== 'string' || o === '' || typeof input.tool_input.new_string !== 'string')
4257
+ return null;
4258
+ if (input.tool_input.replace_all !== true && onDiskContent.indexOf(o) !== onDiskContent.lastIndexOf(o))
4259
+ return null;
4260
+ const r = editedResult(onDiskContent, input.tool_input);
4261
+ return typeof r === 'string' ? r : null;
4262
+ })();
4263
+ // @implements A-SPEC-222.8 — N2: a successor counts only as the ledger recorded it (a hand-written one moves nothing)
4264
+ // @implements A-SPEC-222.9 — H1, H3, SD1 1/2: judged in succession-guard, on the trusted record the port reads
4265
+ const moveVerdict = require('../spec/succession-guard').movedAnchors({ before: onDiskContent, after: moveResult, governingIds, relPath }, { specs, resolveSpec: (id) => resolveSpec(id) ?? undefined,
4266
+ record: () => require('../governance/recorded-pairs').recordedPairsPort(projectRoot) });
4267
+ const movedAnchors = moveVerdict.moves;
4268
+ const movedTo = (id) => movedAnchors.find((m) => m.x === id)?.y ?? id;
4269
+ // @implements A-SPEC-222.4 — an allowed anchor move is on the record (no person decided it; the conditions did), on
4270
+ // every allow path after the phase gate
4271
+ const recordMovedAnchors = () => {
4272
+ for (const mv of movedAnchors) {
4273
+ try {
4274
+ // @implements A-SPEC-222.6 — F4: the successor digest and the result hash; autonomous (no person decided it),
4275
+ // directive none (none is needed: the conditions decide, with or without full autonomy). L2: once per result.
4276
+ const inputs = [relPath, mv.x, mv.y, `successor-digest:${mv.digest}`, `after-sha256:${mv.after}`, 'autonomous', 'directive:none'];
4277
+ const store = new ledger_store_1.FileLedgerStore(path.join(projectRoot, '.ax', 'ledger'));
4278
+ if (store.loadAll().some((e) => e.kind === 'anchor-moved' && JSON.stringify(e.inputs) === JSON.stringify(inputs)))
4279
+ continue;
4280
+ store.append({
4281
+ ts: nowTs, actor: 'holmes-kit', kind: 'anchor-moved', inputs,
4282
+ summary: `moved the anchor of ${relPath} from retired ${mv.x} to its sealed successor ${mv.y}`.slice(0, 200),
4283
+ rationale: 'autonomous anchor move: the edit changes only the @implements id, to the outdated spec\'s superseded_by (A-SPEC-222.4)',
4284
+ });
4285
+ }
4286
+ catch { /* the record is best effort; the gate already judged the edit */ }
4287
+ }
4288
+ };
4289
+ const phaseTargets = governingIds.length > 0 ? [...new Set(governingIds.map(movedTo))] : [undefined];
3353
4290
  let failedTarget;
3354
4291
  let res = (0, phase_1.phaseCheck)(action, { specs, targetAspecId: phaseTargets[0] });
3355
4292
  for (const tid of phaseTargets) {
@@ -3372,8 +4309,10 @@ function evaluateHook(input, specsDir, opts) {
3372
4309
  const prescriptiveGuide = ` — Next Action (DO NOT write workaround scripts in /tmp): Step 1: Call 'spec_next({})' to verify slice state. Step 2: Call 'spec_approve({ id: "${targetSpecId}" })' to seal spec. Step 3: Ensure '// @implements ${targetSpecId}' is on line 1 of target file.`;
3373
4310
  return {
3374
4311
  permissionDecision: 'deny',
4312
+ refusal: 'spec.not-approved', // A-SPEC-245.24 — the phase gate's refusal: no approved chain for the target
3375
4313
  permissionDecisionReason: `[Holmes-Kit Gate Refusal] ${res.remediation?.message} -> ${res.remediation?.next_action} (${res.remediation?.discipline})${prescriptiveGuide}`
3376
- + (lost ? `\n${governance_history_1.GOVERNANCE_LOST_HINT}` : ''),
4314
+ + (lost ? `\n${governance_history_1.GOVERNANCE_LOST_HINT}` : '')
4315
+ + (moveVerdict.note ? `\n[Holmes-Kit] ${moveVerdict.note}` : ''), // A-SPEC-222.9 — the ignored record is named
3377
4316
  };
3378
4317
  }
3379
4318
  // @implements A-SPEC-508.1
@@ -3436,7 +4375,7 @@ function evaluateHook(input, specsDir, opts) {
3436
4375
  if (afterSites.length > beforeSites.length && others.length > 0) {
3437
4376
  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`;
3438
4377
  if (writeClassify.strict)
3439
- return { permissionDecision: 'deny', permissionDecisionReason: why };
4378
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: why };
3440
4379
  scopeWarnings = [scopeWarnings, why].filter(Boolean).join('\n');
3441
4380
  }
3442
4381
  }
@@ -3448,6 +4387,7 @@ function evaluateHook(input, specsDir, opts) {
3448
4387
  .map((f) => `${relPath} is anchored to ${f.id} but falls outside its 'Files to Touch' scope (${f.reason})`).join('; ');
3449
4388
  return {
3450
4389
  permissionDecision: 'deny',
4390
+ refusal: 'scope.outside', // A-SPEC-245.24
3451
4391
  permissionDecisionReason: `[Holmes-Kit] ${failed} — extend that section first (spec edit is allowed), add it as a test under the anchored spec, or supply out-of-band approval`
3452
4392
  + (scopeWarnings ? `\n${scopeWarnings}` : ''),
3453
4393
  };
@@ -3481,8 +4421,11 @@ function evaluateHook(input, specsDir, opts) {
3481
4421
  // vouching for itself.
3482
4422
  declaredDigest: process.env.HOLMES_EVIDENCE?.trim() || null,
3483
4423
  currentHead: evidenceHead,
4424
+ ...(opts.advisory ? { advisory: opts.advisory } : {}),
3484
4425
  });
3485
4426
  if (evidenceDecision) {
4427
+ if (evidenceDecision.permissionDecision === 'allow')
4428
+ recordMovedAnchors();
3486
4429
  // @implements A-SPEC-508.1 — an allow-with-reason from the evidence gate must not swallow
3487
4430
  // the anchor-deletion warning: both ride the same reason field, newline-joined.
3488
4431
  if (scopeWarnings && evidenceDecision.permissionDecision === 'allow') {
@@ -3491,6 +4434,7 @@ function evaluateHook(input, specsDir, opts) {
3491
4434
  return evidenceDecision;
3492
4435
  }
3493
4436
  }
4437
+ recordMovedAnchors();
3494
4438
  // @implements A-SPEC-508.1 — anchor-deletion warnings ride the allow (allow-with-reason, the
3495
4439
  // same channel A-SPEC-278 uses): the write proceeds, but the RTM loss is on the record.
3496
4440
  if (scopeWarnings)
@@ -3608,9 +4552,23 @@ if (require.main === module) {
3608
4552
  const wired = wiredSpecsDir(process.argv, process.env);
3609
4553
  return path.isAbsolute(wired) ? wired : path.join(hookProjectRoot, wired);
3610
4554
  })();
4555
+ // @implements A-SPEC-245.4 — held through every pass below, settled once after the last one
4556
+ const settlement = new approval_grants_1.GrantSettlement();
4557
+ // @implements A-SPEC-333.2, A-SPEC-333.4 — the session reading these warnings; records wait for the final decision
4558
+ // below. Compression only where the compaction signal is observed (Claude Code); elsewhere only the ledger row.
4559
+ const rawFields = (rawHookInput !== null && typeof rawHookInput === 'object' ? rawHookInput : {});
4560
+ const advisoryHarness = (0, heartbeat_1.hookHarnessOf)(rawHookInput, process.env);
4561
+ const advisory = input.session_id
4562
+ ? { session: input.session_id, ...(input.agent_id ? { agent: input.agent_id } : {}), pending: [],
4563
+ compress: advisoryHarness === 'claude', harness: advisoryHarness ?? '', // A-SPEC-333.9 — the ledger names it
4564
+ ...(typeof rawFields.transcript_path === 'string' ? { transcriptPath: rawFields.transcript_path } : {}),
4565
+ ...(typeof rawFields.tool_use_id === 'string' ? { toolUseId: rawFields.tool_use_id } : {}) }
4566
+ : undefined;
3611
4567
  const judged = evaluateHook(input, specsDirWired, {
3612
4568
  projectRoot: hookProjectRoot,
3613
4569
  approval: readApprovalFromEnv(),
4570
+ settlement,
4571
+ ...(advisory ? { advisory } : {}),
3614
4572
  // Round 17: rm targets resolve from the directory the shell runs in (inside the project).
3615
4573
  resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3616
4574
  resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
@@ -3631,9 +4589,13 @@ if (require.main === module) {
3631
4589
  tool: input.tool_name, toolInput: input.tool_input })
3632
4590
  : staged;
3633
4591
  // @implements A-SPEC-778 — in a run, refusals are logged and a repeated code stops the run; elsewhere unchanged.
3634
- const out = (hookRoot.anchored
4592
+ const settled = settleVerdict((hookRoot.anchored
3635
4593
  ? (0, run_refusals_1.applyRunRefusalStop)(roled, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id, tool: input.tool_name })
3636
- : judged);
4594
+ : judged), settlement);
4595
+ // @implements A-SPEC-333.4 — an allowed `git commit` in a Claude session names the files still warned (information only)
4596
+ const reminder = advisory?.compress && settled.permissionDecision === 'allow' && input.tool_name === 'Bash'
4597
+ && (0, advisory_line_1.isGitCommit)(input.tool_input?.command ?? '') ? (0, advisory_line_1.commitReminder)(hookProjectRoot, advisory) : null;
4598
+ const out = reminder ? { ...settled, permissionDecisionReason: [settled.permissionDecisionReason, reminder].filter(Boolean).join('\n') } : settled;
3637
4599
  io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor(input.tool_name, out) }));
3638
4600
  // N3 provenance: record the audit-critical decision classes on the tamper-evident chain —
3639
4601
  // every DENY, and every ALLOW that was unlocked by an out-of-band approval. Fail-open: a
@@ -3658,16 +4620,21 @@ if (require.main === module) {
3658
4620
  // recorded as approved under a token that had expired in 2000. Under a session key that made
3659
4621
  // the whole log 'approved-action' and hid the real openings. Ask the counterfactual instead:
3660
4622
  // would this same call have been denied with no approval in hand?
4623
+ // A-SPEC-333.2, A-SPEC-333.4 — invariant: this re-ask never carries `advisory`. It reads no warning store and adds
4624
+ // nothing to `advisory.pending`, so only what the decision above said can be recorded below.
3661
4625
  const withoutApproval = out.permissionDecision === 'allow' && valid
3662
4626
  ? evaluateHook(input, specsDirWired, {
3663
4627
  projectRoot: hookProjectRoot,
3664
4628
  approval: undefined,
4629
+ settlement: approval_grants_1.GrantSettlement.counterfactual(), // A-SPEC-245.4 — a reading, not a decision: spends nothing
3665
4630
  // A-SPEC-734 (round 17): the same base, project and spec directory as the decision it re-asks.
3666
4631
  resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3667
4632
  resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
3668
4633
  })
3669
4634
  : undefined;
3670
- const unlocked = withoutApproval?.permissionDecision === 'deny';
4635
+ // A-SPEC-245.4 (f): a grant this decision spent unlocked the act too, and the line names that grant's actor
4636
+ const acting = out.permissionDecision === 'allow' ? auditApprovalFor(approval, withoutApproval?.permissionDecision === 'deny', settlement) : undefined;
4637
+ const unlocked = acting !== undefined;
3671
4638
  if (out.permissionDecision === 'deny' || unlocked) {
3672
4639
  const target = input.tool_input?.file_path
3673
4640
  ? (0, provenance_chain_1.redactTarget)('path', input.tool_input.file_path)
@@ -3675,7 +4642,7 @@ if (require.main === module) {
3675
4642
  // @implements A-SPEC-148 — writes go to THIS replica's chain; the legacy file is read-only now.
3676
4643
  new ledger_store_1.FileLedgerStore(path.join(hookProjectRoot, path.dirname(provenance_chain_1.PROVENANCE_FILE))).append({
3677
4644
  ts: new Date().toISOString(),
3678
- actor: unlocked && approval ? approval.actor : 'agent',
4645
+ actor: acting ? acting.actor : 'agent',
3679
4646
  kind: out.permissionDecision === 'deny' ? 'gate-deny' : 'approved-action',
3680
4647
  // REDACTED. Both fields used to carry the raw command; an audit of this repository's own
3681
4648
  // ledger found 15 of 29 records leaking absolute home paths and 6 matching secret-ish
@@ -3689,18 +4656,24 @@ if (require.main === module) {
3689
4656
  // @implements A-SPEC-133 — a master-key use becomes an audit line: the approval's
3690
4657
  // narrowing (or its absence) travels with the record (r7-191: promised, never shipped).
3691
4658
  inputs: [input.tool_name, target,
3692
- ...(unlocked ? [(0, provenance_chain_1.approvalMarkers)(approval)] : []), // one item, last position — the marker cannot split and self-contradict
4659
+ ...(acting ? [(0, provenance_chain_1.approvalMarkers)(acting)] : []), // one item, last position — the marker cannot split and self-contradict
3693
4660
  ].filter(Boolean),
3694
4661
  // round-9: a deny inherited the actor/rationale/authorization of an ambient approval that
3695
4662
  // did NOT cover it, so the audit line credited an authorizer who authorized nothing.
3696
- rationale: unlocked && approval ? approval.rationale : '',
4663
+ rationale: acting ? acting.rationale : '',
3697
4664
  // NEVER the raw token (review #1): a fingerprint identifies the credential without
3698
4665
  // storing the replayable secret; invalid approval attempts record nothing of it.
3699
- authorization: unlocked && approval ? (0, provenance_chain_1.authorizationRef)(approval.actor, approval.token) : '',
4666
+ authorization: acting ? (0, provenance_chain_1.authorizationRef)(acting.actor, acting.token) : '',
3700
4667
  });
3701
4668
  }
3702
4669
  }
3703
4670
  catch { /* provenance must never break the gate */ }
4671
+ // @implements A-SPEC-333.2, A-SPEC-333.4 — the last act before the return: recorded only now, and only what this
4672
+ // allow actually carried (a deny records nothing)
4673
+ try {
4674
+ (0, advisory_line_1.commitAdvisory)(hookProjectRoot, advisory, out);
4675
+ }
4676
+ catch { /* an unrecorded warning is said again */ }
3704
4677
  if (out.permissionDecision === 'deny') {
3705
4678
  // Belt-and-suspenders: Claude Code's exit-code-2 contract feeds STDERR back to the
3706
4679
  // model as the block reason, while permissionDecisionReason in the stdout JSON is
@@ -3782,7 +4755,18 @@ if (require.main === module) {
3782
4755
  process.exit(r.code);
3783
4756
  };
3784
4757
  if (!isMainThread) {
3785
- parentPort.postMessage(collect(workerData.buf));
4758
+ // @implements A-SPEC-245.9 (1b-2) — a final allow's spends cross to the main thread; the worker waits for its answer
4759
+ const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
4760
+ mainThreadSettler = (p) => {
4761
+ const flag = new Int32Array(new SharedArrayBuffer(4));
4762
+ const { port1, port2 } = new MessageChannel();
4763
+ parentPort.postMessage({ type: 'settle', pending: p, flag, port: port2 }, [port2]);
4764
+ Atomics.wait(flag, 0, 0, HOOK_DEADLINE_MS());
4765
+ const answer = receiveMessageOnPort(port1)?.message;
4766
+ port1.close();
4767
+ return answer ?? { outcome: 'refused', committed: [], refusal: 'the main thread did not answer the spend in time — nothing was done' };
4768
+ };
4769
+ parentPort.postMessage({ type: 'result', result: collect(workerData.buf) });
3786
4770
  }
3787
4771
  else {
3788
4772
  let buf = '';
@@ -3810,7 +4794,29 @@ if (require.main === module) {
3810
4794
  void worker.terminate();
3811
4795
  done(gateErrorOutcome(`the gate could not reach a verdict within ${Math.round(deadline / 1000)} s — a command or content too complex to judge in time`));
3812
4796
  }, deadline);
3813
- worker.once('message', (r) => done(r));
4797
+ worker.on('message', (m) => {
4798
+ if (m.type === 'result') {
4799
+ done(m.result);
4800
+ return;
4801
+ }
4802
+ // A-SPEC-245.9 (1b-2): the spend runs here, on the main thread; a deadline that ends the worker after it
4803
+ // answers the gate-error deny, and an approval then stays spent with nothing done (fail-closed)
4804
+ let answer;
4805
+ if (settled)
4806
+ answer = { outcome: 'refused', committed: [], refusal: 'the gate already answered — nothing was spent' };
4807
+ else {
4808
+ try {
4809
+ answer = settleOnMainThread(m.pending);
4810
+ }
4811
+ catch (e) {
4812
+ answer = { outcome: 'refused', committed: [], refusal: `the spend failed: ${e instanceof Error ? e.message : String(e)}` };
4813
+ }
4814
+ }
4815
+ m.port.postMessage(answer);
4816
+ m.port.close();
4817
+ Atomics.store(m.flag, 0, 1);
4818
+ Atomics.notify(m.flag, 0);
4819
+ });
3814
4820
  worker.once('error', (e) => done(gateErrorOutcome(`the gate stopped without a verdict: ${e.message}`)));
3815
4821
  worker.once('exit', (code) => { if (!settled)
3816
4822
  done(gateErrorOutcome(`the gate stopped without a verdict (exit ${code})`)); });