@holmes-lab/holmes-kit 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/CHANGELOG.md +344 -6
  2. package/README.md +54 -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 +202 -424
  65. package/dist/holmes/cli/init.js +33 -0
  66. package/dist/holmes/cli/lock-recover.d.ts +5 -0
  67. package/dist/holmes/cli/lock-recover.js +126 -0
  68. package/dist/holmes/cli/mcp-processes.js +1 -1
  69. package/dist/holmes/cli/release-docs.js +1 -1
  70. package/dist/holmes/cli/run-exec.d.ts +141 -0
  71. package/dist/holmes/cli/run-exec.js +1435 -0
  72. package/dist/holmes/cli/run-provision.d.ts +3 -1
  73. package/dist/holmes/cli/run-provision.js +255 -44
  74. package/dist/holmes/cli/run-wiring.d.ts +69 -0
  75. package/dist/holmes/cli/run-wiring.js +270 -0
  76. package/dist/holmes/cli/run.d.ts +21 -0
  77. package/dist/holmes/cli/run.js +341 -92
  78. package/dist/holmes/cli/runtime-binding-approval.js +32 -19
  79. package/dist/holmes/cli/screen-safe.d.ts +3 -92
  80. package/dist/holmes/cli/screen-safe.js +18 -756
  81. package/dist/holmes/config/config.d.ts +2 -0
  82. package/dist/holmes/config/config.js +5 -2
  83. package/dist/holmes/cpg/foundation/language-matrix.js +2 -2
  84. package/dist/holmes/cpg/import-resolver.js +1 -1
  85. package/dist/holmes/governance/approval-decisions.d.ts +47 -0
  86. package/dist/holmes/governance/approval-decisions.js +29 -0
  87. package/dist/holmes/governance/approval-grants.d.ts +220 -1
  88. package/dist/holmes/governance/approval-grants.js +612 -33
  89. package/dist/holmes/governance/approval-queue.d.ts +26 -0
  90. package/dist/holmes/governance/approval-queue.js +109 -11
  91. package/dist/holmes/governance/approval-spend.d.ts +95 -0
  92. package/dist/holmes/governance/approval-spend.js +191 -0
  93. package/dist/holmes/governance/autonomous-shell.d.ts +61 -0
  94. package/dist/holmes/governance/autonomous-shell.js +332 -0
  95. package/dist/holmes/governance/autonomy.d.ts +5 -0
  96. package/dist/holmes/governance/autonomy.js +16 -11
  97. package/dist/holmes/governance/constitution.d.ts +5 -0
  98. package/dist/holmes/governance/constitution.js +32 -12
  99. package/dist/holmes/governance/full-autonomy.d.ts +10 -0
  100. package/dist/holmes/governance/full-autonomy.js +103 -7
  101. package/dist/holmes/governance/harness-catalog.d.ts +103 -0
  102. package/dist/holmes/governance/harness-catalog.js +348 -0
  103. package/dist/holmes/governance/human-channel.d.ts +38 -0
  104. package/dist/holmes/governance/human-channel.js +49 -0
  105. package/dist/holmes/governance/install-manifest.d.ts +22 -0
  106. package/dist/holmes/governance/install-manifest.js +160 -0
  107. package/dist/holmes/governance/ledger-rechain.js +2 -0
  108. package/dist/holmes/governance/ledger-store.conformance.d.ts +7 -1
  109. package/dist/holmes/governance/ledger-store.conformance.js +66 -0
  110. package/dist/holmes/governance/ledger-store.d.ts +88 -11
  111. package/dist/holmes/governance/ledger-store.js +186 -8
  112. package/dist/holmes/governance/provenance-chain.d.ts +16 -4
  113. package/dist/holmes/governance/provenance-chain.js +19 -4
  114. package/dist/holmes/governance/provenance-ledger.d.ts +6 -3
  115. package/dist/holmes/governance/provenance-ledger.js +53 -18
  116. package/dist/holmes/governance/push-gate-runner.js +11 -7
  117. package/dist/holmes/governance/recorded-pairs.d.ts +96 -0
  118. package/dist/holmes/governance/recorded-pairs.js +522 -0
  119. package/dist/holmes/governance/replica-id.d.ts +1 -1
  120. package/dist/holmes/governance/replica-id.js +1 -1
  121. package/dist/holmes/governance/spec-seam.d.ts +59 -0
  122. package/dist/holmes/governance/spec-seam.js +587 -0
  123. package/dist/holmes/governance/spend-kinds.d.ts +16 -0
  124. package/dist/holmes/governance/spend-kinds.js +18 -0
  125. package/dist/holmes/guardrail/decision-ledger.d.ts +2 -1
  126. package/dist/holmes/guardrail/decision-ledger.js +2 -1
  127. package/dist/holmes/guardrail/impact-gate.d.ts +1 -0
  128. package/dist/holmes/guardrail/impact-gate.js +1 -1
  129. package/dist/holmes/guardrail/line-continuation.d.ts +8 -0
  130. package/dist/holmes/guardrail/line-continuation.js +39 -0
  131. package/dist/holmes/guardrail/operator-person.d.ts +28 -4
  132. package/dist/holmes/guardrail/operator-person.js +57 -11
  133. package/dist/holmes/guardrail/refusal-codes.d.ts +8 -3
  134. package/dist/holmes/guardrail/refusal-codes.js +64 -10
  135. package/dist/holmes/guardrail/risk-classifier.d.ts +15 -9
  136. package/dist/holmes/guardrail/risk-classifier.js +228 -16
  137. package/dist/holmes/guardrail/risk-gate.d.ts +2 -8
  138. package/dist/holmes/guardrail/risk-gate.js +7 -34
  139. package/dist/holmes/guardrail/risk-types.d.ts +10 -0
  140. package/dist/holmes/guardrail/run-plan-scope.js +3 -1
  141. package/dist/holmes/guardrail/run-refusals.js +24 -8
  142. package/dist/holmes/guardrail/run-stages.d.ts +5 -0
  143. package/dist/holmes/guardrail/run-stages.js +25 -5
  144. package/dist/holmes/guardrail/scope-judgment.js +1 -1
  145. package/dist/holmes/guardrail/shell-words.js +24 -3
  146. package/dist/holmes/guardrail/unresolved-write.d.ts +40 -0
  147. package/dist/holmes/guardrail/unresolved-write.js +556 -0
  148. package/dist/holmes/guardrail/write-target.d.ts +3 -0
  149. package/dist/holmes/guardrail/write-target.js +26 -5
  150. package/dist/holmes/hooks/pre-tool-use.d.ts +105 -1
  151. package/dist/holmes/hooks/pre-tool-use.js +1134 -167
  152. package/dist/holmes/hooks/rtm-refresh-child.d.ts +1 -1
  153. package/dist/holmes/hooks/rtm-refresh-child.js +1 -1
  154. package/dist/holmes/hooks/stop.d.ts +23 -0
  155. package/dist/holmes/hooks/stop.js +86 -33
  156. package/dist/holmes/mcp/approval-adapters.js +3 -1
  157. package/dist/holmes/mcp/approval-commit.js +3 -2
  158. package/dist/holmes/mcp/approval-policy.d.ts +2 -1
  159. package/dist/holmes/mcp/approval-policy.js +3 -1
  160. package/dist/holmes/mcp/handlers/adoption.d.ts +1 -1
  161. package/dist/holmes/mcp/handlers/approval-ask.d.ts +3 -0
  162. package/dist/holmes/mcp/handlers/approval-ask.js +18 -7
  163. package/dist/holmes/mcp/handlers/entity-integration.d.ts +3 -3
  164. package/dist/holmes/mcp/handlers/entity-integration.js +29 -11
  165. package/dist/holmes/mcp/handlers/entity-renumber.d.ts +4 -4
  166. package/dist/holmes/mcp/handlers/entity-renumber.js +29 -11
  167. package/dist/holmes/mcp/handlers/entity-store.d.ts +2 -2
  168. package/dist/holmes/mcp/handlers/entity-store.js +133 -59
  169. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +9 -5
  170. package/dist/holmes/mcp/handlers/operator-inspection.js +79 -16
  171. package/dist/holmes/mcp/handlers/phase-queries.d.ts +1 -1
  172. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +4 -4
  173. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -2
  174. package/dist/holmes/mcp/handlers/review-evidence.js +35 -11
  175. package/dist/holmes/mcp/handlers/review-queries.d.ts +5 -0
  176. package/dist/holmes/mcp/handlers/review-queries.js +8 -1
  177. package/dist/holmes/mcp/handlers/review-verdict.d.ts +3 -0
  178. package/dist/holmes/mcp/handlers/review-verdict.js +10 -3
  179. package/dist/holmes/mcp/handlers/risk-assessment.d.ts +7 -2
  180. package/dist/holmes/mcp/handlers/risk-assessment.js +34 -12
  181. package/dist/holmes/mcp/handlers/runtime-binding-tool.d.ts +2 -2
  182. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +6 -1
  183. package/dist/holmes/mcp/handlers/slice-orchestration.js +14 -1
  184. package/dist/holmes/mcp/handlers/spec-approval.d.ts +15 -3
  185. package/dist/holmes/mcp/handlers/spec-approval.js +32 -5
  186. package/dist/holmes/mcp/handlers/spec-authoring.d.ts +2 -2
  187. package/dist/holmes/mcp/handlers/spec-authoring.js +19 -2
  188. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +11 -38
  189. package/dist/holmes/mcp/handlers/spec-lifecycle.js +441 -94
  190. package/dist/holmes/mcp/handlers/spec-queries.d.ts +2 -2
  191. package/dist/holmes/mcp/handlers/taint-screening.d.ts +1 -1
  192. package/dist/holmes/mcp/handlers/taint-screening.js +2 -2
  193. package/dist/holmes/mcp/handlers/test-execution.d.ts +1 -1
  194. package/dist/holmes/mcp/handlers/workspace-queries.d.ts +2 -2
  195. package/dist/holmes/mcp/handlers.d.ts +89 -79
  196. package/dist/holmes/mcp/handlers.js +69 -22
  197. package/dist/holmes/mcp/harness-attestation.d.ts +78 -5
  198. package/dist/holmes/mcp/harness-attestation.js +325 -53
  199. package/dist/holmes/mcp/maintenance-analyze.d.ts +1 -1
  200. package/dist/holmes/mcp/maintenance-analyze.js +9 -9
  201. package/dist/holmes/mcp/maintenance-evidence.js +31 -2
  202. package/dist/holmes/mcp/requirement-triage-evidence.js +22 -13
  203. package/dist/holmes/mcp/server-staleness.js +1 -1
  204. package/dist/holmes/mcp/server.js +9 -8
  205. package/dist/holmes/mcp/spec-id-guard.js +1 -1
  206. package/dist/holmes/mcp/tool-schemas.d.ts +13 -0
  207. package/dist/holmes/mcp/tool-schemas.js +29 -2
  208. package/dist/holmes/project/act-root.d.ts +19 -0
  209. package/dist/holmes/project/act-root.js +100 -0
  210. package/dist/holmes/project/baseline.js +4 -3
  211. package/dist/holmes/project/bounded-group.d.ts +47 -0
  212. package/dist/holmes/project/bounded-group.js +140 -0
  213. package/dist/holmes/project/bounded-io.d.ts +50 -2
  214. package/dist/holmes/project/bounded-io.js +138 -6
  215. package/dist/holmes/project/change-source.js +2 -2
  216. package/dist/holmes/project/instance-id.d.ts +10 -0
  217. package/dist/holmes/project/instance-id.js +233 -0
  218. package/dist/holmes/project/machine-identity.d.ts +25 -0
  219. package/dist/holmes/project/machine-identity.js +133 -0
  220. package/dist/holmes/project/owned-lock.d.ts +84 -0
  221. package/dist/holmes/project/owned-lock.js +263 -0
  222. package/dist/holmes/project/plain-lock-fs.d.ts +2 -0
  223. package/dist/holmes/project/plain-lock-fs.js +126 -0
  224. package/dist/holmes/project/request-lock.d.ts +85 -0
  225. package/dist/holmes/project/request-lock.js +459 -0
  226. package/dist/holmes/project/root.d.ts +12 -4
  227. package/dist/holmes/project/root.js +26 -7
  228. package/dist/holmes/project/run-records.d.ts +19 -0
  229. package/dist/holmes/project/run-records.js +94 -12
  230. package/dist/holmes/project/screen-text.d.ts +94 -0
  231. package/dist/holmes/project/screen-text.js +763 -0
  232. package/dist/holmes/project/spend-lock.d.ts +82 -0
  233. package/dist/holmes/project/spend-lock.js +413 -0
  234. package/dist/holmes/refresh/freshness-coordinator.d.ts +1 -1
  235. package/dist/holmes/refresh/freshness-coordinator.js +1 -1
  236. package/dist/holmes/review/condition-hunk-replay.js +4 -2
  237. package/dist/holmes/review/confidence-calibration.d.ts +1 -1
  238. package/dist/holmes/review/confidence-calibration.js +1 -1
  239. package/dist/holmes/review/content-verify.js +1 -1
  240. package/dist/holmes/review/hop-ablation.d.ts +4 -4
  241. package/dist/holmes/review/hop-ablation.js +5 -5
  242. package/dist/holmes/review/point-in-time-replay.js +12 -3
  243. package/dist/holmes/review/rank-diagnosis.d.ts +2 -2
  244. package/dist/holmes/review/rank-diagnosis.js +1 -1
  245. package/dist/holmes/review/replay-corpus.d.ts +10 -4
  246. package/dist/holmes/review/replay-corpus.js +25 -9
  247. package/dist/holmes/review/requirement-triage.js +2 -2
  248. package/dist/holmes/review/semantic-arm.d.ts +3 -3
  249. package/dist/holmes/review/semantic-arm.js +3 -3
  250. package/dist/holmes/review/test-outcomes.js +3 -1
  251. package/dist/holmes/review/test-runner.d.ts +11 -0
  252. package/dist/holmes/review/test-runner.js +31 -10
  253. package/dist/holmes/review/test-selection-breadth.js +2 -2
  254. package/dist/holmes/review/verdicts.d.ts +105 -8
  255. package/dist/holmes/review/verdicts.js +640 -36
  256. package/dist/holmes/rtm/anchor-census.d.ts +9 -0
  257. package/dist/holmes/rtm/anchor-census.js +151 -0
  258. package/dist/holmes/rtm/anchor-ids.d.ts +25 -1
  259. package/dist/holmes/rtm/anchor-ids.js +45 -2
  260. package/dist/holmes/rtm/comment-ranges.d.ts +2 -0
  261. package/dist/holmes/rtm/comment-ranges.js +104 -0
  262. package/dist/holmes/rtm/counted-tests.d.ts +1 -0
  263. package/dist/holmes/rtm/counted-tests.js +63 -0
  264. package/dist/holmes/rtm/impact-advisory.d.ts +1 -1
  265. package/dist/holmes/rtm/known-defects.js +1 -1
  266. package/dist/holmes/rtm/localize.js +1 -1
  267. package/dist/holmes/rtm/taint-benchmark.d.ts +1 -1
  268. package/dist/holmes/rtm/taint-vocabulary.d.ts +1 -1
  269. package/dist/holmes/rtm/test-scope.d.ts +31 -0
  270. package/dist/holmes/rtm/test-scope.js +166 -5
  271. package/dist/holmes/rtm/trace-gaps.js +1 -1
  272. package/dist/holmes/runtime/dispatch.d.ts +10 -0
  273. package/dist/holmes/runtime/dispatch.js +12 -1
  274. package/dist/holmes/semantic/cloud-usage.d.ts +1 -1
  275. package/dist/holmes/semantic/cloud-usage.js +1 -1
  276. package/dist/holmes/semantic/unreadable-paths.d.ts +1 -1
  277. package/dist/holmes/semantic/unreadable-paths.js +1 -1
  278. package/dist/holmes/spec/approval-blockers.js +1 -1
  279. package/dist/holmes/spec/entity-store.d.ts +6 -1
  280. package/dist/holmes/spec/entity-store.js +16 -2
  281. package/dist/holmes/spec/entity-transaction.d.ts +7 -2
  282. package/dist/holmes/spec/entity-transaction.js +87 -170
  283. package/dist/holmes/spec/spec-store.d.ts +12 -6
  284. package/dist/holmes/spec/spec-store.js +4 -2
  285. package/dist/holmes/spec/spec-types.js +1 -1
  286. package/dist/holmes/spec/succession-guard.d.ts +56 -0
  287. package/dist/holmes/spec/succession-guard.js +187 -0
  288. package/dist/holmes/spec/succession.d.ts +70 -0
  289. package/dist/holmes/spec/succession.js +171 -0
  290. package/dist/holmes/spec/transition-policy.d.ts +2 -2
  291. package/docs/install-guide.md +9 -3
  292. package/docs/language-support.md +78 -0
  293. package/package.json +4 -3
  294. package/playbooks/author-slice/PLAYBOOK.md +1 -1
  295. package/playbooks/promote-slice/PLAYBOOK.md +5 -1
  296. package/playbooks/publish/PLAYBOOK.md +45 -33
  297. package/dist/holmes/review/manual-baseline.d.ts +0 -209
  298. 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-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");
@@ -113,6 +123,7 @@ 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");
115
125
  const bounded_io_1 = require("../project/bounded-io");
126
+ const flags_1 = require("../cli/flags"); // @implements A-SPEC-245.18 — the CLI's own flag reading, one source
116
127
  // Resolve per-rm-target git facts (H1 git-aware guardrail): is each recursive-rm target a
117
128
  // regenerable build artifact (gitignored), version-controlled source (tracked), or escaping the
118
129
  // project? This is the I/O half — the classifier stays pure and merely consumes these signals.
@@ -187,27 +198,41 @@ function resolveStagedStore(command, projectRoot, specsDir) {
187
198
  return undefined;
188
199
  if (!fs.existsSync(specsDir))
189
200
  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)() });
201
+ // the repository question first (one bounded child); the change list itself is computed without `git status`
202
+ 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
203
  const answer = (0, bounded_io_1.gitAnswerOf)(r, projectRoot);
192
204
  if (answer === 'no-repository')
193
205
  return undefined;
206
+ // @implements A-SPEC-222.12 (N1) — and another replica's ledger file (any provenance*.jsonl but this writer's own)
207
+ const ledgerDir = path.join(projectRoot, '.ax', 'ledger');
194
208
  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 };
209
+ return { specsDir, unanswered: true, ledgerDir };
210
+ // @implements A-SPEC-792.32 — `git status` re-hashes a racily clean file through its clean filter, which ran the
211
+ // agent's filter command inside this hook (measured 2026-10-26); worktreeChanges compares bytes without git's filters
212
+ let changes;
213
+ let foreign = [];
214
+ try {
215
+ const { worktreeChanges } = require('../governance/spec-seam');
216
+ changes = worktreeChanges(projectRoot, [path.relative(projectRoot, specsDir)]);
217
+ if (fs.existsSync(ledgerDir)) {
218
+ let own = null;
219
+ try {
220
+ own = new ledger_store_1.FileLedgerStore(ledgerDir).replicaId();
221
+ }
222
+ catch {
223
+ own = null;
224
+ }
225
+ foreign = worktreeChanges(projectRoot, [path.relative(projectRoot, ledgerDir)]).filter((c) => {
226
+ const m = /^provenance(?:\.([^/]+))?\.jsonl$/i.exec(path.posix.basename(c.path));
227
+ return m !== null && !(own !== null && m[1] === own);
228
+ });
229
+ }
230
+ }
231
+ catch {
232
+ return { specsDir, unanswered: true, ledgerDir };
233
+ }
234
+ return { specsDir, tracked: changes.some((c) => !c.untracked), untracked: changes.some((c) => c.untracked),
235
+ ledgerDir, foreignLedger: { tracked: foreign.some((c) => !c.untracked), untracked: foreign.some((c) => c.untracked) } };
211
236
  }
212
237
  /**
213
238
  * @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 +672,138 @@ function wrappedServerWord(normalized) {
647
672
  }
648
673
  return false;
649
674
  }
675
+ /**
676
+ * @implements A-SPEC-245.9 (1b-5, item 7) — `holmes-kit lock recover` retires a lock another process may hold: the
677
+ * operator's act. The CLI refuses it from an agent by the environment and the process ancestry, which a process
678
+ * reparented away from the harness escapes, so the gate refuses the command itself. A segment counts when its command
679
+ * word (after env, nohup, time, command, exec, builtin and NAME=value) runs the CLI — `holmes-kit`, `npx [-y]
680
+ * [@holmes-lab/]holmes-kit[@v]`, or `node <…/holmes/cli/index.js | …holmes-kit[.js]>` — and its next words are
681
+ * `lock recover`; a mention as an argument (echo, grep) is not the act.
682
+ */
683
+ function lockRecoverAct(command) {
684
+ // @implements A-SPEC-245.17 (item 1) — read through the gate's own shell reading, as the agent-CLI launch is: segments
685
+ // split on unquoted separators (so `{`, `then`, `do`, `!` lead a segment), quoting removed (joined quotes and
686
+ // backslashes read as the word they make), a -c body, an eval argument, a command substitution and a here-document
687
+ // read as words of a command, an inert text command's arguments (echo, grep …) left as data. By word, not by wrapper:
688
+ // sudo, timeout, nice, time, setsid, screen, tmux, xargs, env options, command -p and the package runners need no
689
+ // list. Named limits: a word made by variable expansion ($H lock recover) and an eval body built at run time — both
690
+ // refused since A-SPEC-245.18 when the command's text names holmes-kit, lock and recover.
691
+ // the reading hands the predicate a word's basename, so index.js finds the segment; the full word is judged below
692
+ // @implements A-SPEC-245.19 (item 2) — the hook is early refusal of the direct forms only; the authority boundary is
693
+ // the CLI's operator judgement (operatorActGuard: the inherited harness marker or the process ancestry). Text that
694
+ // names the act and is handed to a shell, an interpreter or a run-time word is advised on (lockRecoverAdvisory), not
695
+ // refused: it refused commit messages, PR bodies and prose. Named limit: the hook does not read interpreter source,
696
+ // package scripts, aliases or run-time words.
697
+ const segments = agentLaunchSegments(command, 0, { test: (w) => isHolmesKitWord(w) || w === 'index.js' });
698
+ return segments.some(({ words, spans }) => !lockRecoverDataLead(words, spans) && words.some((w, i) => {
699
+ if (!isHolmesKitWord(w))
700
+ return false;
701
+ let j = i + 1;
702
+ while (j < words.length && (words[j].startsWith('-') || isHolmesKitWord(words[j])))
703
+ j++; // npx -p pkg holmes-kit, npm exec pkg --
704
+ if (words[j] !== 'lock')
705
+ return false;
706
+ // @implements A-SPEC-245.18 (item 4) — xargs or parallel fills the arguments at run time
707
+ if (words.slice(0, i).some((p) => /^(?:xargs|parallel)$/.test(baseWord(p))))
708
+ return true;
709
+ // @implements A-SPEC-245.18 (item 2) — the CLI removes flags wherever they stand (parseFlags): judge what is left
710
+ const after = words.slice(j + 1);
711
+ try {
712
+ return (0, flags_1.parseFlags)(after).positionals.includes('recover');
713
+ }
714
+ catch {
715
+ return after.includes('recover');
716
+ }
717
+ }));
718
+ }
719
+ const baseWord = (w) => w.split(/[\\/]/).pop() ?? w;
720
+ /**
721
+ * The CLI as a word: its name, a path to it, its .js/.cmd/.ps1/.exe shim, the package, each with an optional
722
+ * `@<version|tag>` (the shell reading hands the predicate `holmes-kit@0.40.0`, a basename — A-SPEC-245.18 item 1); its
723
+ * index.js under holmes/cli, or a relative one (`cd …/cli && node index.js`); the text after `=` and a leading `!`
724
+ * (`git -c alias.x='!holmes-kit …'`).
725
+ */
726
+ const HOLMES_KIT_WORD = /^(?:\S*[\/\\])?holmes-kit(?:\.js|\.cmd|\.ps1|\.exe)?(?:@[^\s\/\\]+)?$|(?:^|[\/\\])holmes[\/\\]cli[\/\\]index\.js$|^(?:\.[\/\\])?index\.js$/i;
727
+ function isHolmesKitWord(w) {
728
+ // @implements A-SPEC-245.19 (item 2) — after a sed delimiter too (`s|x|holmes-kit …|e`); A-SPEC-245.20 — `;` as well
729
+ const cut = Math.max(...['=', '|', '#', ',', ':', ';'].map((c) => w.lastIndexOf(c)));
730
+ return HOLMES_KIT_WORD.test(w.slice(cut + 1).replace(/^!/, ''));
731
+ }
732
+ /**
733
+ * @implements A-SPEC-245.18 (item 3) — a segment whose lead takes the text as data: jest (directly, through npx, or by a
734
+ * path to it), tee, and sed whose script carries no GNU execute (the `e` command, the `s///e` flag).
735
+ */
736
+ function lockRecoverDataLead(words, spans) {
737
+ let i = 0;
738
+ while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))
739
+ i++;
740
+ if (words[i] === 'npx') {
741
+ // @implements A-SPEC-245.19 (item 2) — a -p/--package value is not the command (a -c/--call string's words follow as
742
+ // the command, so it needs no rule of its own: A-SPEC-245.20 removed the duplicate)
743
+ i++;
744
+ while (words[i]?.startsWith('-'))
745
+ i += /^(?:-p|--package)$/.test(words[i]) ? 2 : 1;
746
+ }
747
+ const lead = baseWord(words[i] ?? '');
748
+ if (lead === 'jest' || lead === 'tee')
749
+ return true;
750
+ if (lead !== 'sed')
751
+ return false;
752
+ // @implements A-SPEC-245.23 (item 1) — a script given through --expression= or attached to -e is read as a script
753
+ // @implements A-SPEC-245.24 (items 2, 6d) — the words of one quoted span are one script again (the shell reading split a
754
+ // pattern address at its spaces), and GNU's abbreviated --expression spellings are stripped like the full one
755
+ const script = sedScriptWords(words.slice(i + 1), (spans ?? []).slice(i + 1))
756
+ // 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
757
+ .map((w) => w.replace(/^(?:--e[a-z]*=|-[a-zA-Z]*?e)/, '')).join(' ');
758
+ // @implements A-SPEC-245.19 (item 2) — the s command's flags after its third delimiter, whatever the delimiter
759
+ // @implements A-SPEC-245.24 (items 2, 3) — the e command is recognised by the character before it — an address's last
760
+ // character (a delimiter, a digit, $, !, ~, `,`, an I or M flag) or a command's start — with no nested quantifier, so
761
+ // the judgement is linear (245.23's address class took 2.7 s on 36 slashes). Measured against the 245.19 build by
762
+ // the differential corpus (sed-early-refusal-corpus.test.ts): no input it refused early passes here.
763
+ // Named limits, refused by the CLI and outside this early refusal: a custom-delimited address, GNU +N ranges, a script
764
+ // assembled at run time (one s command writing the command, another running it). It can refuse sed data that names
765
+ // 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.
766
+ // A-SPEC-245.25 (item 2) — 245.19's second alternative ORed back unchanged (it covered a command word attached to e:
767
+ // the 245.22-245.24 rewrites each fell below the 245.19 baseline); the s command takes ASCII punctuation delimiters
768
+ // only (item 4: many non-ASCII delimiters made the alternative quadratic). Named limits, refused by the CLI: no address
769
+ // or a line-number address with an attached command, `1e{ …;}`, an absolute path after e, an alphanumeric or
770
+ // non-ASCII delimiter. A-SPEC-245.26 (item 3) — and, passing since 245.19: the CLI word attached to a pattern
771
+ // address's e; a space or ! between the address and an attached command; an s command attached to an address; an s
772
+ // delimiter (@ ! % _ ~ ^) the CLI-word reading does not cut at. The early refusal's direction waits for the owner.
773
+ // A-SPEC-245.26 (item 2) — the same alternative in a form that does not backtrack quadratically on a long run of e
774
+ // (the review's equivalent: an e somewhere in the alphanumeric run after the slash, then the run to its end)
775
+ 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);
776
+ }
777
+ /** @implements A-SPEC-245.24 (item 2) — consecutive words of one quoted span joined back with a space. */
778
+ function sedScriptWords(words, spans) {
779
+ const out = [];
780
+ words.forEach((w, k) => {
781
+ if (k > 0 && spans[k] !== undefined && spans[k] >= 0 && spans[k] === spans[k - 1])
782
+ out[out.length - 1] += ` ${w}`;
783
+ else
784
+ out.push(w);
785
+ });
786
+ return out;
787
+ }
788
+ /** A shell that reads its program from a pipe, a here-string or a process substitution. */
789
+ 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]*<<</;
790
+ /** A command word built at run time: an expansion or a substitution where a command starts. */
791
+ const RUNTIME_COMMAND_WORD = /(?:^|[;&|\n({]|\b(?:then|do|else|sudo|env|nohup|time|command|exec)\s)\s*["']?(?:\$[({A-Za-z_]|`)/;
792
+ /**
793
+ * @implements A-SPEC-245.19 (item 2) — the advisory an allowed Bash command carries when its text names the act and
794
+ * hands it to something that runs text: the CLI will refuse it from a session.
795
+ */
796
+ function lockRecoverAdvisory(command) {
797
+ return lockRecoverTextRuns(command)
798
+ ? '[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).'
799
+ : null;
800
+ }
801
+ function lockRecoverTextRuns(command) {
802
+ const text = command.replace(/["'\\]/g, '');
803
+ if (!/holmes-kit/i.test(text) || !/\block\b/.test(text) || !/\brecover\b/.test(text))
804
+ return false;
805
+ return interpreterSpawns(command) || SHELL_FED.test(command) || RUNTIME_COMMAND_WORD.test(command);
806
+ }
650
807
  function startsHolmesServer(command) {
651
808
  command = (0, shell_argument_roles_1.shellArgumentRoles)(command).serverText;
652
809
  if (SERVER_RUNNERS.some((t) => t.test(command)))
@@ -668,10 +825,15 @@ function startsHolmesServer(command) {
668
825
  * Round-1 A-SPEC-718's approval_commit exception is now the rule for every tool.
669
826
  */
670
827
  function hookOutputFor(_toolName, out) {
671
- const { permissionDecision, permissionDecisionReason, ...rest } = out;
828
+ // @implements A-SPEC-245.23 (item 3) — a verdict's `refusal` is the deny site's own code; the harness never sees the field
829
+ // A-SPEC-245.25 — `request` is the run path's, never the harness's
830
+ const { permissionDecision, permissionDecisionReason, refusal, request: _request, ...rest } = out;
672
831
  if (permissionDecision === 'deny') {
673
832
  // @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) };
833
+ // A-SPEC-245.26 (4a) — a site that carries `refusal` but leaves it unset names no registered code: unclassified,
834
+ // never the reason's words
835
+ const code = 'refusal' in out ? (typeof refusal === 'string' ? refusal : '') : undefined;
836
+ return { hookEventName: 'PreToolUse', ...rest, permissionDecision, permissionDecisionReason: (0, refusal_codes_1.withRefusalLine)(permissionDecisionReason, code) };
675
837
  }
676
838
  const context = [typeof rest.additionalContext === 'string' ? rest.additionalContext : '', permissionDecisionReason ?? ''].filter((t) => t !== '').join('\n');
677
839
  const { additionalContext: _c, ...others } = rest;
@@ -992,17 +1154,102 @@ function agentCliLaunch(command) {
992
1154
  }
993
1155
  /** @implements A-SPEC-774.9 — an interpreter that spawns an agent by name (the 774.2 rule, kept apart for reuse). */
994
1156
  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)
1157
+ return interpreterSpawns(command)
997
1158
  && /['"](?:claude|codex|gemini|agy|aider|cursor-agent|opencode|goose|qwen)(?:\.exe|\.cmd)?['"]/.test(command);
998
1159
  }
1160
+ /** @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. */
1161
+ function interpreterSpawns(command) {
1162
+ return /\b(?:node|python[0-9.]*|ruby|perl|deno|bun|php)\b/.test(command)
1163
+ && /\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|subprocess|system|popen|Popen)\b/.test(command);
1164
+ }
1165
+ /**
1166
+ * @implements A-SPEC-774.67 — exactly the product's report command: the Holmes CLI (as installed, through npx, or the
1167
+ * package's bin under node), `report`, then only `--message <word>`, `--harness <harness>` and `--open`, each at most once.
1168
+ */
1169
+ function isHolmesReport(rawWords, rawSpans = [], spanQuote = []) {
1170
+ // @implements A-SPEC-774.68 — a word holding $ or a backtick is never text here: it may be a command substitution
1171
+ // @implements A-SPEC-774.69 — unless its quoting keeps it text: wholly single-quoted, or wholly double-quoted with
1172
+ // neither $( nor a backtick (`'costs $5'`, `"home $HOME"`; review 18:43, F1.2-e)
1173
+ const text = (w, k) => {
1174
+ if (!/[$`]/.test(w))
1175
+ return true;
1176
+ const q = rawSpans[k] !== undefined && rawSpans[k] >= 0 ? spanQuote[rawSpans[k]] : undefined;
1177
+ return q === "'" || (q === '"' && !/\$\(|`/.test(w));
1178
+ };
1179
+ if (!rawWords.every(text))
1180
+ return false;
1181
+ // one quoted value is one word (`--message "ART-4 zero"`): words sharing a quoted span are joined
1182
+ const words = [];
1183
+ for (let k = 0; k < rawWords.length; k++) {
1184
+ if (k > 0 && rawSpans[k] !== undefined && rawSpans[k] >= 0 && rawSpans[k] === rawSpans[k - 1])
1185
+ words[words.length - 1] += ` ${rawWords[k]}`;
1186
+ else
1187
+ words.push(rawWords[k]);
1188
+ }
1189
+ let i = 0;
1190
+ if (words[0] === 'npx') {
1191
+ i = 1;
1192
+ if (words[i] === '-y' || words[i] === '--yes')
1193
+ i++;
1194
+ }
1195
+ const prog = words[i] ?? '';
1196
+ const isCli = prog === 'holmes-kit' || (words[0] === 'npx' && /^@holmes-lab\/holmes-kit(?:@[\w.-]+)?$/.test(prog));
1197
+ const isBin = words[0] === 'node' && i === 0 && /(?:^|\/)bin\/holmes-kit\.js$/.test(words[1] ?? '');
1198
+ if (isBin)
1199
+ i = 1;
1200
+ else if (!isCli)
1201
+ return false;
1202
+ if (words[i + 1] !== 'report')
1203
+ return false;
1204
+ const seen = new Set();
1205
+ for (let k = i + 2; k < words.length; k++) {
1206
+ const w = words[k];
1207
+ if (seen.has(w))
1208
+ return false;
1209
+ seen.add(w);
1210
+ if (w === '--open')
1211
+ continue;
1212
+ if (w === '--message' && k + 1 < words.length) {
1213
+ k++;
1214
+ continue;
1215
+ }
1216
+ if (w === '--harness' && /^(?:claude|codex|agy|antigravity)$/.test(words[k + 1] ?? '')) {
1217
+ k++;
1218
+ continue;
1219
+ }
1220
+ return false;
1221
+ }
1222
+ return true;
1223
+ }
999
1224
  /** The words of every segment that launches an agent CLI (A-SPEC-774.5 §1), quote-aware. */
1000
1225
  /**
1001
1226
  * @implements A-SPEC-774.26 — with each word, the quoted span it came from (-1: unquoted or mixed), so the option check
1002
1227
  * can tell a quoted prompt (`-p "… cut -d= …"`) from options, and a quoted program (`tmux new -d 'claude …'`) from both.
1003
1228
  */
1004
- function agentLaunchSegments(command) {
1229
+ // @implements A-SPEC-774.88 — the program pattern is a parameter: the test runtime's kill seam reads shell strings for
1230
+ // kill, pkill and killall with the same word scanner (the default, and so the code gate, is unchanged)
1231
+ function agentLaunchSegments(command, depth = 0, program = AGENT_CLI) {
1005
1232
  const found = [];
1233
+ const scan = scanShell(command); // @implements A-SPEC-774.75 — computed once, read by the substitution scan too
1234
+ // @implements A-SPEC-774.68 — a command substitution runs whatever quoting surrounds it: its body is a command too
1235
+ const subs = substitutionBodies(command, scan);
1236
+ const nested = depth < 8 ? subs.bodies.flatMap((b) => agentLaunchSegments(b, depth + 1, program)) : [];
1237
+ // @implements A-SPEC-774.69 — what the limits leave unread is judged a launch, with an option no list allows (F1.2-b)
1238
+ if (subs.overflow || (depth >= 8 && subs.bodies.length > 0))
1239
+ nested.push({ words: ['codex', '--holmes-unjudged-substitutions'], spans: [-1, -1] });
1240
+ // @implements A-SPEC-774.72 — the one scanner; a here-document fed to anything but an inert text command (`bash <<'EOF'`)
1241
+ // runs its lines, which are judged as commands; an inert one's body (`cat <<'EOF'`) is data (A-SPEC-774.69)
1242
+ // @implements A-SPEC-774.75 — unless it never ends: an unterminated body is judged as commands under any lead, and
1243
+ // here-documents nested past depth 8 are judged a launch, as substitutions are
1244
+ for (const h of scan.docs) {
1245
+ if (INERT_TEXT_COMMANDS.has(h.lead) && h.terminated)
1246
+ continue;
1247
+ if (depth >= 8) {
1248
+ nested.push({ words: ['codex', '--holmes-unjudged-here-documents'], spans: [-1, -1] });
1249
+ break;
1250
+ }
1251
+ nested.push(...agentLaunchSegments(command.slice(h.bodyStart, h.bodyEnd), depth + 1, program));
1252
+ }
1006
1253
  // @implements A-SPEC-774.5 §1 — by WORD, not by wrapper. The wrapper list (774.2) was walked through by `tmux new -d
1007
1254
  // '…'`, `script -q /dev/null …` and `watch …` (supervisor probe, 2026-10-17): launchers have no end. Quoting is
1008
1255
  // removed first, so a program inside a quoted argument is read as words of the same segment; the exceptions are a
@@ -1012,44 +1259,74 @@ function agentLaunchSegments(command) {
1012
1259
  const segs = [];
1013
1260
  let cur = '';
1014
1261
  let curSpans = [];
1015
- let quote = null;
1016
1262
  let span = -1;
1017
1263
  let spans = 0;
1264
+ let open = false;
1265
+ let ansi = false; // the open span is $'…'
1266
+ let undecodable = false;
1267
+ const spanQuote = []; // @implements A-SPEC-774.69 — the quote kind of each quoted span, for the report exemption
1018
1268
  const add = (s, at) => { for (const c of s) {
1019
1269
  cur += c;
1020
1270
  curSpans.push(at);
1021
1271
  } };
1272
+ const cut = () => { segs.push({ text: cur, spanOf: curSpans }); cur = ''; curSpans = []; };
1273
+ const { kind } = scan;
1022
1274
  for (let k = 0; k < command.length; k++) {
1023
1275
  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;
1276
+ const t = kind[k];
1277
+ // @implements A-SPEC-774.72 — quoting from the scan: a delimiter opens or closes a span (quoting joins, as the shell
1278
+ // does: cl'aude' is claude); $'…' is a single-quote span with its escapes decoded; comments and bodies are dropped
1279
+ if (t === 7 /* Ch.Delim */) {
1280
+ if (!open) {
1281
+ open = true;
1282
+ span = spans++;
1283
+ spanQuote[span] = ch === '"' ? '"' : "'";
1284
+ ansi = ch === '$';
1285
+ if (ansi)
1286
+ k++;
1030
1287
  }
1031
1288
  else
1032
- add(ch, span);
1289
+ open = false;
1033
1290
  continue;
1034
1291
  }
1035
- if (ch === '\\') {
1036
- add(command[++k] ?? '', -1);
1292
+ // @implements A-SPEC-774.75 — inside $'…' an escape is decoded as bash 5 decodes it (`\x63odex` is codex); one that
1293
+ // names no character is judged a launch
1294
+ if (t === 8 /* Ch.Escape */ && open && ansi) {
1295
+ const d = ansiEscape(command, k + 1);
1296
+ if (d === null) {
1297
+ undecodable = true;
1298
+ k++;
1299
+ continue;
1300
+ }
1301
+ add(d.text, span);
1302
+ k += d.length;
1037
1303
  continue;
1038
1304
  }
1039
- if (ch === "'" || ch === '"') {
1040
- quote = ch;
1041
- span = spans++;
1305
+ if (t === 8 /* Ch.Escape */) {
1306
+ const next = command[++k] ?? '';
1307
+ add(next, open ? span : -1);
1308
+ continue;
1309
+ }
1310
+ if (t === 1 /* Ch.Single */ || t === 2 /* Ch.Double */ || t === 3 /* Ch.Ansi */) {
1311
+ add(ch, span);
1312
+ continue;
1313
+ }
1314
+ if (t === 4 /* Ch.Comment */)
1315
+ continue;
1316
+ if (t === 5 /* Ch.Body */ || t === 6 /* Ch.QuotedBody */) {
1317
+ if (cur !== '')
1318
+ cut();
1042
1319
  continue;
1043
- } // quoting joins, as the shell does: cl'aude' is claude
1320
+ }
1044
1321
  if (/[|;&\n()]/.test(ch)) {
1045
- segs.push({ text: cur, spanOf: curSpans });
1046
- cur = '';
1047
- curSpans = [];
1322
+ cut();
1048
1323
  continue;
1049
1324
  }
1050
1325
  add(ch, -1);
1051
1326
  }
1052
1327
  segs.push({ text: cur, spanOf: curSpans });
1328
+ if (undecodable)
1329
+ nested.push({ words: ['codex', '--holmes-unjudged-escape'], spans: [-1, -1] });
1053
1330
  for (const seg of segs) {
1054
1331
  // 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
1332
  const rawWords = [];
@@ -1069,10 +1346,33 @@ function agentLaunchSegments(command) {
1069
1346
  continue;
1070
1347
  }
1071
1348
  const s = seg.spanOf[k];
1349
+ // @implements A-SPEC-774.69 — an unquoted ${IFS} or $IFS splits words, as field splitting does (F1.2-c)
1350
+ if (s === -1 && c === '$') {
1351
+ const ifs = /^\$(?:\{IFS\}|IFS(?![A-Za-z0-9_]))/.exec(seg.text.slice(k));
1352
+ if (ifs && seg.spanOf.slice(k, k + ifs[0].length).every((x) => x === -1)) {
1353
+ flush();
1354
+ k += ifs[0].length - 1;
1355
+ continue;
1356
+ }
1357
+ }
1072
1358
  wspan = wspan === null ? s : wspan === s ? s : -1;
1073
1359
  wcur += c;
1074
1360
  }
1075
1361
  flush();
1362
+ // @implements A-SPEC-774.69 — an agent name followed by an expansion runs whatever the expansion holds: the name, then
1363
+ // an option no list allows
1364
+ const AGENT_BEFORE_EXPANSION = (w) => {
1365
+ const at = w.indexOf('$');
1366
+ if (at <= 0)
1367
+ return null;
1368
+ const name = w.slice(0, at);
1369
+ return program.test(name.split(/[\\/]/).pop() ?? name) ? name : null;
1370
+ };
1371
+ for (let r = rawWords.length - 1; r >= 0; r--) {
1372
+ const name = rawWords[r].span === -1 ? AGENT_BEFORE_EXPANSION(rawWords[r].w) : null;
1373
+ if (name !== null)
1374
+ rawWords.splice(r, 1, { w: name, span: -1 }, { w: '--holmes-unjudged-expansion', span: -1 });
1375
+ }
1076
1376
  const words = rawWords.map((r) => r.w);
1077
1377
  const wordSpans = rawWords.map((r) => r.span);
1078
1378
  let i = 0;
@@ -1081,10 +1381,12 @@ function agentLaunchSegments(command) {
1081
1381
  const rest = words.slice(i);
1082
1382
  if (rest.length === 0)
1083
1383
  continue;
1384
+ if (isHolmesReport(rest, wordSpans.slice(i), spanQuote))
1385
+ continue; // @implements A-SPEC-774.67 — the product's own report command
1084
1386
  const base = (w) => w.split(/[\\/]/).pop() ?? w;
1085
1387
  const pkgOf = (w) => (/^(@?[^@]+)/.exec(w) ?? ['', ''])[1];
1086
1388
  // 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)));
1389
+ const isAgent = (w) => [w, w.slice(w.lastIndexOf('=') + 1)].some((v) => program.test(base(v)) || (program === AGENT_CLI && AGENT_PACKAGES.has(pkgOf(v))));
1088
1390
  if (!rest.some(isAgent))
1089
1391
  continue;
1090
1392
  const lead = base(rest[0]);
@@ -1116,7 +1418,263 @@ function agentLaunchSegments(command) {
1116
1418
  continue;
1117
1419
  found.push({ words, spans: wordSpans }); // with the leading NAME=value words: the interactive allowlist judges them (774.11)
1118
1420
  }
1119
- return found;
1421
+ return [...found, ...nested];
1422
+ }
1423
+ /**
1424
+ * @implements A-SPEC-774.75 — one `$'…'` escape from `at` (the character after the backslash), as bash 5 decodes it: its
1425
+ * text and how many characters it consumed; null when it names no character (above U+10FFFF, a surrogate, `\c` at the end).
1426
+ */
1427
+ function ansiEscape(text, at) {
1428
+ const n = text[at] ?? '';
1429
+ if (n === 'x' || n === 'u' || n === 'U') {
1430
+ 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];
1431
+ if (d === '')
1432
+ return { text: `\\${n}`, length: 1 }; // no digits: as written
1433
+ const code = parseInt(d, 16);
1434
+ if (code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff))
1435
+ return null;
1436
+ return { text: String.fromCodePoint(code), length: 1 + d.length };
1437
+ }
1438
+ if (n >= '0' && n <= '7') {
1439
+ const d = /^[0-7]{1,3}/.exec(text.slice(at, at + 3))[0];
1440
+ return { text: String.fromCharCode(parseInt(d, 8) & 0xff), length: d.length };
1441
+ }
1442
+ if (n === 'c')
1443
+ return at + 1 < text.length && text[at + 1] !== "'" ? { text: String.fromCharCode(text.charCodeAt(at + 1) & 0x1f), length: 2 } : null;
1444
+ const simple = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
1445
+ return { text: simple[n] ?? `\\${n}`, length: 1 };
1446
+ }
1447
+ /**
1448
+ * @implements A-SPEC-774.75 — a here-document's delimiter word from `at` (after `<<`): read to a blank or `;&|<>()`, its
1449
+ * quotes removed; any quoting makes the body quoted (`E"O"F` waits for `EOF`). Null when there is no word or a quote is
1450
+ * left open before the newline.
1451
+ */
1452
+ function hereDocWord(text, at) {
1453
+ let i = at;
1454
+ const strip = text[i] === '-';
1455
+ if (strip)
1456
+ i++;
1457
+ while (text[i] === ' ' || text[i] === '\t')
1458
+ i++;
1459
+ const start = i;
1460
+ let delim = '';
1461
+ let quoted = false;
1462
+ while (i < text.length && !/[\s;&|<>()]/.test(text[i])) {
1463
+ const c = text[i];
1464
+ if (c === "'" || c === '"') {
1465
+ const close = text.indexOf(c, i + 1);
1466
+ const nl = text.indexOf('\n', i + 1);
1467
+ if (close < 0 || (nl >= 0 && nl < close))
1468
+ return null;
1469
+ delim += text.slice(i + 1, close);
1470
+ quoted = true;
1471
+ i = close + 1;
1472
+ continue;
1473
+ }
1474
+ if (c === '\\') {
1475
+ if (i + 1 >= text.length || text[i + 1] === '\n')
1476
+ return null;
1477
+ delim += text[i + 1];
1478
+ quoted = true;
1479
+ i += 2;
1480
+ continue;
1481
+ }
1482
+ delim += c;
1483
+ i++;
1484
+ }
1485
+ return i === start ? null : { delim, quoted, strip, end: i };
1486
+ }
1487
+ /**
1488
+ * @implements A-SPEC-774.72 — the one quote state machine (F1.3-e, f): single quotes, double quotes, `$'…'` with its
1489
+ * backslash escapes, a `#` comment from a word start to the newline, and here-document bodies after the newline that
1490
+ * ends their `<<` line. The substitution scan, the here-document list and the segment lexer all read this.
1491
+ */
1492
+ // @implements A-SPEC-774.81 — exported so each branch can be pinned directly
1493
+ function scanShell(command) {
1494
+ const kind = new Array(command.length).fill(0 /* Ch.Code */);
1495
+ const docs = [];
1496
+ const pending = [];
1497
+ let segStart = 0;
1498
+ // @implements A-SPEC-774.75 — the separator before `#` must itself be unescaped (`a\ #x` is one word; a line
1499
+ // continuation is not taken to start a comment either, the conservative reading)
1500
+ const wordStart = (k) => k === 0 || (/[\s;&|()]/.test(command[k - 1]) && kind[k - 2] !== 8 /* Ch.Escape */);
1501
+ let inBacktick = false; // a comment inside backticks ends before the closing backtick
1502
+ let leadAt = -1; // a segment's lead word, read once per segment
1503
+ let lead = '';
1504
+ for (let k = 0; k < command.length; k++) {
1505
+ const ch = command[k];
1506
+ if (ch === '\\') {
1507
+ kind[k] = 8 /* Ch.Escape */;
1508
+ k++;
1509
+ continue;
1510
+ }
1511
+ if (ch === '`') {
1512
+ inBacktick = !inBacktick;
1513
+ continue;
1514
+ }
1515
+ if (ch === "'") {
1516
+ kind[k] = 7 /* Ch.Delim */;
1517
+ let j = k + 1;
1518
+ for (; j < command.length && command[j] !== "'"; j++)
1519
+ kind[j] = 1 /* Ch.Single */;
1520
+ if (j < command.length)
1521
+ kind[j] = 7 /* Ch.Delim */;
1522
+ k = j;
1523
+ continue;
1524
+ }
1525
+ if (ch === '$' && command[k + 1] === "'") {
1526
+ kind[k] = 7 /* Ch.Delim */;
1527
+ kind[k + 1] = 7 /* Ch.Delim */;
1528
+ let j = k + 2;
1529
+ for (; j < command.length && command[j] !== "'"; j++) {
1530
+ if (command[j] === '\\') {
1531
+ kind[j] = 8 /* Ch.Escape */;
1532
+ j++;
1533
+ if (j < command.length)
1534
+ kind[j] = 3 /* Ch.Ansi */;
1535
+ continue;
1536
+ }
1537
+ kind[j] = 3 /* Ch.Ansi */;
1538
+ }
1539
+ if (j < command.length)
1540
+ kind[j] = 7 /* Ch.Delim */;
1541
+ k = j;
1542
+ continue;
1543
+ }
1544
+ if (ch === '"') {
1545
+ kind[k] = 7 /* Ch.Delim */;
1546
+ let j = k + 1;
1547
+ for (; j < command.length && command[j] !== '"'; j++) {
1548
+ if (command[j] === '\\') {
1549
+ kind[j] = 8 /* Ch.Escape */;
1550
+ j++;
1551
+ if (j < command.length)
1552
+ kind[j] = 2 /* Ch.Double */;
1553
+ continue;
1554
+ }
1555
+ kind[j] = 2 /* Ch.Double */;
1556
+ }
1557
+ if (j < command.length)
1558
+ kind[j] = 7 /* Ch.Delim */;
1559
+ k = j;
1560
+ continue;
1561
+ }
1562
+ if (ch === '#' && wordStart(k)) {
1563
+ let j = k;
1564
+ for (; j < command.length && command[j] !== '\n' && !(inBacktick && command[j] === '`'); j++)
1565
+ kind[j] = 4 /* Ch.Comment */;
1566
+ k = j - 1;
1567
+ continue;
1568
+ }
1569
+ if (/[|;&()]/.test(ch)) {
1570
+ segStart = k + 1;
1571
+ continue;
1572
+ }
1573
+ // @implements A-SPEC-774.75 — `<<<` is a here-string, never a here-document at its second `<`
1574
+ if (ch === '<' && command[k + 1] === '<' && command[k + 2] === '<') {
1575
+ k += 2;
1576
+ continue;
1577
+ }
1578
+ if (ch === '<' && command[k + 1] === '<') {
1579
+ const w = hereDocWord(command, k + 2);
1580
+ if (w) {
1581
+ if (leadAt !== segStart) {
1582
+ leadAt = segStart;
1583
+ lead = ((/^\s*(\S*)/.exec(command.slice(segStart, k)) ?? ['', ''])[1]).split('/').pop() ?? '';
1584
+ }
1585
+ pending.push({ delim: w.delim, quoted: w.quoted, strip: w.strip, lead });
1586
+ k = w.end - 1;
1587
+ }
1588
+ continue;
1589
+ }
1590
+ if (ch === '\n') {
1591
+ segStart = k + 1;
1592
+ let at = k + 1;
1593
+ for (const h of pending.splice(0)) {
1594
+ let line = at;
1595
+ let bodyEnd = command.length;
1596
+ let next = command.length;
1597
+ let terminated = false;
1598
+ for (;;) {
1599
+ const nl = command.indexOf('\n', line);
1600
+ const text = command.slice(line, nl < 0 ? command.length : nl);
1601
+ if ((h.strip ? text.replace(/^\t+/, '') : text) === h.delim) {
1602
+ bodyEnd = line;
1603
+ next = nl < 0 ? command.length : nl + 1;
1604
+ terminated = true;
1605
+ break;
1606
+ }
1607
+ if (nl < 0)
1608
+ break;
1609
+ line = nl + 1;
1610
+ }
1611
+ for (let b = at; b < next; b++)
1612
+ kind[b] = b < bodyEnd && !h.quoted ? 5 /* Ch.Body */ : 6 /* Ch.QuotedBody */;
1613
+ docs.push({ bodyStart: at, bodyEnd, next, quoted: h.quoted, lead: h.lead, terminated });
1614
+ at = next;
1615
+ }
1616
+ if (at > k + 1) {
1617
+ k = at - 1;
1618
+ segStart = at;
1619
+ }
1620
+ }
1621
+ }
1622
+ return { kind, docs };
1623
+ }
1624
+ /**
1625
+ * @implements A-SPEC-774.68 — the bodies of the command substitutions outside single quotes: `$(…)` to its balanced `)`
1626
+ * and `` `…` `` to the next unescaped backtick, each to the end of the text when unclosed; nested bodies are found when
1627
+ * their body is judged in turn.
1628
+ * @implements A-SPEC-774.69 — read as the shell quotes: an apostrophe inside double quotes is a character, `$'…'` ends at
1629
+ * its first unescaped `'`, an unquoted here-document body is text in which substitutions run and a quoted one is skipped.
1630
+ * At most 64; `overflow` says a 65th was left unread, which the caller judges as a launch (review 18:43, F1.2-a, b).
1631
+ */
1632
+ function substitutionBodies(command, scan = scanShell(command)) {
1633
+ const out = [];
1634
+ let overflow = false;
1635
+ const take = (body) => { if (out.length >= 64)
1636
+ overflow = true;
1637
+ else
1638
+ out.push(body); };
1639
+ const { kind } = scan; // @implements A-SPEC-774.72 — the one scanner (774.75: handed over, not computed again)
1640
+ /** `$(…)` from `k` (at `$`), or a backtick span from `k`; the index of its last character. */
1641
+ const substitutionAt = (text, k) => {
1642
+ if (text[k] === '$') {
1643
+ let depth = 0;
1644
+ let j = k + 1;
1645
+ for (; j < text.length; j++) {
1646
+ if (text[j] === '\\') {
1647
+ j++;
1648
+ continue;
1649
+ }
1650
+ if (text[j] === '(')
1651
+ depth++;
1652
+ else if (text[j] === ')' && --depth === 0)
1653
+ break;
1654
+ }
1655
+ take(text.slice(k + 2, j));
1656
+ return j;
1657
+ }
1658
+ let j = k + 1;
1659
+ while (j < text.length && text[j] !== '`')
1660
+ j += text[j] === '\\' ? 2 : 1;
1661
+ take(text.slice(k + 1, j));
1662
+ return j;
1663
+ };
1664
+ for (let k = 0; k < command.length; k++) {
1665
+ const t = kind[k];
1666
+ if (t === 8 /* Ch.Escape */) {
1667
+ k++;
1668
+ continue;
1669
+ }
1670
+ // substitutions run in code, in double quotes and in an unquoted here-document body; nowhere else
1671
+ if (t !== 0 /* Ch.Code */ && t !== 2 /* Ch.Double */ && t !== 5 /* Ch.Body */)
1672
+ continue;
1673
+ const ch = command[k];
1674
+ if ((ch === '$' && command[k + 1] === '(') || ch === '`')
1675
+ k = substitutionAt(command, k);
1676
+ }
1677
+ return { bodies: out, overflow };
1120
1678
  }
1121
1679
  function dumpsEnvInCommandPosition(command, depth = 0) {
1122
1680
  if (depth > 3)
@@ -1273,8 +1831,8 @@ function shellPatchOf(command) {
1273
1831
  const PATCH_MARKERS = ['apply_patch', 'applypatch', '*** begin patch', '*** add file:', '*** update file:', '*** delete file:', '*** move to:'];
1274
1832
  /** Whether a text shows a marker once its quotes and backslashes are removed and its letters lowered. Substring tests only. */
1275
1833
  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();
1834
+ // A backslash before a line feed is a line continuation: the shell removes both, so both are removed here (A-SPEC-794.52).
1835
+ const plain = (0, line_continuation_1.joinLineContinuations)(text).split('"').join('').split("'").join('').split('\\').join('').toLowerCase();
1278
1836
  // `$'…'` and `$"…"` leave their `$` behind once the quotes are gone (`apply$'_patch'` reads `apply$_patch`), so the
1279
1837
  // text is tested with the dollars removed as well.
1280
1838
  const undollared = plain.split('$').join('');
@@ -1544,6 +2102,7 @@ function decideOnGateError(opts) {
1544
2102
  // spec chain that was never the problem.
1545
2103
  return {
1546
2104
  permissionDecision: 'deny',
2105
+ refusal: 'gate.unjudgeable', // A-SPEC-245.24 (item 1) — the message is the error's, so the code is the site's
1547
2106
  permissionDecisionReason: `[Holmes-Kit] cannot judge due to an internal error — the gate does not allow when it cannot decide: ${opts.message}`
1548
2107
  + ' → 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
2108
  };
@@ -1635,8 +2194,85 @@ function wiredSpecsDir(argv, env) {
1635
2194
  }
1636
2195
  /** Default spec root. Used to tell "never governed" apart from an explicitly configured HOLMES_SPECS. */
1637
2196
  exports.DEFAULT_SPECS_DIR = '.ax/specs';
2197
+ // @implements A-SPEC-222.4, A-SPEC-222.6 — the anchor-move judgment; A-SPEC-222.9 (SD1 1) moved it to succession-guard,
2198
+ // re-exported here for its callers
2199
+ var succession_guard_1 = require("../spec/succession-guard");
2200
+ Object.defineProperty(exports, "anchorMoveOnly", { enumerable: true, get: function () { return succession_guard_1.anchorMoveOnly; } });
1638
2201
  // @implements A-SPEC-100.2
1639
- function evaluateHook(input, specsDir, opts) {
2202
+ /**
2203
+ * @implements A-SPEC-245.2 — the grants one judgement resolved, settled once at its final decision. Each branch that
2204
+ * resolves a grant holds it here instead of spending it: an `.ax/roles` Write spent its grant at the roles branch and
2205
+ * was then denied by the protected-directory branch, which resolved the same approval again and found it gone (one
2206
+ * grant: denied and gone; two: allowed and both gone — measured).
2207
+ */
2208
+ /**
2209
+ * @implements A-SPEC-245.4 — the settlement is an explicit value in `opts`, settled once at the FINAL decision: the
2210
+ * entry point creates it and settles it after the plan-scope, stage, role and run-refusal passes (each can still turn
2211
+ * the allow into a deny, and a run-stage deny spent the grant of an act that never happened), and the counterfactual
2212
+ * audit reading passes one that never spends. A caller that passes none is settled at this function's return.
2213
+ */
2214
+ function settleVerdict(verdict, settlement) {
2215
+ const allowed = verdict.permissionDecision === 'allow';
2216
+ // @implements A-SPEC-245.9 (1b-2) — in the hook's worker, the spend is the main thread's (settleOnMainThread)
2217
+ const pending = settlement.pending();
2218
+ const outcome = allowed && settlement.spends && (pending.held.length > 0 || pending.env.length > 0)
2219
+ ? settlement.adopt((mainThreadSettler ?? settleOnMainThread)(pending))
2220
+ : settlement.settle(allowed);
2221
+ if (outcome === 'settled')
2222
+ return verdict;
2223
+ if (outcome === 'refused') {
2224
+ // A-SPEC-245.24 (item 1) — a spent, revoked or conflicting single-use approval needs a new one from the person
2225
+ 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)` };
2226
+ }
2227
+ 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)' };
2228
+ }
2229
+ /**
2230
+ * @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
2231
+ * waits for its answer. The worker can be terminated at the deadline at any instruction; the main thread is not.
2232
+ */
2233
+ let mainThreadSettler = null;
2234
+ /** @implements A-SPEC-245.9 (1b-2) — the main thread's half: settle the pending spends here and answer. */
2235
+ function settleOnMainThread(p) {
2236
+ // test seam (A-SPEC-245.15, 6c): which thread spent — a boolean switch writing one fixed file inside the judged project
2237
+ // (the pending spends' root, where `.ax` exists), never a path taken from the environment
2238
+ const probeRoot = [...p.held, ...p.env][0]?.root;
2239
+ if (process.env.HOLMES_HOOK_TEST_SPEND_THREAD === '1' && probeRoot && fs.existsSync(path.join(probeRoot, '.ax'))) {
2240
+ try {
2241
+ fs.mkdirSync(path.join(probeRoot, '.ax', 'state'), { recursive: true });
2242
+ fs.writeFileSync(path.join(probeRoot, '.ax', 'state', 'spend-thread-probe'), require('node:worker_threads').isMainThread ? 'main' : 'worker');
2243
+ }
2244
+ catch { /* a seam */ }
2245
+ }
2246
+ const s = approval_grants_1.GrantSettlement.fromPending(p);
2247
+ const outcome = s.settle(true);
2248
+ return { outcome, committed: [...s.committed], ...(s.refusal !== undefined ? { refusal: s.refusal } : {}) };
2249
+ }
2250
+ /** @implements A-SPEC-245.4 (f) — the approval an audit line names: a grant this decision spent, else the counterfactual's environment approval. */
2251
+ function auditApprovalFor(envApproval, counterfactualDenied, settlement) {
2252
+ return settlement.committed[0] ?? (counterfactualDenied ? envApproval : undefined);
2253
+ }
2254
+ function evaluateHook(...args) {
2255
+ const [input, specsDir, opts] = args;
2256
+ // @implements A-SPEC-245.26 (item 1) — a nested reading is one that shares the top reading's `filed` holder (through
2257
+ // `...opts`); a caller's settlement is not that sign: runHookProcess gives one, and taking it for a nested reading lost
2258
+ // the filed request (no run wait) and the advisory on the path every harness runs
2259
+ if (opts.filed !== undefined)
2260
+ return judgeHook(input, specsDir, opts);
2261
+ const filed = {};
2262
+ const settlement = opts.settlement ?? new approval_grants_1.GrantSettlement();
2263
+ const judged = judgeHook(input, specsDir, { ...opts, settlement, filed });
2264
+ // the caller that brought its own settlement settles it (runHookProcess, after the run path); otherwise it is settled here
2265
+ const settled = opts.settlement !== undefined ? judged : settleVerdict(judged, settlement);
2266
+ // @implements A-SPEC-245.25 (item 5a) — a deny carries the request the gate filed; the run path waits on that id only
2267
+ const verdict = settled.permissionDecision === 'deny' && filed.request !== undefined ? { ...settled, request: filed.request } : settled;
2268
+ // @implements A-SPEC-245.19 (item 2) — an allowed command whose text names the act carries the advisory
2269
+ const advice = input.tool_name === 'Bash' && verdict.permissionDecision === 'allow' && typeof input.tool_input.command === 'string'
2270
+ ? lockRecoverAdvisory(input.tool_input.command) : null;
2271
+ if (advice === null)
2272
+ return verdict;
2273
+ return { ...verdict, permissionDecisionReason: [verdict.permissionDecisionReason, advice].filter((t) => typeof t === 'string' && t !== '').join('\n') };
2274
+ }
2275
+ function judgeHook(input, specsDir, opts) {
1640
2276
  // @implements A-SPEC-790.2 — a Codex shell payload on Windows: the Bash reading first (a denial there is the decision,
1641
2277
  // and nothing more is filed); then the PowerShell text Codex actually runs. Only ever stricter than the Bash reading.
1642
2278
  const codexPs = input.codexPowerShell;
@@ -1650,7 +2286,7 @@ function evaluateHook(input, specsDir, opts) {
1650
2286
  return bashVerdict;
1651
2287
  if ('unjudgeable' in codexPs) {
1652
2288
  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)` };
2289
+ 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
2290
  }
1655
2291
  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
2292
  }
@@ -1666,13 +2302,14 @@ function evaluateHook(input, specsDir, opts) {
1666
2302
  // @implements A-SPEC-790 — a PowerShell command whose text cannot be read is refused rather than judged.
1667
2303
  const psUnjudgeable = input.powershellUnjudgeable;
1668
2304
  if (psUnjudgeable !== undefined) {
1669
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] a PowerShell command that cannot be judged (${psUnjudgeable}) is refused (REQ-790)` };
2305
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] a PowerShell command that cannot be judged (${psUnjudgeable}) is refused (REQ-790)` };
1670
2306
  }
1671
2307
  if (input.patchUnreadable) {
1672
2308
  const cause = input;
1673
2309
  // @implements A-SPEC-769.7 — four conditions, four sentences: shell marker, no-op update, and (below) the
1674
2310
  // 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'
2311
+ return { permissionDecision: 'deny', refusal: cause.patchUnreadableCause === 'shell-marker' || cause.patchUnreadableCause === 'no-op' ? 'patch.unreadable' : 'target.unresolvable',
2312
+ permissionDecisionReason: cause.patchUnreadableCause === 'shell-marker'
1676
2313
  ? SHELL_MARKED_REASON : cause.patchUnreadableCause === 'no-op' ? patchNoopReason(cause.patchNoopPaths ?? []) : PATCH_UNREADABLE_REASON };
1677
2314
  }
1678
2315
  const patchTargets = input.tool_input.patch_targets;
@@ -1696,7 +2333,8 @@ function evaluateHook(input, specsDir, opts) {
1696
2333
  return null;
1697
2334
  }
1698
2335
  };
1699
- const judged = (file, r) => r === null ? { deny: PATCH_UNREADABLE_REASON } : 'failure' in r ? { deny: patchNotAppliedReason(file, r.failure) } : { content: r.result };
2336
+ // A-SPEC-245.24 (item 1) — each deny with its code: an unreadable target, or a patch that does not apply
2337
+ 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
2338
  // @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
2339
  // applies them in sequence, the gate reads the disk once. One file is one key whatever link or letter case names it.
1702
2340
  // (What a shell could rewrite is settled before this point: only the one quoted-heredoc form reaches here.)
@@ -1704,7 +2342,7 @@ function evaluateHook(input, specsDir, opts) {
1704
2342
  for (const t of patchTargets) {
1705
2343
  const file = patchFileKey(at(t.path));
1706
2344
  if (files.has(file))
1707
- return { permissionDecision: 'deny', permissionDecisionReason: PATCH_UNREADABLE_REASON };
2345
+ return { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: PATCH_UNREADABLE_REASON };
1708
2346
  files.add(file);
1709
2347
  }
1710
2348
  for (const t of patchTargets) {
@@ -1714,13 +2352,13 @@ function evaluateHook(input, specsDir, opts) {
1714
2352
  else if (t.kind === 'update' && t.movedTo === undefined) {
1715
2353
  const j = judged(at(t.path), resultOf(at(t.path), t.hunk ?? ''));
1716
2354
  if ('deny' in j)
1717
- return { permissionDecision: 'deny', permissionDecisionReason: j.deny };
2355
+ return { permissionDecision: 'deny', refusal: j.refusal, permissionDecisionReason: j.deny };
1718
2356
  content = j.content;
1719
2357
  }
1720
2358
  else if (t.kind === 'move') {
1721
2359
  const j = judged(at(t.from ?? t.path), t.from === undefined ? null : resultOf(at(t.from), t.hunk ?? ''));
1722
2360
  if ('deny' in j)
1723
- return { permissionDecision: 'deny', permissionDecisionReason: j.deny };
2361
+ return { permissionDecision: 'deny', refusal: j.refusal, permissionDecisionReason: j.deny };
1724
2362
  content = j.content;
1725
2363
  }
1726
2364
  // Judged as a patch tool's write whichever tool carried the patch, so the shell branch below is not re-entered.
@@ -1750,7 +2388,22 @@ function evaluateHook(input, specsDir, opts) {
1750
2388
  }
1751
2389
  return fullCache;
1752
2390
  };
1753
- const hintOrRoute = (req, extra) => (fullEntry() !== null ? (0, full_autonomy_1.fullModeRefusalTail)(req.kind) : (0, approval_queue_1.queueHint)(opts.projectRoot, req, extra));
2391
+ const hintOrRoute = (req, extra) => (fullEntry() !== null ? (0, full_autonomy_1.fullModeRefusalTail)(req.kind) : fileHint(req, extra));
2392
+ // @implements A-SPEC-245.25 (item 5a) — the request the gate filed (or found already pending: the queue drops the
2393
+ // duplicate, and its hint then names no id), recorded for the verdict by its own id, never read from text
2394
+ function fileHint(req, extra) {
2395
+ const hint = (0, approval_queue_1.queueHint)(opts.projectRoot, req, extra);
2396
+ if (opts.filed !== undefined) {
2397
+ // A-SPEC-245.26 (4b) — the id the queue derives from the request itself, never one parsed from the hint
2398
+ const id = (0, approval_queue_1.approvalRequestId)(req.kind, req.target);
2399
+ if (hint !== '' || (0, approval_queue_1.readQueue)(opts.projectRoot).pending.some((p) => p.id === id))
2400
+ opts.filed.request = id;
2401
+ }
2402
+ return hint;
2403
+ }
2404
+ // @implements A-SPEC-245.24 (item 1) — the code of a deny that ends with hintOrRoute: under a full profile the tail is
2405
+ // the full-autonomy refusal (nothing was filed), otherwise the site's own code
2406
+ const routeCode = (base) => (fullEntry() !== null ? 'full-autonomy.refused' : base);
1754
2407
  // @implements A-SPEC-125.4
1755
2408
  // Bash/shell risk gate: this branch runs BEFORE the Write/Edit phaseCheck logic below and
1756
2409
  // is intentionally fail-CLOSED — a classifier throw on the Bash surface denies, never
@@ -1768,7 +2421,30 @@ function evaluateHook(input, specsDir, opts) {
1768
2421
  // shapes of repeated separators took 2.4–6.1 s at 256 KB, their cost spread over every segment of every rule (measured).
1769
2422
  const segmentsOnce = (0, write_target_2.shellSegments)(command, shellBase);
1770
2423
  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)` };
2424
+ 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)` };
2425
+ }
2426
+ // @implements A-SPEC-792.14 — a push cannot carry a spec change no grant accounts for off the machine
2427
+ // A-SPEC-794.52, A-SPEC-794.53 — a push written across a line continuation is still a push; comments and
2428
+ // here-document bodies go first, in the order the flag judgement reads. A-SPEC-794.54 — only a command that names git
2429
+ // and push is read further (the reader only removes text and a `$` before a quote, so it adds no word), and one the
2430
+ // reader cannot finish is read whole
2431
+ const joined = (0, line_continuation_1.joinLineContinuations)(command);
2432
+ 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)))) {
2433
+ try {
2434
+ const seam = require('../governance/spec-seam').unexplainedSpecChanges(opts.projectRoot, specsDir);
2435
+ // @implements A-SPEC-222.15 (item 5) — a scan finding is refused with its own reason and no unstage or reset advice
2436
+ const scans = seam.filter((u) => u.where === 'scan');
2437
+ if (scans.length > 0) {
2438
+ 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)` };
2439
+ }
2440
+ if (seam.length > 0) {
2441
+ const named = seam.slice(0, 5).map((u) => u.where === 'index' ? `staged ${u.path}` : `commit ${(u.commit ?? '').slice(0, 12)} changes ${u.path}`).join('; ');
2442
+ 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)` };
2443
+ }
2444
+ }
2445
+ catch {
2446
+ 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)' };
2447
+ }
1772
2448
  }
1773
2449
  // Git-aware rm signals (H1): resolved only when a resolver is injected (the CLI wires the real
1774
2450
  // git-backed one; unit tests omit it and exercise the pure static path). Fail-open: a throwing
@@ -1805,9 +2481,9 @@ function evaluateHook(input, specsDir, opts) {
1805
2481
  catch (e) {
1806
2482
  // @implements A-SPEC-728 (rule 44) — a classifier bound says what it is: too large to judge, not a classifier failure.
1807
2483
  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)` };
2484
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: `[Holmes-Kit] ${e.message} — refused rather than judged; split it into smaller commands (A-SPEC-728)` };
1809
2485
  }
1810
- return { permissionDecision: 'deny', permissionDecisionReason: '[Holmes-Kit] risk classification failed on a shell command — denied (fail-closed)' };
2486
+ return { permissionDecision: 'deny', refusal: 'gate.unjudgeable', permissionDecisionReason: '[Holmes-Kit] risk classification failed on a shell command — denied (fail-closed)' };
1811
2487
  }
1812
2488
  // @implements A-SPEC-133
1813
2489
  // Hard-hitl needs an approval that COVERS this specific command (scope + not expired), and if
@@ -1828,52 +2504,105 @@ function evaluateHook(input, specsDir, opts) {
1828
2504
  const legacySessionApproval = approval?.scope === undefined
1829
2505
  && (0, risk_gate_1.approvalCovers)(approval, { kind: 'config-write', target: command }, nowTs);
1830
2506
  let hardHitlCovered = false;
2507
+ // @implements A-SPEC-792.32 — the staging approvals this act carries, recorded only at the final allow
2508
+ let autonomousStaging = null;
2509
+ let personStaging = false;
2510
+ // @implements A-SPEC-794.49 — REQ-792: push and publish follow the profile's flags, and no grant lifts it
2511
+ const outwardEntry = fullEntry();
2512
+ const outwardRoute = outwardEntry === null ? null : (0, full_autonomy_1.fullModeOutwardRefusal)((0, risk_classifier_1.outwardActsOf)(command), outwardEntry);
2513
+ if (outwardRoute !== null) {
2514
+ return { permissionDecision: 'deny', refusal: 'full-autonomy.refused', permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: a push or a publish is irreversible and outward — refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', outwardRoute)}` };
2515
+ }
1831
2516
  if (assessment.level === 'hard-hitl') {
1832
2517
  // @implements A-SPEC-245 — env first, then the grant files. The grant's mandatory nonce rides
1833
2518
  // the SAME atomic ledger consumption below, so hard-hitl single-use needs no new machinery.
1834
2519
  const resolved = resolveForCommand('shell');
1835
2520
  const covers = resolved !== undefined;
1836
- const deny = (why) => ({
2521
+ // @implements A-SPEC-245.24 (item 1, R1) — the reasons quote agent-chosen names (an alias, a hook name), so the code
2522
+ // is the site's: approval.required, or the full-autonomy refusal on the full-profile paths
2523
+ const deny = (why, refusal = 'approval.required') => ({
1837
2524
  permissionDecision: 'deny',
2525
+ refusal,
1838
2526
  permissionDecisionReason: `[Holmes-Kit] hard-hitl risk: ${assessment.reasons.join('; ')} — ${why}`,
1839
2527
  });
1840
2528
  // @implements A-SPEC-244 — the refusal itself files the review request. The queue kind is the
1841
2529
  // approval SCOPE kind ('shell'), so the reviewing CLI can mint a covering grant mechanically.
1842
2530
  hardHitlCovered = covers;
1843
- const full = covers ? null : fullEntry();
1844
- if (full !== null) {
2531
+ const fullScope = covers ? null : fullEntry();
2532
+ // @implements A-SPEC-792.28 — H2-a: governance staging under a full profile is approved by machine conditions
2533
+ // (autonomous-shell.ts judges; this records), and a failed condition is named on today's path
2534
+ let h2Note = '';
2535
+ if (fullScope !== null) {
2536
+ const auto = require('../governance/autonomous-shell');
2537
+ if (auto.governanceStagingOnly(assessment.reasons)) {
2538
+ // @implements A-SPEC-792.31 — the verdict is told where the spec store is
2539
+ const specsRel = path.relative(opts.projectRoot, specsDir).split(path.sep).join('/');
2540
+ // @implements A-SPEC-792.32 — one base (the shell's), and the stop lifted only by a caller's programmatic option
2541
+ const verdict = auto.autonomousShellVerdict({ command, root: opts.projectRoot, shellStaging: (0, config_1.loadConfig)(opts.projectRoot).autonomy.shellStaging, specsRel,
2542
+ base: shellBase, specStaging: opts.autonomySpecStaging === true }, auto.realShellDeps(opts.projectRoot));
2543
+ if (verdict.ok) {
2544
+ // @implements A-SPEC-792.32 — approved here, recorded at the final allow (every later Bash gate first), and
2545
+ // what is recorded is the verdict's proven (path, blob) pairs, computed from the bytes it proved
2546
+ autonomousStaging = { scope: fullScope.scope, paths: verdict.paths, proven: verdict.proven, conditions: verdict.conditions };
2547
+ hardHitlCovered = true;
2548
+ }
2549
+ else
2550
+ h2Note = ` (autonomous shell approval: ${verdict.failed} — ${verdict.detail})`;
2551
+ }
2552
+ }
2553
+ if (autonomousStaging === null) {
1845
2554
  // @implements A-SPEC-792.5 — a full scope approves a scoped destructive act after a recovery point and refuses
1846
2555
  // 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;
2556
+ // @implements A-SPEC-792.10 — except spec staging, which goes to the person's form like it does without a profile.
2557
+ const v = fullScope === null ? null
2558
+ : (0, full_autonomy_1.fullModeShellVerdict)({ command, reasons: assessment.reasons, cwd: shellBase, workspace: opts.projectRoot, scratchRoot: (0, scratch_root_1.trustedScratchRoot)(), entry: fullScope });
2559
+ const full = v === null || v.outcome === 'ask' ? null : fullScope;
2560
+ if (full !== null && v !== null && v.outcome !== 'ask') {
2561
+ if (v.outcome === 'refuse')
2562
+ return deny(`refused${h2Note}${(0, full_autonomy_1.fullModeRefusalTail)('shell', v.route)}`, 'full-autonomy.refused');
2563
+ let recoveryRef;
2564
+ if (v.recovery) {
2565
+ const r = (0, full_autonomy_1.writeRecoveryRef)(opts.projectRoot, nowTs);
2566
+ if ('error' in r)
2567
+ return deny(`refused${(0, full_autonomy_1.fullModeRefusalTail)('shell', r.error)}`, 'full-autonomy.refused');
2568
+ recoveryRef = r.ref;
2569
+ }
2570
+ try {
2571
+ new ledger_store_1.FileLedgerStore(path.join(opts.projectRoot, '.ax', 'ledger')).append({
2572
+ ts: nowTs, actor: `full-autonomy:${full.scope}`, kind: 'full-autonomy-approved',
2573
+ summary: `hard-hitl shell act approved under full autonomy${recoveryRef ? ` (recovery ${recoveryRef})` : ''}`.slice(0, 200),
2574
+ inputs: [crypto.createHash('sha256').update(command).digest('hex')],
2575
+ rationale: assessment.reasons.join('; ').slice(0, 300),
2576
+ });
2577
+ }
2578
+ catch { /* the act is approved; the audit row is best effort like the other gate records */ }
2579
+ hardHitlCovered = true;
1856
2580
  }
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
- });
2581
+ else if (!covers) {
2582
+ // @implements A-SPEC-564.2 — the base reason's length rides along so the refusal record
2583
+ // knows the FULL feedback cost (base + hint), not just the hint's half.
2584
+ const base = `requires an approval that covers this command${h2Note}`;
2585
+ const refused = deny(base
2586
+ + fileHint({ kind: 'shell', target: command, why: assessment.reasons.join('; ') }, { baseReasonBytes: base.length }));
2587
+ // @implements A-SPEC-794.55 — staging spec files by their paths is a request for a person, not a read gone wrong:
2588
+ // the person's route comes first, and the classifier's reason follows unchanged
2589
+ if ((0, full_autonomy_1.onlyStagesSpecs)(command, shellBase, opts.projectRoot)) {
2590
+ 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: ');
2591
+ }
2592
+ return refused;
2593
+ }
2594
+ else {
2595
+ pendingApprovals.push(resolved);
2596
+ // @implements A-SPEC-792.13 — a granted act that stages records what it stages, so the seam can tell it apart (a
2597
+ // literal spec path is refused as an opaque .ax act before the staging rule names it)
2598
+ // @implements A-SPEC-792.15 — only an act the gate judged as spec staging (or an opaque .ax act): an unrelated
2599
+ // approval that merely holds the words grants nothing
2600
+ // @implements A-SPEC-792.32 — recorded at the final allow, after every later Bash gate
2601
+ if (/\bgit\b/.test(command) && /\b(?:add|stage|commit)\b/.test(command)
2602
+ && 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))) {
2603
+ personStaging = true;
2604
+ }
1864
2605
  }
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
2606
  }
1878
2607
  }
1879
2608
  // Bash BYPASS gates (adversarial review: `cat > evil.ts` created ungoverned files, `echo x >
@@ -1979,6 +2708,16 @@ function evaluateHook(input, specsDir, opts) {
1979
2708
  // request id is printed: none exists until the operator runs the command, which files it.
1980
2709
  // @implements A-SPEC-753.3 — the exact grammar first; otherwise any command of the line that applies. The
1981
2710
  // operator part is that one command as written, not the whole line.
2711
+ // @implements A-SPEC-245.9 (1b-5) — the operator's act, refused here in every harness's spelling
2712
+ if (lockRecoverAct(command)) {
2713
+ return {
2714
+ permissionDecision: 'deny',
2715
+ // @implements A-SPEC-245.22 (item 5) — the act's name only: the agent's words chose the refusal code (a
2716
+ // command holding "this run stopped" was coded run.stopped), and A-SPEC-792.1 spells no command for a person
2717
+ 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).',
2718
+ refusal: 'operator-act.refused', // A-SPEC-245.23 (item 3)
2719
+ };
2720
+ }
1982
2721
  const installerExact = legacySessionApproval ? null : (0, shell_argument_roles_1.installerInvocationOf)(command);
1983
2722
  const installerApply = legacySessionApproval ? null
1984
2723
  : installerExact === 'apply' ? command
@@ -1986,12 +2725,14 @@ function evaluateHook(input, specsDir, opts) {
1986
2725
  if (installerApply !== null) {
1987
2726
  return {
1988
2727
  permissionDecision: 'deny',
2728
+ refusal: 'launch.refused', // A-SPEC-245.24
1989
2729
  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
2730
  };
1991
2731
  }
1992
2732
  if (!legacySessionApproval && startsHolmesServer(command)) {
1993
2733
  return {
1994
2734
  permissionDecision: 'deny',
2735
+ refusal: 'launch.refused', // A-SPEC-245.24
1995
2736
  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
2737
  };
1997
2738
  }
@@ -2013,7 +2754,8 @@ function evaluateHook(input, specsDir, opts) {
2013
2754
  if (!hint && (0, approval_queue_1.readQueue)(opts.projectRoot).pending.some((request) => request.id === id)) {
2014
2755
  hint = ` — approval request ${id} is pending; retry after operator approval`;
2015
2756
  }
2016
- return { permissionDecision: 'deny', permissionDecisionReason: reason
2757
+ // A-SPEC-245.24 (item 1) — a launch with a gate-off setting or in a run is a launch; the others read secrets
2758
+ return { permissionDecision: 'deny', refusal: routeCode(GATE_OFF !== null || AGENT_LAUNCH ? 'launch.refused' : 'secret.access'), permissionDecisionReason: reason
2017
2759
  + (hint || ' — could not persist the approval request; ask the operator to check the project approval queue storage') };
2018
2760
  }
2019
2761
  pendingApprovals.push(resolved);
@@ -2025,7 +2767,8 @@ function evaluateHook(input, specsDir, opts) {
2025
2767
  // `cp`, `mv`, `install`, `ln -f`, `dd of=`, `rsync` and `sed -i` write the same file just as
2026
2768
  // well. A gate that names one syntax for an act is a gate over that syntax, not over the act.
2027
2769
  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-]+)?)';
2770
+ // @implements A-SPEC-792.35 — and what git runs: .git/config, .git/info/*, .git/hooks/* and any .gitattributes
2771
+ const CONFIG_FILE = '(?:\\.claude[\\\\/]settings[\\w.-]*\\.json|\\.mcp\\.json|\\.env(?!\\.(?:example|sample|template|dist))(?:\\.[\\w-]+)?|\\.git[\\\\/](?:config|(?:info|hooks)[\\\\/][\\w.-]+)|\\.gitattributes)';
2029
2772
  // @implements A-SPEC-448
2030
2773
  // Paths an INTERPRETER one-liner writes. The residual both shell rules recorded, closed by
2031
2774
  // asking for the evidence of a write rather than for an interpreter's name near a pattern.
@@ -2124,7 +2867,7 @@ function evaluateHook(input, specsDir, opts) {
2124
2867
  }
2125
2868
  return out;
2126
2869
  };
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)` };
2870
+ 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
2871
  const isTilde = (p) => p === '~' || p.startsWith('~/');
2129
2872
  // Relative candidate in a segment whose base is unknowable (dynamic cd argument): 'unknown',
2130
2873
  // and the caller fails CLOSED — but only when such a candidate exists, so `cd "$X" && npm
@@ -2190,13 +2933,15 @@ function evaluateHook(input, specsDir, opts) {
2190
2933
  // tell reading from writing costs more than the hole it closes; the same residual is already
2191
2934
  // recorded for the code-write rule below.
2192
2935
  if (configWrite) {
2193
- return { permissionDecision: 'deny', permissionDecisionReason: registry_1.MESSAGES.INTEGRITY_CONFIG_EDIT('.claude/settings, .env, .mcp.json', 'A-SPEC-191') };
2936
+ 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
2937
  }
2195
2938
  // @implements A-SPEC-728 — the harness config that loads THIS session's gate also lives outside
2196
2939
  // the project: `~/.claude/settings*.json` and Codex's user-level `config.toml`/`hooks.json`
2197
2940
  // (the only place codex-cli 0.155 loads Holmes from). Judged by identity after `~`/`$HOME`/
2198
2941
  // `$CODEX_HOME` expansion, so no spelling is a door.
2199
- const CODEX_FILE = String.raw `(?:config\.toml|hooks\.json)`;
2942
+ // @implements A-SPEC-792.39 — and the user's global git config and attributes (`~/.gitconfig`,
2943
+ // `$XDG_CONFIG_HOME/git/config`, `…/git/attributes`), which name programs every git child runs.
2944
+ const CODEX_FILE = String.raw `(?:config\.toml|hooks\.json|\.gitconfig|git[\\/](?:config|attributes))`;
2200
2945
  const userCfgCands = [...cfgCandidates];
2201
2946
  const CODEX_REDIRECT = new RegExp(`(?:>{1,2}|\\btee\\b(?:\\s+-a)?\\s)\\s*${pathAlt(CODEX_FILE)}`, 'g');
2202
2947
  for (const seg of segments) {
@@ -2204,13 +2949,13 @@ function evaluateHook(input, specsDir, opts) {
2204
2949
  collectPaths(seg, WRITE_VERB, CODEX_FILE, userCfgCands);
2205
2950
  collectPaths(seg, /\bsed\b/, CODEX_FILE, userCfgCands, /\s-i\b/);
2206
2951
  }
2207
- const USER_CFG_RE = /(?:config\.toml|hooks\.json|settings[\w.-]*\.json)$/;
2952
+ const USER_CFG_RE = /(?:config\.toml|hooks\.json|settings[\w.-]*\.json|\.gitconfig|git[\\/](?:config|attributes))$/;
2208
2953
  userCfgCands.push(...interpreterWrites.filter((p) => USER_CFG_RE.test(p)).flatMap(expandInterp));
2209
2954
  const userCfgList = distinct(userCfgCands);
2210
2955
  if (userCfgList === null)
2211
2956
  return TOO_MANY_CANDIDATES;
2212
2957
  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)))
2958
+ .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
2959
  .find((k) => k !== null);
2215
2960
  // One config-write approval (env or a granted queue request for this exact command) lifts both
2216
2961
  // rules below; the refusal files that request, as the Write/Edit config gate does.
@@ -2220,7 +2965,7 @@ function evaluateHook(input, specsDir, opts) {
2220
2965
  pendingApprovals.push(r);
2221
2966
  return null;
2222
2967
  }
2223
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${why} — an out-of-band approval that includes config-write is required (A-SPEC-728)`
2968
+ 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
2969
  + hintOrRoute({ kind: 'config-write', target: command, why }) }; // A-SPEC-792.5
2225
2970
  };
2226
2971
  let configWriteLifted = false;
@@ -2241,7 +2986,7 @@ function evaluateHook(input, specsDir, opts) {
2241
2986
  if (act && act.includes(write_target_1.PROJECT_CAPS_LABEL)) {
2242
2987
  const onDisk = (0, project_caps_1.readProjectCaps)(opts.projectRoot);
2243
2988
  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)` };
2989
+ 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
2990
  }
2246
2991
  if (!(0, project_caps_1.capsAtWidest)(onDisk)) {
2247
2992
  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 +3160,7 @@ function evaluateHook(input, specsDir, opts) {
2415
3160
  // @implements A-SPEC-774.10 — a legacy policy outside a run keeps the 0.35.25 freedom for WRITE_OTHER.
2416
3161
  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
3162
  if (issue)
2418
- return { permissionDecision: 'deny', permissionDecisionReason: issue };
3163
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: issue };
2419
3164
  }
2420
3165
  }
2421
3166
  // @implements A-SPEC-774.23 — a scoped run's shell writes stay inside its plan, as its file tool writes do.
@@ -2424,7 +3169,7 @@ function evaluateHook(input, specsDir, opts) {
2424
3169
  .filter((c) => judgeCand(c, [opts.projectRoot]) === 'in').map((c) => path.resolve(opts.projectRoot, judgedPath(c)));
2425
3170
  const outside = (0, run_plan_scope_1.planScopeRefusal)({ projectRoot: opts.projectRoot, specsDir, env: process.env, cwd: input.cwd, sessionId: input.session_id }, inProject);
2426
3171
  if (outside)
2427
- return { permissionDecision: 'deny', permissionDecisionReason: outside };
3172
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: outside };
2428
3173
  }
2429
3174
  // @implements A-SPEC-747.4 — a write whose destination or command word is computed at run time (xargs input, find's
2430
3175
  // `{}`, a variable, an IFS join) never reached the literal-destination rule above: 19 such writes to code files
@@ -2446,7 +3191,7 @@ function evaluateHook(input, specsDir, opts) {
2446
3191
  computedWrite = 'computed command';
2447
3192
  }
2448
3193
  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)` };
3194
+ 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
3195
  }
2451
3196
  const codeList = distinct([...candidates, ...interpreterWrites.flatMap(expandInterp)].filter(governedCode));
2452
3197
  // Rule 43: only a governed project judges this list — an ungoverned one was refused for nothing it would check.
@@ -2459,7 +3204,7 @@ function evaluateHook(input, specsDir, opts) {
2459
3204
  // has never depended on governance); code candidates stay dormant on a spec-less repo.
2460
3205
  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
3206
  if (cfgVerdicts.includes('unknown')) {
2462
- return { permissionDecision: 'deny', permissionDecisionReason: UNRESOLVED_BASE_DENY };
3207
+ return { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: UNRESOLVED_BASE_DENY };
2463
3208
  }
2464
3209
  if (codeVerdicts.includes('in') || codeVerdicts.includes('unknown')) {
2465
3210
  // @implements A-SPEC-550.1 — governance is "specs EXIST", not "a spec is approved". The old
@@ -2470,15 +3215,16 @@ function evaluateHook(input, specsDir, opts) {
2470
3215
  const governed = readSpecsSync(specsDir).length > 0;
2471
3216
  if (governed) {
2472
3217
  return codeVerdicts.includes('in')
2473
- ? { permissionDecision: 'deny', permissionDecisionReason: SHELL_CODE_WRITE_REASON }
2474
- : { permissionDecision: 'deny', permissionDecisionReason: UNRESOLVED_BASE_DENY };
3218
+ ? { permissionDecision: 'deny', refusal: 'shell.code-write', permissionDecisionReason: SHELL_CODE_WRITE_REASON }
3219
+ : { permissionDecision: 'deny', refusal: 'target.unresolvable', permissionDecisionReason: UNRESOLVED_BASE_DENY };
2475
3220
  }
2476
3221
  }
2477
3222
  }
2478
3223
  // @implements A-SPEC-790.8 — a carried approval was spent by the first reading; only the others are spent here.
2479
3224
  const spendable = pendingApprovals.flatMap((p) => (p.source === 'carried' ? [] : [p]));
2480
3225
  if (spendable.length > 0) {
2481
- const deny = (why) => ({ permissionDecision: 'deny',
3226
+ // A-SPEC-245.24 (item 1) — a single-use approval that cannot be spent once needs a new one from the person
3227
+ const deny = (why) => ({ permissionDecision: 'deny', refusal: 'approval.required',
2482
3228
  permissionDecisionReason: `[Holmes-Kit] ${why}` });
2483
3229
  // @implements A-SPEC-477.1 — a later invalid approval must not spend an earlier valid one.
2484
3230
  // Validate the complete set, then check all replays and append under ONE existing ledger hold.
@@ -2489,41 +3235,58 @@ function evaluateHook(input, specsDir, opts) {
2489
3235
  const ledgerFile = (0, ledger_store_2.writerChainFile)(path.join(opts.projectRoot, '.ax', 'ledger'));
2490
3236
  const unique = new Map(spendable.filter(({ approval }) => !!approval.nonce)
2491
3237
  .map(({ approval }) => [approval.nonce, approval]));
2492
- const check = () => {
3238
+ // A read: a conflict or a replay denies here with its reason; the spend itself is the settlement's, below
3239
+ try {
2493
3240
  const conflict = (0, ledger_store_2.ledgerConflictReason)(path.dirname(ledgerFile));
2494
3241
  if (conflict)
2495
- return conflict;
3242
+ return deny(conflict);
2496
3243
  const consumed = (0, ledger_store_2.nonceConsumedIn)(ledgerFile);
2497
3244
  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);
3245
+ return deny('single-use approval already consumed (replay)');
2517
3246
  }
2518
3247
  catch (err) {
2519
- return deny(`could not obtain exclusive ledger access to spend the single-use approval (${err instanceof Error ? err.message : String(err)})`);
3248
+ return deny(`could not read the ledger to judge the single-use approval (${err instanceof Error ? err.message : String(err)})`);
2520
3249
  }
3250
+ // @implements A-SPEC-245.9 (1b-2) — every single-use approval of this act, a grant's or the environment's, is
3251
+ // spent when the decision is final, on the hook's main thread, through spendApprovals (GrantSettlement.settle)
3252
+ if (opts.settlement === undefined && unique.size > 0)
3253
+ return deny('no settlement holds this single-use approval — it cannot be spent once, so it is denied');
2521
3254
  for (const { source, approval } of spendable) {
2522
- if (source === 'grant' && approval.nonce)
2523
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, approval.nonce);
3255
+ if (!approval.nonce)
3256
+ continue;
3257
+ if (source === 'grant')
3258
+ opts.settlement?.hold(opts.projectRoot, approval.nonce, approval); // A-SPEC-245.2, A-SPEC-245.4
3259
+ else
3260
+ opts.settlement?.holdEnv(opts.projectRoot, approval.nonce, approval, `consumed single-use approval for: ${(0, provenance_chain_1.redactTarget)('command', command)}`.slice(0, 200));
2524
3261
  }
2525
3262
  opts.onApprovalsSpent?.(spendable.map(({ approval }) => approval));
2526
3263
  }
3264
+ // @implements A-SPEC-792.32 — the one place a staging approval is recorded: every Bash gate has passed, the act is
3265
+ // allowed. The autonomous record is the verdict's proven pairs; the person path's names only its add segments.
3266
+ if (autonomousStaging !== null) {
3267
+ const a = autonomousStaging;
3268
+ const sha = (t) => crypto.createHash('sha256').update(t).digest('hex');
3269
+ try {
3270
+ new ledger_store_1.FileLedgerStore(path.join(opts.projectRoot, '.ax', 'ledger')).append({
3271
+ ts: nowTs, actor: `full-autonomy:${a.scope}`, kind: 'autonomous-shell-approved',
3272
+ summary: `governance staging approved by machine conditions (${a.paths.length} path(s))`,
3273
+ inputs: [`command:${sha(command)}`, `paths:${sha(a.paths.join('\n'))}`, `count:${a.paths.length}`, ...Object.entries(a.conditions).map(([k, x]) => `${k}:${x}`)],
3274
+ rationale: 'A-SPEC-792.28: grammar, provenance, integrity and reversibility each held',
3275
+ });
3276
+ }
3277
+ catch { /* the act is approved by its conditions; the audit row is best effort like the other gate records */ }
3278
+ (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) });
3279
+ try {
3280
+ require('../governance/spec-seam').recordProvenGrant(opts.projectRoot, specsDir, a.proven);
3281
+ }
3282
+ catch { /* unrecorded: the seam then reports the staged change, which fails closed at Stop */ }
3283
+ }
3284
+ if (personStaging) {
3285
+ try {
3286
+ require('../governance/spec-seam').recordGrantedStaging(opts.projectRoot, specsDir, command, shellBase);
3287
+ }
3288
+ catch { /* unrecorded: the seam then reports the staged change, which fails closed at Stop */ }
3289
+ }
2527
3290
  // @implements A-SPEC-774.13 — an allowed interactive launch inherits this session's authority variables; a hook
2528
3291
  // cannot change a command's environment, so it names them (never their values) and gives the operator's re-run.
2529
3292
  if (agentCliLaunch(command) && !(0, run_mode_1.runMode)(process.env, opts.projectRoot, input.cwd, input.session_id).run) {
@@ -2544,15 +3307,17 @@ function evaluateHook(input, specsDir, opts) {
2544
3307
  const foreign = input.tool_input.foreign_paths ?? (0, write_target_2.foreignMcpPaths)(input.tool_name, input.tool_input);
2545
3308
  if (foreign && (foreign.paths.length > 0 || foreign.unresolvable.length > 0)) {
2546
3309
  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)` };
3310
+ 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
3311
  }
2549
3312
  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)` };
3313
+ 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
3314
  }
2552
3315
  for (const fp of foreign.paths) {
2553
3316
  const v = evaluateHook({ tool_name: 'Write', tool_input: { file_path: fp, content: '' }, ...(input.cwd === undefined ? {} : { cwd: input.cwd }) }, specsDir, opts);
2554
3317
  if (v.permissionDecision === 'deny') {
2555
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} → ${fp.slice(0, 120)}: ${v.permissionDecisionReason ?? ''}` };
3318
+ // A-SPEC-245.23 (item 3) — the nested verdict's code, from its own site or its own text, before the path is prefixed
3319
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${input.tool_name} → ${fp.slice(0, 120)}: ${v.permissionDecisionReason ?? ''}`,
3320
+ refusal: (0, refusal_codes_1.refusalFor)(v.permissionDecisionReason ?? '', v.refusal).code };
2556
3321
  }
2557
3322
  }
2558
3323
  }
@@ -2576,6 +3341,7 @@ function evaluateHook(input, specsDir, opts) {
2576
3341
  // has to recognise.
2577
3342
  return {
2578
3343
  permissionDecision: 'deny',
3344
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2579
3345
  permissionDecisionReason: '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)',
2580
3346
  };
2581
3347
  }
@@ -2590,6 +3356,7 @@ function evaluateHook(input, specsDir, opts) {
2590
3356
  if (writesCode && !p) {
2591
3357
  return {
2592
3358
  permissionDecision: 'deny',
3359
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2593
3360
  permissionDecisionReason: '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)'
2594
3361
  + ' — there is no way to check whether an unnamed file overwrites an approved spec, so it is not allowed.',
2595
3362
  };
@@ -2615,7 +3382,7 @@ function evaluateHook(input, specsDir, opts) {
2615
3382
  // is not bounded by a count at all; it ends at the filesystem root, which always terminates.
2616
3383
  // `canonicalPath` (realpathSync.native), not the JS realpath: the root arrives canonicalised by
2617
3384
  // 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\…`)
3385
+ // the built hook — an in-project target spelled through `%TEMP%`'s alias (`C:\Users\FIRSTL~1\…`)
2619
3386
  // resolved to a string the long-name root did not contain, and took the "outside → allow" exit
2620
3387
  // below. Both sides must go through the one canonicaliser, or an alias is a free pass.
2621
3388
  // @implements A-SPEC-728 (rule 37) — the nearest ancestor that resolves is found by halving (whether an ancestor
@@ -2669,6 +3436,7 @@ function evaluateHook(input, specsDir, opts) {
2669
3436
  // nothing to govern"; an undecidable target is refused, not allowed.
2670
3437
  return {
2671
3438
  permissionDecision: 'deny',
3439
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2672
3440
  permissionDecisionReason: '[Holmes-Kit] a network path (UNC) cannot be resolved to a local filesystem identity,'
2673
3441
  + ' so it cannot be judged inside or outside the project — an untellable target is not allowed.'
2674
3442
  + ' Put the project on a local drive, or use a drive-letter-mapped path.',
@@ -2722,11 +3490,11 @@ function evaluateHook(input, specsDir, opts) {
2722
3490
  return { permissionDecision: 'allow' };
2723
3491
  const userResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2724
3492
  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`
3493
+ 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
3494
  + hintOrRoute({ kind: 'config-write', target: norm, why: `writing ${userKind}` }) }; // A-SPEC-792.5
2727
3495
  }
2728
3496
  if (userResolved.source === 'grant' && userResolved.approval.nonce)
2729
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, userResolved.approval.nonce);
3497
+ opts.settlement?.hold(opts.projectRoot, userResolved.approval.nonce, userResolved.approval); // A-SPEC-245.2
2730
3498
  return { permissionDecision: 'allow' };
2731
3499
  }
2732
3500
  norm = canonical;
@@ -2739,6 +3507,7 @@ function evaluateHook(input, specsDir, opts) {
2739
3507
  if (norm.includes('\u0000')) {
2740
3508
  return {
2741
3509
  permissionDecision: 'deny',
3510
+ refusal: 'target.unresolvable', // A-SPEC-245.24
2742
3511
  permissionDecisionReason: '[Holmes-Kit] the edit target path contains a NUL byte, so which file it is cannot be judged'
2743
3512
  + ' — a target whose name cannot be pinned down is not allowed.',
2744
3513
  };
@@ -2767,13 +3536,15 @@ function evaluateHook(input, specsDir, opts) {
2767
3536
  if (rolesResolved === undefined) {
2768
3537
  return {
2769
3538
  permissionDecision: 'deny',
3539
+ refusal: routeCode('approval.required'), // A-SPEC-245.24
2770
3540
  permissionDecisionReason: '[Holmes-Kit] the role policy (.ax/roles/) defines the very authority this gate enforces —'
2771
3541
  + ' an agent cannot change it itself. An out-of-band approval that includes config-write is required.'
2772
3542
  + hintOrRoute({ kind: 'config-write', target: norm, why: 'writing the role policy (.ax/roles/)' }), // A-SPEC-792.5
2773
3543
  };
2774
3544
  }
3545
+ // A-SPEC-245.2: held, not spent — the protected-directory branch below resolves this same grant again
2775
3546
  if (rolesResolved.source === 'grant' && rolesResolved.approval.nonce)
2776
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, rolesResolved.approval.nonce);
3547
+ opts.settlement?.hold(opts.projectRoot, rolesResolved.approval.nonce, rolesResolved.approval);
2777
3548
  }
2778
3549
  // @implements A-SPEC-191 §22 — ask by identity. A spelling regex was defeated by a single in-project link.
2779
3550
  // @implements A-SPEC-728 — a project that itself sits in a harness home still protects those files.
@@ -2789,11 +3560,11 @@ function evaluateHook(input, specsDir, opts) {
2789
3560
  // @implements A-SPEC-193 §8 — name what was blocked. Baking a list into the sentence makes the
2790
3561
  // wording false as harnesses grow (REQ-155: a diagnosis that points at the wrong file has negative value).
2791
3562
  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`
3563
+ 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
3564
  + hintOrRoute({ kind: 'config-write', target: norm, why: `writing ${kindName}` }) }; // A-SPEC-792.5
2794
3565
  }
2795
3566
  if (cfgResolved.source === 'grant' && cfgResolved.approval.nonce)
2796
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, cfgResolved.approval.nonce);
3567
+ opts.settlement?.hold(opts.projectRoot, cfgResolved.approval.nonce, cfgResolved.approval); // A-SPEC-245.2
2797
3568
  }
2798
3569
  // @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
3570
  // act (owner decision 2026-10-19), lowering stays free, and in a run no write changes one.
@@ -2801,16 +3572,16 @@ function evaluateHook(input, specsDir, opts) {
2801
3572
  const capsAct = projectCapsWriteAct(opts.projectRoot, input);
2802
3573
  if (capsAct !== null) {
2803
3574
  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)` };
3575
+ 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
3576
  }
2806
3577
  if (capsAct !== 'lowered') {
2807
3578
  const capsResolved = (0, approval_grants_1.resolveApproval)(opts.projectRoot, weApproval, { kind: 'config-write', target: norm }, nowTs);
2808
3579
  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)`
3580
+ 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
3581
  + hintOrRoute({ kind: 'config-write', target: norm, why: `raising a project cap (${capsAct})` }) }; // A-SPEC-792.5
2811
3582
  }
2812
3583
  if (capsResolved.source === 'grant' && capsResolved.approval.nonce)
2813
- (0, approval_grants_1.consumeGrantFile)(opts.projectRoot, capsResolved.approval.nonce);
3584
+ opts.settlement?.hold(opts.projectRoot, capsResolved.approval.nonce, capsResolved.approval); // A-SPEC-245.2
2814
3585
  }
2815
3586
  }
2816
3587
  }
@@ -2836,7 +3607,7 @@ function evaluateHook(input, specsDir, opts) {
2836
3607
  // legacy reading uses the same value.
2837
3608
  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
3609
  if (specRoleIssue)
2839
- return { permissionDecision: 'deny', permissionDecisionReason: specRoleIssue };
3610
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: specRoleIssue };
2840
3611
  }
2841
3612
  // F1: a spec cannot SELF-APPROVE. `status: approved` is what unlocks every downstream gate
2842
3613
  // (phaseCheck trusts the on-disk status). If the incoming write promotes a spec to approved and it
@@ -2854,7 +3625,7 @@ function evaluateHook(input, specsDir, opts) {
2854
3625
  const specWriteCovered = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'spec-write', target: norm }, nowTs);
2855
3626
  if (incomingSetsApproved(input.tool_input) && !specWriteCovered) {
2856
3627
  if (!onDiskApproved) {
2857
- return { permissionDecision: 'deny', permissionDecisionReason: registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
3628
+ return { permissionDecision: 'deny', refusal: 'spec.protected', permissionDecisionReason: registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
2858
3629
  }
2859
3630
  }
2860
3631
  // @implements A-SPEC-728 (rule 39) — and judged on the RESULT too: an Edit of `draft` into `approved` carries no
@@ -2876,7 +3647,7 @@ function evaluateHook(input, specsDir, opts) {
2876
3647
  catch { /* not a spec the store would read as approved */ }
2877
3648
  }
2878
3649
  if (approvedAfter || edited === TOO_LARGE) {
2879
- return { permissionDecision: 'deny', permissionDecisionReason: edited === TOO_LARGE
3650
+ return { permissionDecision: 'deny', refusal: edited === TOO_LARGE ? 'gate.unjudgeable' : 'spec.protected', permissionDecisionReason: edited === TOO_LARGE
2880
3651
  ? `[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
3652
  : registry_1.MESSAGES.SEAL_SELF_APPROVAL_RESTRICTED(path.basename(p, '.md'), 'A-SPEC-133') };
2882
3653
  }
@@ -2890,9 +3661,113 @@ function evaluateHook(input, specsDir, opts) {
2890
3661
  if (onDiskApproved && !specWriteCovered) {
2891
3662
  return {
2892
3663
  permissionDecision: 'deny',
3664
+ refusal: 'spec.protected', // A-SPEC-245.24
2893
3665
  permissionDecisionReason: registry_1.MESSAGES.SEAL_APPROVED_SPEC_MUTATION(path.basename(p, '.md'), undefined, 'A-SPEC-132'),
2894
3666
  };
2895
3667
  }
3668
+ // @implements A-SPEC-222.10 — H-B: a retired spec keeps the seal it was approved with, and its successor and anchor
3669
+ // moves are judged on it, so its sealed content and seal fields are as protected as an approved spec's (the rule
3670
+ // above ran only for `approved`, and an Edit rewrote an outdated body together with a recomputed approved_digest)
3671
+ if (!specWriteCovered) {
3672
+ let disk = null;
3673
+ try {
3674
+ disk = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null;
3675
+ }
3676
+ catch {
3677
+ disk = null;
3678
+ }
3679
+ let before = null;
3680
+ try {
3681
+ before = disk !== null ? (0, spec_parser_1.parseSpec)(disk) : null;
3682
+ }
3683
+ catch {
3684
+ before = null;
3685
+ }
3686
+ const edited = editedResult(disk, input.tool_input);
3687
+ let after = null;
3688
+ if (typeof edited === 'string') {
3689
+ try {
3690
+ after = (0, spec_parser_1.parseSpec)(edited);
3691
+ }
3692
+ catch {
3693
+ after = null;
3694
+ }
3695
+ }
3696
+ // @implements A-SPEC-222.12 — N2: and its status, both ways: an edit that leaves `outdated` (to rewrite the body
3697
+ // and come back) or enters it (a retirement is spec_retire's) is refused like a body change
3698
+ // A-SPEC-222.13 (low b): a new file written as outdated enters it too
3699
+ // A-SPEC-222.14 (low b): new means no file on disk; one whose YAML does not parse keeps its `status:` line
3700
+ // @implements A-SPEC-222.15 (item 2) — read from the first frontmatter block only, a trailing comment allowed (a
3701
+ // body line retired a spec by hand, and refused a legitimate repair)
3702
+ const { lenientFrontmatter } = require('../spec/succession-guard');
3703
+ const beforeOutdated = before !== null ? before.status === 'outdated'
3704
+ : disk !== null ? lenientFrontmatter(disk)?.status === 'outdated' : false;
3705
+ const statusMoves = after !== null && beforeOutdated !== (after.status === 'outdated');
3706
+ if (statusMoves) {
3707
+ return {
3708
+ permissionDecision: 'deny',
3709
+ refusal: 'spec.protected',
3710
+ 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)`,
3711
+ };
3712
+ }
3713
+ // @implements A-SPEC-222.15 (item 1) — a retired spec whose YAML does not parse has no `before` to compare: its
3714
+ // repair is allowed only back to a seal the trusted ledger records (222.14 let a rewrite with a recomputed digest
3715
+ // through here)
3716
+ if (before === null && disk !== null && beforeOutdated) {
3717
+ const id = path.basename(p, '.md');
3718
+ let toSeal = false;
3719
+ if (edited !== TOO_LARGE && after !== null) {
3720
+ const digest = (0, spec_digest_1.specDigest)(after);
3721
+ if (after.frontmatter.approved_digest === digest) {
3722
+ try {
3723
+ toSeal = require('../governance/recorded-pairs').recordedPairsPort(opts.projectRoot).approved(id, digest);
3724
+ }
3725
+ catch {
3726
+ toSeal = false;
3727
+ }
3728
+ }
3729
+ }
3730
+ if (!toSeal) {
3731
+ return {
3732
+ permissionDecision: 'deny',
3733
+ refusal: 'spec.protected',
3734
+ 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)`,
3735
+ };
3736
+ }
3737
+ }
3738
+ if (before !== null && before.status === 'outdated') {
3739
+ const sealOfSpec = (s) => JSON.stringify(spec_digest_1.SEAL_FIELDS.map((k) => s.frontmatter[k] ?? null));
3740
+ const changed = edited === TOO_LARGE || (after !== null && ((0, spec_digest_1.specDigest)(after) !== (0, spec_digest_1.specDigest)(before) || sealOfSpec(after) !== sealOfSpec(before)));
3741
+ if (changed) {
3742
+ return {
3743
+ permissionDecision: 'deny',
3744
+ refusal: 'spec.protected',
3745
+ 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)`,
3746
+ };
3747
+ }
3748
+ }
3749
+ }
3750
+ // @implements A-SPEC-222.8 — N2: who succeeds a spec is the tools' record, never a hand edit (the route is spec_retire)
3751
+ // @implements A-SPEC-222.9 — SD1 1: judged in succession-guard; the gate only asks
3752
+ {
3753
+ let disk = null;
3754
+ try {
3755
+ disk = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null;
3756
+ }
3757
+ catch {
3758
+ disk = null;
3759
+ }
3760
+ const edited = editedResult(disk, input.tool_input);
3761
+ const { successionFieldEditRefusal } = require('../spec/succession-guard');
3762
+ 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);
3763
+ if (why !== null) {
3764
+ return {
3765
+ permissionDecision: 'deny',
3766
+ refusal: 'spec.protected', // A-SPEC-245.24
3767
+ permissionDecisionReason: why,
3768
+ };
3769
+ }
3770
+ }
2896
3771
  // @implements A-SPEC-792.9 — a write that would leave the spec unreadable is refused with the parse error, whatever
2897
3772
  // 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
3773
  // and the run ended asking a person. A file already unreadable on disk is judged as before.
@@ -2918,6 +3793,7 @@ function evaluateHook(input, specsDir, opts) {
2918
3793
  if (broken !== null && (disk === null || parseError(disk) === null)) {
2919
3794
  return {
2920
3795
  permissionDecision: 'deny',
3796
+ refusal: 'spec.unreadable', // A-SPEC-245.24
2921
3797
  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
3798
  };
2923
3799
  }
@@ -2930,6 +3806,7 @@ function evaluateHook(input, specsDir, opts) {
2930
3806
  if (newReq !== null) {
2931
3807
  return {
2932
3808
  permissionDecision: 'deny',
3809
+ refusal: 'spec.not-approved', // A-SPEC-245.24 — the remedy is the tool, not a person
2933
3810
  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
3811
  };
2935
3812
  }
@@ -2942,6 +3819,7 @@ function evaluateHook(input, specsDir, opts) {
2942
3819
  if (assessment.level === 'hard-hitl' && !(0, risk_gate_1.isValidApproval)(opts.approval)) {
2943
3820
  return {
2944
3821
  permissionDecision: 'deny',
3822
+ refusal: 'spec.protected', // A-SPEC-245.24 — the reasons quote spec text; the code is the site's
2945
3823
  permissionDecisionReason: `[Holmes-Kit] high blast-radius spec edit: ${assessment.reasons.join('; ')} — requires out-of-band approval`,
2946
3824
  };
2947
3825
  }
@@ -2960,7 +3838,7 @@ function evaluateHook(input, specsDir, opts) {
2960
3838
  const otherPolicy = (0, role_policy_1.loadRolePolicy)(opts.projectRoot);
2961
3839
  // @implements A-SPEC-774.10 — read strictly only in a run or under a vocabulary-2 policy.
2962
3840
  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' };
3841
+ return otherIssue ? { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: otherIssue } : { permissionDecision: 'allow' };
2964
3842
  }
2965
3843
  // Read specs synchronously via a fresh walk (hook must be sync)
2966
3844
  const specs = readSpecsSync(specsDir);
@@ -3010,6 +3888,7 @@ function evaluateHook(input, specsDir, opts) {
3010
3888
  if (violations.length > 0) {
3011
3889
  return {
3012
3890
  permissionDecision: 'deny',
3891
+ refusal: 'architecture.violation', // A-SPEC-245.24
3013
3892
  permissionDecisionReason: '[Holmes-Kit] structural-constraint violation — a shape an approved C-SPEC forbids:\n'
3014
3893
  + violations.map((v) => ' - ' + v).join('\n')
3015
3894
  + '\n' + proposed_content_1.CSPEC_GATE_LIMITS,
@@ -3036,12 +3915,12 @@ function evaluateHook(input, specsDir, opts) {
3036
3915
  previous = fs.readFileSync(norm, 'utf8');
3037
3916
  }
3038
3917
  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` };
3918
+ 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
3919
  }
3041
3920
  }
3042
3921
  const edited = editedResult(previous ?? null, ti166);
3043
3922
  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` };
3923
+ 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
3924
  }
3046
3925
  // An edit that does not apply: the incoming fragments are judged (over-inclusion is the safe direction).
3047
3926
  const leaves = edited ?? [ti166.content, ti166.new_string, ...(Array.isArray(ti166.edits)
@@ -3156,6 +4035,7 @@ function evaluateHook(input, specsDir, opts) {
3156
4035
  ? ` (${(0, tspec_state_1.listOrCount)(hidden.flatMap(([, ids]) => ids), tspec_state_1.ID_BUDGET, 'items', Infinity)} require individual verification due to distinct reasons)` : '');
3157
4036
  return {
3158
4037
  permissionDecision: 'deny',
4038
+ refusal: 'spec.not-approved', // A-SPEC-245.24
3159
4039
  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
4040
  + ` — Claiming unapproved specifications in existing or new files is prohibited.${why}`,
3161
4041
  };
@@ -3192,7 +4072,7 @@ function evaluateHook(input, specsDir, opts) {
3192
4072
  if (ungovernedPolicy !== null) {
3193
4073
  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
4074
  if (issue)
3195
- return { permissionDecision: 'deny', permissionDecisionReason: issue };
4075
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: issue };
3196
4076
  }
3197
4077
  return { permissionDecision: 'allow' };
3198
4078
  }
@@ -3222,7 +4102,7 @@ function evaluateHook(input, specsDir, opts) {
3222
4102
  // second id passed). The shared parser is consumed through `stripStringLiterals`, the same
3223
4103
  // preprocessing the claim gate got in S-504.1, so a fixture string anchor no longer governs.
3224
4104
  // 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');
4105
+ const { anchorSpecIdsFor } = require('../rtm/anchor-ids');
3226
4106
  const uniq = (xs) => [...new Set(xs)];
3227
4107
  // @implements A-SPEC-529.2 — the preprocessing branches on FILE FORMAT. A-SPEC-529.1 stripped
3228
4108
  // string literals so a code fixture like `const s = "@implements A-SPEC-999"` could not become
@@ -3231,10 +4111,9 @@ function evaluateHook(input, specsDir, opts) {
3231
4111
  // 2026-09-03, a release package.json edit was refused with "A-SPEC(unspecified)". Code formats
3232
4112
  // (line-comment anchors) still strip; JSON/YAML/TOML/config and unknown extensions read raw
3233
4113
  // (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'))));
4114
+ // @implements A-SPEC-222.8 — the per-format reading lives in anchor-ids, shared with the census and the move judgment
4115
+ const diskGovIds = uniq(anchorSpecIdsFor(relPath, onDiskContent));
4116
+ const payloadGovIds = uniq(anchorSpecIdsFor(relPath, [input.tool_input.content ?? '', input.tool_input.new_string ?? ''].join('\n')));
3238
4117
  const governingIds = diskGovIds.length > 0 ? diskGovIds : payloadGovIds;
3239
4118
  // The single "primary" id kept for message templates and phaseCheck's targetAspecId default: the
3240
4119
  // first governing id, which is exactly what `m?.[1]` used to be for a single-anchor file.
@@ -3286,7 +4165,7 @@ function evaluateHook(input, specsDir, opts) {
3286
4165
  // @implements A-SPEC-133 — the override is authorized by a token covering the code write.
3287
4166
  const codeWriteCovered = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'code-write', target: relPath }, nowTs);
3288
4167
  if (staleTarget && !codeWriteCovered) {
3289
- return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] ${staleTarget} — re-approve with spec_approve, then proceed` };
4168
+ return { permissionDecision: 'deny', refusal: 'spec.not-approved', permissionDecisionReason: `[Holmes-Kit] ${staleTarget} — re-approve with spec_approve, then proceed` };
3290
4169
  }
3291
4170
  // @implements A-SPEC-152
3292
4171
  // Role gate — BEFORE the spec gate on purpose: if this identity may not perform the action at all,
@@ -3305,7 +4184,7 @@ function evaluateHook(input, specsDir, opts) {
3305
4184
  // role-override approval lifts a role refusal. Interactively a code-write approval still lifts it (0.35.25).
3306
4185
  const roleOverride = (0, risk_gate_1.approvalCovers)(weApproval, { kind: 'role-override', target: relPath }, nowTs);
3307
4186
  if (roleIssue && !roleOverride && (roleRun || !codeWriteCovered)) {
3308
- return { permissionDecision: 'deny', permissionDecisionReason: roleIssue };
4187
+ return { permissionDecision: 'deny', refusal: 'role.refused', permissionDecisionReason: roleIssue };
3309
4188
  }
3310
4189
  // @implements A-SPEC-134
3311
4190
  // Constitution-debt gate: after the Stop gate gave up its block cap on an unresolved constitution,
@@ -3340,6 +4219,7 @@ function evaluateHook(input, specsDir, opts) {
3340
4219
  }
3341
4220
  return {
3342
4221
  permissionDecision: 'deny',
4222
+ refusal: 'constitution.debt', // A-SPEC-245.24
3343
4223
  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
4224
  + (hint || ' — could not persist the approval request; ask the operator to check the project approval queue storage'),
3345
4225
  };
@@ -3349,7 +4229,49 @@ function evaluateHook(input, specsDir, opts) {
3349
4229
  // verdict, and its id flows into the refusal template (so the author sees the anchor that is
3350
4230
  // actually unsatisfied, not merely the first one on the file). An empty set keeps the prior
3351
4231
  // single call with an undefined target. Deterministic: governing-set order is document order.
3352
- const phaseTargets = governingIds.length > 0 ? governingIds : [undefined];
4232
+ // @implements A-SPEC-222.4 — the exit from a retired anchor (AU1-b, owner decision 2026-10-25): an Edit whose only
4233
+ // change moves an outdated X to its sealed superseded_by Y on @implements lines is judged under Y, not X; every other
4234
+ // gate still runs. Without it the file refused every edit, the anchor move included (run-exec.ts line 28).
4235
+ // @implements A-SPEC-222.6 — judged on the file: the edit applied to the disk text (absent, or not unique without
4236
+ // replace_all, is no result and no move), and Y must qualify as X's successor (sealed, lineage, coverage)
4237
+ const moveResult = (() => {
4238
+ if (input.tool_name !== 'Edit')
4239
+ return null;
4240
+ const o = input.tool_input.old_string;
4241
+ if (typeof o !== 'string' || o === '' || typeof input.tool_input.new_string !== 'string')
4242
+ return null;
4243
+ if (input.tool_input.replace_all !== true && onDiskContent.indexOf(o) !== onDiskContent.lastIndexOf(o))
4244
+ return null;
4245
+ const r = editedResult(onDiskContent, input.tool_input);
4246
+ return typeof r === 'string' ? r : null;
4247
+ })();
4248
+ // @implements A-SPEC-222.8 — N2: a successor counts only as the ledger recorded it (a hand-written one moves nothing)
4249
+ // @implements A-SPEC-222.9 — H1, H3, SD1 1/2: judged in succession-guard, on the trusted record the port reads
4250
+ const moveVerdict = require('../spec/succession-guard').movedAnchors({ before: onDiskContent, after: moveResult, governingIds, relPath }, { specs, resolveSpec: (id) => resolveSpec(id) ?? undefined,
4251
+ record: () => require('../governance/recorded-pairs').recordedPairsPort(projectRoot) });
4252
+ const movedAnchors = moveVerdict.moves;
4253
+ const movedTo = (id) => movedAnchors.find((m) => m.x === id)?.y ?? id;
4254
+ // @implements A-SPEC-222.4 — an allowed anchor move is on the record (no person decided it; the conditions did), on
4255
+ // every allow path after the phase gate
4256
+ const recordMovedAnchors = () => {
4257
+ for (const mv of movedAnchors) {
4258
+ try {
4259
+ // @implements A-SPEC-222.6 — F4: the successor digest and the result hash; autonomous (no person decided it),
4260
+ // directive none (none is needed: the conditions decide, with or without full autonomy). L2: once per result.
4261
+ const inputs = [relPath, mv.x, mv.y, `successor-digest:${mv.digest}`, `after-sha256:${mv.after}`, 'autonomous', 'directive:none'];
4262
+ const store = new ledger_store_1.FileLedgerStore(path.join(projectRoot, '.ax', 'ledger'));
4263
+ if (store.loadAll().some((e) => e.kind === 'anchor-moved' && JSON.stringify(e.inputs) === JSON.stringify(inputs)))
4264
+ continue;
4265
+ store.append({
4266
+ ts: nowTs, actor: 'holmes-kit', kind: 'anchor-moved', inputs,
4267
+ summary: `moved the anchor of ${relPath} from retired ${mv.x} to its sealed successor ${mv.y}`.slice(0, 200),
4268
+ rationale: 'autonomous anchor move: the edit changes only the @implements id, to the outdated spec\'s superseded_by (A-SPEC-222.4)',
4269
+ });
4270
+ }
4271
+ catch { /* the record is best effort; the gate already judged the edit */ }
4272
+ }
4273
+ };
4274
+ const phaseTargets = governingIds.length > 0 ? [...new Set(governingIds.map(movedTo))] : [undefined];
3353
4275
  let failedTarget;
3354
4276
  let res = (0, phase_1.phaseCheck)(action, { specs, targetAspecId: phaseTargets[0] });
3355
4277
  for (const tid of phaseTargets) {
@@ -3372,8 +4294,10 @@ function evaluateHook(input, specsDir, opts) {
3372
4294
  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
4295
  return {
3374
4296
  permissionDecision: 'deny',
4297
+ refusal: 'spec.not-approved', // A-SPEC-245.24 — the phase gate's refusal: no approved chain for the target
3375
4298
  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}` : ''),
4299
+ + (lost ? `\n${governance_history_1.GOVERNANCE_LOST_HINT}` : '')
4300
+ + (moveVerdict.note ? `\n[Holmes-Kit] ${moveVerdict.note}` : ''), // A-SPEC-222.9 — the ignored record is named
3377
4301
  };
3378
4302
  }
3379
4303
  // @implements A-SPEC-508.1
@@ -3436,7 +4360,7 @@ function evaluateHook(input, specsDir, opts) {
3436
4360
  if (afterSites.length > beforeSites.length && others.length > 0) {
3437
4361
  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
4362
  if (writeClassify.strict)
3439
- return { permissionDecision: 'deny', permissionDecisionReason: why };
4363
+ return { permissionDecision: 'deny', refusal: 'scope.outside', permissionDecisionReason: why };
3440
4364
  scopeWarnings = [scopeWarnings, why].filter(Boolean).join('\n');
3441
4365
  }
3442
4366
  }
@@ -3448,6 +4372,7 @@ function evaluateHook(input, specsDir, opts) {
3448
4372
  .map((f) => `${relPath} is anchored to ${f.id} but falls outside its 'Files to Touch' scope (${f.reason})`).join('; ');
3449
4373
  return {
3450
4374
  permissionDecision: 'deny',
4375
+ refusal: 'scope.outside', // A-SPEC-245.24
3451
4376
  permissionDecisionReason: `[Holmes-Kit] ${failed} — extend that section first (spec edit is allowed), add it as a test under the anchored spec, or supply out-of-band approval`
3452
4377
  + (scopeWarnings ? `\n${scopeWarnings}` : ''),
3453
4378
  };
@@ -3483,6 +4408,8 @@ function evaluateHook(input, specsDir, opts) {
3483
4408
  currentHead: evidenceHead,
3484
4409
  });
3485
4410
  if (evidenceDecision) {
4411
+ if (evidenceDecision.permissionDecision === 'allow')
4412
+ recordMovedAnchors();
3486
4413
  // @implements A-SPEC-508.1 — an allow-with-reason from the evidence gate must not swallow
3487
4414
  // the anchor-deletion warning: both ride the same reason field, newline-joined.
3488
4415
  if (scopeWarnings && evidenceDecision.permissionDecision === 'allow') {
@@ -3491,6 +4418,7 @@ function evaluateHook(input, specsDir, opts) {
3491
4418
  return evidenceDecision;
3492
4419
  }
3493
4420
  }
4421
+ recordMovedAnchors();
3494
4422
  // @implements A-SPEC-508.1 — anchor-deletion warnings ride the allow (allow-with-reason, the
3495
4423
  // same channel A-SPEC-278 uses): the write proceeds, but the RTM loss is on the record.
3496
4424
  if (scopeWarnings)
@@ -3608,9 +4536,12 @@ if (require.main === module) {
3608
4536
  const wired = wiredSpecsDir(process.argv, process.env);
3609
4537
  return path.isAbsolute(wired) ? wired : path.join(hookProjectRoot, wired);
3610
4538
  })();
4539
+ // @implements A-SPEC-245.4 — held through every pass below, settled once after the last one
4540
+ const settlement = new approval_grants_1.GrantSettlement();
3611
4541
  const judged = evaluateHook(input, specsDirWired, {
3612
4542
  projectRoot: hookProjectRoot,
3613
4543
  approval: readApprovalFromEnv(),
4544
+ settlement,
3614
4545
  // Round 17: rm targets resolve from the directory the shell runs in (inside the project).
3615
4546
  resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3616
4547
  resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
@@ -3631,9 +4562,9 @@ if (require.main === module) {
3631
4562
  tool: input.tool_name, toolInput: input.tool_input })
3632
4563
  : staged;
3633
4564
  // @implements A-SPEC-778 — in a run, refusals are logged and a repeated code stops the run; elsewhere unchanged.
3634
- const out = (hookRoot.anchored
4565
+ const out = settleVerdict((hookRoot.anchored
3635
4566
  ? (0, run_refusals_1.applyRunRefusalStop)(roled, { projectRoot: hookProjectRoot, env: process.env, cwd: input.cwd, sessionId: input.session_id, tool: input.tool_name })
3636
- : judged);
4567
+ : judged), settlement);
3637
4568
  io.out(JSON.stringify({ hookSpecificOutput: hookOutputFor(input.tool_name, out) }));
3638
4569
  // N3 provenance: record the audit-critical decision classes on the tamper-evident chain —
3639
4570
  // every DENY, and every ALLOW that was unlocked by an out-of-band approval. Fail-open: a
@@ -3662,12 +4593,15 @@ if (require.main === module) {
3662
4593
  ? evaluateHook(input, specsDirWired, {
3663
4594
  projectRoot: hookProjectRoot,
3664
4595
  approval: undefined,
4596
+ settlement: approval_grants_1.GrantSettlement.counterfactual(), // A-SPEC-245.4 — a reading, not a decision: spends nothing
3665
4597
  // A-SPEC-734 (round 17): the same base, project and spec directory as the decision it re-asks.
3666
4598
  resolveRmSignals: (command) => resolveRmSignals(command, (0, write_target_2.shellBaseFor)(hookProjectRoot, input.tool_input.workdir, input.cwd), hookProjectRoot, specsDirWired),
3667
4599
  resolveStagedStore: (command) => resolveStagedStore(command, hookProjectRoot, specsDirWired),
3668
4600
  })
3669
4601
  : undefined;
3670
- const unlocked = withoutApproval?.permissionDecision === 'deny';
4602
+ // A-SPEC-245.4 (f): a grant this decision spent unlocked the act too, and the line names that grant's actor
4603
+ const acting = out.permissionDecision === 'allow' ? auditApprovalFor(approval, withoutApproval?.permissionDecision === 'deny', settlement) : undefined;
4604
+ const unlocked = acting !== undefined;
3671
4605
  if (out.permissionDecision === 'deny' || unlocked) {
3672
4606
  const target = input.tool_input?.file_path
3673
4607
  ? (0, provenance_chain_1.redactTarget)('path', input.tool_input.file_path)
@@ -3675,7 +4609,7 @@ if (require.main === module) {
3675
4609
  // @implements A-SPEC-148 — writes go to THIS replica's chain; the legacy file is read-only now.
3676
4610
  new ledger_store_1.FileLedgerStore(path.join(hookProjectRoot, path.dirname(provenance_chain_1.PROVENANCE_FILE))).append({
3677
4611
  ts: new Date().toISOString(),
3678
- actor: unlocked && approval ? approval.actor : 'agent',
4612
+ actor: acting ? acting.actor : 'agent',
3679
4613
  kind: out.permissionDecision === 'deny' ? 'gate-deny' : 'approved-action',
3680
4614
  // REDACTED. Both fields used to carry the raw command; an audit of this repository's own
3681
4615
  // ledger found 15 of 29 records leaking absolute home paths and 6 matching secret-ish
@@ -3689,14 +4623,14 @@ if (require.main === module) {
3689
4623
  // @implements A-SPEC-133 — a master-key use becomes an audit line: the approval's
3690
4624
  // narrowing (or its absence) travels with the record (r7-191: promised, never shipped).
3691
4625
  inputs: [input.tool_name, target,
3692
- ...(unlocked ? [(0, provenance_chain_1.approvalMarkers)(approval)] : []), // one item, last position — the marker cannot split and self-contradict
4626
+ ...(acting ? [(0, provenance_chain_1.approvalMarkers)(acting)] : []), // one item, last position — the marker cannot split and self-contradict
3693
4627
  ].filter(Boolean),
3694
4628
  // round-9: a deny inherited the actor/rationale/authorization of an ambient approval that
3695
4629
  // did NOT cover it, so the audit line credited an authorizer who authorized nothing.
3696
- rationale: unlocked && approval ? approval.rationale : '',
4630
+ rationale: acting ? acting.rationale : '',
3697
4631
  // NEVER the raw token (review #1): a fingerprint identifies the credential without
3698
4632
  // storing the replayable secret; invalid approval attempts record nothing of it.
3699
- authorization: unlocked && approval ? (0, provenance_chain_1.authorizationRef)(approval.actor, approval.token) : '',
4633
+ authorization: acting ? (0, provenance_chain_1.authorizationRef)(acting.actor, acting.token) : '',
3700
4634
  });
3701
4635
  }
3702
4636
  }
@@ -3782,7 +4716,18 @@ if (require.main === module) {
3782
4716
  process.exit(r.code);
3783
4717
  };
3784
4718
  if (!isMainThread) {
3785
- parentPort.postMessage(collect(workerData.buf));
4719
+ // @implements A-SPEC-245.9 (1b-2) — a final allow's spends cross to the main thread; the worker waits for its answer
4720
+ const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
4721
+ mainThreadSettler = (p) => {
4722
+ const flag = new Int32Array(new SharedArrayBuffer(4));
4723
+ const { port1, port2 } = new MessageChannel();
4724
+ parentPort.postMessage({ type: 'settle', pending: p, flag, port: port2 }, [port2]);
4725
+ Atomics.wait(flag, 0, 0, HOOK_DEADLINE_MS());
4726
+ const answer = receiveMessageOnPort(port1)?.message;
4727
+ port1.close();
4728
+ return answer ?? { outcome: 'refused', committed: [], refusal: 'the main thread did not answer the spend in time — nothing was done' };
4729
+ };
4730
+ parentPort.postMessage({ type: 'result', result: collect(workerData.buf) });
3786
4731
  }
3787
4732
  else {
3788
4733
  let buf = '';
@@ -3810,7 +4755,29 @@ if (require.main === module) {
3810
4755
  void worker.terminate();
3811
4756
  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
4757
  }, deadline);
3813
- worker.once('message', (r) => done(r));
4758
+ worker.on('message', (m) => {
4759
+ if (m.type === 'result') {
4760
+ done(m.result);
4761
+ return;
4762
+ }
4763
+ // A-SPEC-245.9 (1b-2): the spend runs here, on the main thread; a deadline that ends the worker after it
4764
+ // answers the gate-error deny, and an approval then stays spent with nothing done (fail-closed)
4765
+ let answer;
4766
+ if (settled)
4767
+ answer = { outcome: 'refused', committed: [], refusal: 'the gate already answered — nothing was spent' };
4768
+ else {
4769
+ try {
4770
+ answer = settleOnMainThread(m.pending);
4771
+ }
4772
+ catch (e) {
4773
+ answer = { outcome: 'refused', committed: [], refusal: `the spend failed: ${e instanceof Error ? e.message : String(e)}` };
4774
+ }
4775
+ }
4776
+ m.port.postMessage(answer);
4777
+ m.port.close();
4778
+ Atomics.store(m.flag, 0, 1);
4779
+ Atomics.notify(m.flag, 0);
4780
+ });
3814
4781
  worker.once('error', (e) => done(gateErrorOutcome(`the gate stopped without a verdict: ${e.message}`)));
3815
4782
  worker.once('exit', (code) => { if (!settled)
3816
4783
  done(gateErrorOutcome(`the gate stopped without a verdict (exit ${code})`)); });