@holmes-lab/holmes-kit 0.39.0 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/CHANGELOG.md +578 -6
  2. package/README.md +120 -41
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/admission/core/admission-policy.d.ts +37 -0
  5. package/dist/holmes/admission/core/admission-policy.js +147 -0
  6. package/dist/holmes/admission/core/bounded-reader.d.ts +56 -0
  7. package/dist/holmes/admission/core/bounded-reader.js +135 -0
  8. package/dist/holmes/admission/core/change-classifier.d.ts +34 -0
  9. package/dist/holmes/admission/core/change-classifier.js +278 -0
  10. package/dist/holmes/admission/core/config-loader.d.ts +30 -0
  11. package/dist/holmes/admission/core/config-loader.js +145 -0
  12. package/dist/holmes/admission/core/event-judgement.d.ts +37 -0
  13. package/dist/holmes/admission/core/event-judgement.js +251 -0
  14. package/dist/holmes/admission/core/path-rules.d.ts +35 -0
  15. package/dist/holmes/admission/core/path-rules.js +88 -0
  16. package/dist/holmes/admission/core/pin.d.ts +7 -0
  17. package/dist/holmes/admission/core/pin.js +29 -0
  18. package/dist/holmes/admission/core/ports.d.ts +48 -0
  19. package/dist/holmes/admission/core/ports.js +11 -0
  20. package/dist/holmes/admission/core/range-resolver.d.ts +32 -0
  21. package/dist/holmes/admission/core/range-resolver.js +51 -0
  22. package/dist/holmes/admission/core/self-containment.d.ts +1 -0
  23. package/dist/holmes/admission/core/self-containment.js +125 -0
  24. package/dist/holmes/admission/core/signature-source.d.ts +9 -0
  25. package/dist/holmes/admission/core/signature-source.js +4 -0
  26. package/dist/holmes/admission/core/transition-planner.d.ts +15 -0
  27. package/dist/holmes/admission/core/transition-planner.js +14 -0
  28. package/dist/holmes/admission/core/verdict.d.ts +38 -0
  29. package/dist/holmes/admission/core/verdict.js +17 -0
  30. package/dist/holmes/admission/core/wiring.d.ts +44 -0
  31. package/dist/holmes/admission/core/wiring.js +618 -0
  32. package/dist/holmes/admission/forge/git-object-port.d.ts +4 -0
  33. package/dist/holmes/admission/forge/git-object-port.js +132 -0
  34. package/dist/holmes/assoc/assoc-arm.d.ts +1 -1
  35. package/dist/holmes/assoc/assoc-arm.js +1 -1
  36. package/dist/holmes/cli/agents.d.ts +8 -0
  37. package/dist/holmes/cli/agents.js +9 -5
  38. package/dist/holmes/cli/approve-cli.d.ts +2 -0
  39. package/dist/holmes/cli/approve-cli.js +392 -0
  40. package/dist/holmes/cli/approve-ref.d.ts +13 -7
  41. package/dist/holmes/cli/approve-ref.js +30 -10
  42. package/dist/holmes/cli/approve-status.d.ts +26 -2
  43. package/dist/holmes/cli/approve-status.js +98 -18
  44. package/dist/holmes/cli/approve-watch.d.ts +5 -0
  45. package/dist/holmes/cli/approve-watch.js +10 -5
  46. package/dist/holmes/cli/approve.d.ts +49 -13
  47. package/dist/holmes/cli/approve.js +249 -67
  48. package/dist/holmes/cli/attest.js +2 -1
  49. package/dist/holmes/cli/autonomy.d.ts +4 -1
  50. package/dist/holmes/cli/autonomy.js +17 -10
  51. package/dist/holmes/cli/codex-oracle.d.ts +11 -0
  52. package/dist/holmes/cli/codex-oracle.js +5 -1
  53. package/dist/holmes/cli/codex-toml.d.ts +10 -0
  54. package/dist/holmes/cli/codex-toml.js +36 -2
  55. package/dist/holmes/cli/doctor-boundary.d.ts +76 -0
  56. package/dist/holmes/cli/doctor-boundary.js +308 -0
  57. package/dist/holmes/cli/doctor-locks.d.ts +15 -0
  58. package/dist/holmes/cli/doctor-locks.js +119 -0
  59. package/dist/holmes/cli/doctor.d.ts +2 -0
  60. package/dist/holmes/cli/doctor.js +34 -5
  61. package/dist/holmes/cli/flags.d.ts +23 -0
  62. package/dist/holmes/cli/flags.js +89 -0
  63. package/dist/holmes/cli/index.d.ts +5 -1
  64. package/dist/holmes/cli/index.js +226 -442
  65. package/dist/holmes/cli/init.js +33 -0
  66. package/dist/holmes/cli/interactive-prompt.d.ts +39 -2
  67. package/dist/holmes/cli/interactive-prompt.js +98 -16
  68. package/dist/holmes/cli/lock-recover.d.ts +5 -0
  69. package/dist/holmes/cli/lock-recover.js +126 -0
  70. package/dist/holmes/cli/mcp-processes.js +1 -1
  71. package/dist/holmes/cli/release-docs.js +1 -1
  72. package/dist/holmes/cli/run-exec.d.ts +141 -0
  73. package/dist/holmes/cli/run-exec.js +1435 -0
  74. package/dist/holmes/cli/run-provision.d.ts +3 -1
  75. package/dist/holmes/cli/run-provision.js +255 -44
  76. package/dist/holmes/cli/run-wiring.d.ts +69 -0
  77. package/dist/holmes/cli/run-wiring.js +270 -0
  78. package/dist/holmes/cli/run.d.ts +21 -0
  79. package/dist/holmes/cli/run.js +341 -92
  80. package/dist/holmes/cli/runtime-binding-approval.js +32 -19
  81. package/dist/holmes/cli/screen-safe.d.ts +3 -92
  82. package/dist/holmes/cli/screen-safe.js +18 -756
  83. package/dist/holmes/config/config.d.ts +19 -0
  84. package/dist/holmes/config/config.js +18 -3
  85. package/dist/holmes/cpg/foundation/language-matrix.js +2 -2
  86. package/dist/holmes/cpg/import-resolver.js +1 -1
  87. package/dist/holmes/governance/approval-decisions.d.ts +47 -0
  88. package/dist/holmes/governance/approval-decisions.js +29 -0
  89. package/dist/holmes/governance/approval-grants.d.ts +220 -1
  90. package/dist/holmes/governance/approval-grants.js +612 -33
  91. package/dist/holmes/governance/approval-queue.d.ts +26 -0
  92. package/dist/holmes/governance/approval-queue.js +109 -11
  93. package/dist/holmes/governance/approval-spend.d.ts +95 -0
  94. package/dist/holmes/governance/approval-spend.js +191 -0
  95. package/dist/holmes/governance/autonomous-shell.d.ts +61 -0
  96. package/dist/holmes/governance/autonomous-shell.js +332 -0
  97. package/dist/holmes/governance/autonomy.d.ts +12 -0
  98. package/dist/holmes/governance/autonomy.js +51 -15
  99. package/dist/holmes/governance/constitution.d.ts +5 -0
  100. package/dist/holmes/governance/constitution.js +32 -12
  101. package/dist/holmes/governance/full-autonomy.d.ts +10 -0
  102. package/dist/holmes/governance/full-autonomy.js +103 -7
  103. package/dist/holmes/governance/harness-catalog.d.ts +103 -0
  104. package/dist/holmes/governance/harness-catalog.js +348 -0
  105. package/dist/holmes/governance/human-channel.d.ts +38 -0
  106. package/dist/holmes/governance/human-channel.js +49 -0
  107. package/dist/holmes/governance/install-manifest.d.ts +22 -0
  108. package/dist/holmes/governance/install-manifest.js +160 -0
  109. package/dist/holmes/governance/ledger-rechain.js +2 -0
  110. package/dist/holmes/governance/ledger-store.conformance.d.ts +7 -1
  111. package/dist/holmes/governance/ledger-store.conformance.js +66 -0
  112. package/dist/holmes/governance/ledger-store.d.ts +88 -11
  113. package/dist/holmes/governance/ledger-store.js +186 -8
  114. package/dist/holmes/governance/provenance-chain.d.ts +16 -4
  115. package/dist/holmes/governance/provenance-chain.js +19 -4
  116. package/dist/holmes/governance/provenance-ledger.d.ts +6 -3
  117. package/dist/holmes/governance/provenance-ledger.js +53 -18
  118. package/dist/holmes/governance/push-gate-runner.d.ts +2 -0
  119. package/dist/holmes/governance/push-gate-runner.js +50 -9
  120. package/dist/holmes/governance/push-gate.d.ts +13 -2
  121. package/dist/holmes/governance/push-gate.js +106 -14
  122. package/dist/holmes/governance/recorded-pairs.d.ts +96 -0
  123. package/dist/holmes/governance/recorded-pairs.js +522 -0
  124. package/dist/holmes/governance/replica-id.d.ts +1 -1
  125. package/dist/holmes/governance/replica-id.js +1 -1
  126. package/dist/holmes/governance/spec-seam.d.ts +59 -0
  127. package/dist/holmes/governance/spec-seam.js +587 -0
  128. package/dist/holmes/governance/spend-kinds.d.ts +16 -0
  129. package/dist/holmes/governance/spend-kinds.js +18 -0
  130. package/dist/holmes/guardrail/advisory-line.d.ts +102 -0
  131. package/dist/holmes/guardrail/advisory-line.js +718 -0
  132. package/dist/holmes/guardrail/decision-ledger.d.ts +2 -1
  133. package/dist/holmes/guardrail/decision-ledger.js +2 -1
  134. package/dist/holmes/guardrail/impact-gate.d.ts +7 -0
  135. package/dist/holmes/guardrail/impact-gate.js +33 -6
  136. package/dist/holmes/guardrail/line-continuation.d.ts +8 -0
  137. package/dist/holmes/guardrail/line-continuation.js +39 -0
  138. package/dist/holmes/guardrail/operator-person.d.ts +28 -4
  139. package/dist/holmes/guardrail/operator-person.js +57 -11
  140. package/dist/holmes/guardrail/refusal-codes.d.ts +8 -3
  141. package/dist/holmes/guardrail/refusal-codes.js +64 -10
  142. package/dist/holmes/guardrail/risk-classifier.d.ts +15 -9
  143. package/dist/holmes/guardrail/risk-classifier.js +228 -16
  144. package/dist/holmes/guardrail/risk-gate.d.ts +2 -8
  145. package/dist/holmes/guardrail/risk-gate.js +7 -34
  146. package/dist/holmes/guardrail/risk-types.d.ts +10 -0
  147. package/dist/holmes/guardrail/run-plan-scope.js +3 -1
  148. package/dist/holmes/guardrail/run-refusals.js +24 -8
  149. package/dist/holmes/guardrail/run-stages.d.ts +5 -0
  150. package/dist/holmes/guardrail/run-stages.js +25 -5
  151. package/dist/holmes/guardrail/scope-judgment.js +1 -1
  152. package/dist/holmes/guardrail/shell-words.js +24 -3
  153. package/dist/holmes/guardrail/unresolved-write.d.ts +40 -0
  154. package/dist/holmes/guardrail/unresolved-write.js +556 -0
  155. package/dist/holmes/guardrail/write-target.d.ts +3 -0
  156. package/dist/holmes/guardrail/write-target.js +26 -5
  157. package/dist/holmes/hooks/pre-tool-use.d.ts +116 -1
  158. package/dist/holmes/hooks/pre-tool-use.js +1176 -170
  159. package/dist/holmes/hooks/rtm-refresh-child.d.ts +1 -1
  160. package/dist/holmes/hooks/rtm-refresh-child.js +1 -1
  161. package/dist/holmes/hooks/session-start.js +17 -1
  162. package/dist/holmes/hooks/stop.d.ts +23 -0
  163. package/dist/holmes/hooks/stop.js +86 -33
  164. package/dist/holmes/mcp/approval-adapters.js +3 -1
  165. package/dist/holmes/mcp/approval-commit.js +3 -2
  166. package/dist/holmes/mcp/approval-policy.d.ts +2 -1
  167. package/dist/holmes/mcp/approval-policy.js +3 -1
  168. package/dist/holmes/mcp/handlers/adoption.d.ts +1 -1
  169. package/dist/holmes/mcp/handlers/approval-ask.d.ts +3 -0
  170. package/dist/holmes/mcp/handlers/approval-ask.js +18 -7
  171. package/dist/holmes/mcp/handlers/entity-integration.d.ts +3 -3
  172. package/dist/holmes/mcp/handlers/entity-integration.js +29 -11
  173. package/dist/holmes/mcp/handlers/entity-renumber.d.ts +4 -4
  174. package/dist/holmes/mcp/handlers/entity-renumber.js +29 -11
  175. package/dist/holmes/mcp/handlers/entity-store.d.ts +2 -2
  176. package/dist/holmes/mcp/handlers/entity-store.js +133 -59
  177. package/dist/holmes/mcp/handlers/maintenance-analysis.d.ts +13 -0
  178. package/dist/holmes/mcp/handlers/maintenance-analysis.js +59 -2
  179. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +9 -5
  180. package/dist/holmes/mcp/handlers/operator-inspection.js +79 -16
  181. package/dist/holmes/mcp/handlers/phase-queries.d.ts +1 -1
  182. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +4 -4
  183. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -2
  184. package/dist/holmes/mcp/handlers/review-evidence.js +35 -11
  185. package/dist/holmes/mcp/handlers/review-queries.d.ts +5 -0
  186. package/dist/holmes/mcp/handlers/review-queries.js +8 -1
  187. package/dist/holmes/mcp/handlers/review-verdict.d.ts +3 -0
  188. package/dist/holmes/mcp/handlers/review-verdict.js +10 -3
  189. package/dist/holmes/mcp/handlers/risk-assessment.d.ts +7 -2
  190. package/dist/holmes/mcp/handlers/risk-assessment.js +34 -12
  191. package/dist/holmes/mcp/handlers/runtime-binding-tool.d.ts +2 -2
  192. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +6 -1
  193. package/dist/holmes/mcp/handlers/slice-orchestration.js +14 -1
  194. package/dist/holmes/mcp/handlers/spec-approval.d.ts +15 -3
  195. package/dist/holmes/mcp/handlers/spec-approval.js +32 -5
  196. package/dist/holmes/mcp/handlers/spec-authoring.d.ts +2 -2
  197. package/dist/holmes/mcp/handlers/spec-authoring.js +19 -2
  198. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +11 -38
  199. package/dist/holmes/mcp/handlers/spec-lifecycle.js +441 -94
  200. package/dist/holmes/mcp/handlers/spec-queries.d.ts +2 -2
  201. package/dist/holmes/mcp/handlers/taint-screening.d.ts +1 -1
  202. package/dist/holmes/mcp/handlers/taint-screening.js +2 -2
  203. package/dist/holmes/mcp/handlers/test-execution.d.ts +471 -4
  204. package/dist/holmes/mcp/handlers/test-execution.js +199 -21
  205. package/dist/holmes/mcp/handlers/workspace-queries.d.ts +2 -2
  206. package/dist/holmes/mcp/handlers.d.ts +557 -82
  207. package/dist/holmes/mcp/handlers.js +74 -23
  208. package/dist/holmes/mcp/harness-attestation.d.ts +78 -5
  209. package/dist/holmes/mcp/harness-attestation.js +325 -53
  210. package/dist/holmes/mcp/maintenance-analyze.d.ts +6 -1
  211. package/dist/holmes/mcp/maintenance-analyze.js +13 -11
  212. package/dist/holmes/mcp/maintenance-evidence.d.ts +9 -0
  213. package/dist/holmes/mcp/maintenance-evidence.js +35 -3
  214. package/dist/holmes/mcp/requirement-triage-evidence.js +22 -13
  215. package/dist/holmes/mcp/server-staleness.js +1 -1
  216. package/dist/holmes/mcp/server.js +9 -8
  217. package/dist/holmes/mcp/spec-id-guard.js +1 -1
  218. package/dist/holmes/mcp/tool-schemas.d.ts +13 -0
  219. package/dist/holmes/mcp/tool-schemas.js +42 -9
  220. package/dist/holmes/project/act-root.d.ts +19 -0
  221. package/dist/holmes/project/act-root.js +100 -0
  222. package/dist/holmes/project/baseline.d.ts +15 -2
  223. package/dist/holmes/project/baseline.js +14 -8
  224. package/dist/holmes/project/bounded-group.d.ts +47 -0
  225. package/dist/holmes/project/bounded-group.js +140 -0
  226. package/dist/holmes/project/bounded-io.d.ts +51 -2
  227. package/dist/holmes/project/bounded-io.js +140 -6
  228. package/dist/holmes/project/change-source.d.ts +4 -0
  229. package/dist/holmes/project/change-source.js +14 -6
  230. package/dist/holmes/project/instance-id.d.ts +10 -0
  231. package/dist/holmes/project/instance-id.js +233 -0
  232. package/dist/holmes/project/machine-identity.d.ts +25 -0
  233. package/dist/holmes/project/machine-identity.js +133 -0
  234. package/dist/holmes/project/owned-lock.d.ts +84 -0
  235. package/dist/holmes/project/owned-lock.js +263 -0
  236. package/dist/holmes/project/plain-lock-fs.d.ts +2 -0
  237. package/dist/holmes/project/plain-lock-fs.js +126 -0
  238. package/dist/holmes/project/request-lock.d.ts +85 -0
  239. package/dist/holmes/project/request-lock.js +459 -0
  240. package/dist/holmes/project/root.d.ts +12 -4
  241. package/dist/holmes/project/root.js +29 -8
  242. package/dist/holmes/project/run-records.d.ts +19 -0
  243. package/dist/holmes/project/run-records.js +94 -12
  244. package/dist/holmes/project/screen-text.d.ts +94 -0
  245. package/dist/holmes/project/screen-text.js +763 -0
  246. package/dist/holmes/project/spend-lock.d.ts +82 -0
  247. package/dist/holmes/project/spend-lock.js +413 -0
  248. package/dist/holmes/refresh/freshness-coordinator.d.ts +1 -1
  249. package/dist/holmes/refresh/freshness-coordinator.js +1 -1
  250. package/dist/holmes/review/condition-hunk-replay.js +4 -2
  251. package/dist/holmes/review/confidence-calibration.d.ts +1 -1
  252. package/dist/holmes/review/confidence-calibration.js +1 -1
  253. package/dist/holmes/review/content-verify.js +1 -1
  254. package/dist/holmes/review/evidence-mode.d.ts +21 -0
  255. package/dist/holmes/review/evidence-mode.js +33 -0
  256. package/dist/holmes/review/head-worktree.d.ts +55 -0
  257. package/dist/holmes/review/head-worktree.js +329 -0
  258. package/dist/holmes/review/hop-ablation.d.ts +4 -4
  259. package/dist/holmes/review/hop-ablation.js +5 -5
  260. package/dist/holmes/review/mrp.js +13 -3
  261. package/dist/holmes/review/point-in-time-replay.js +12 -3
  262. package/dist/holmes/review/rank-diagnosis.d.ts +2 -2
  263. package/dist/holmes/review/rank-diagnosis.js +1 -1
  264. package/dist/holmes/review/replay-corpus.d.ts +10 -4
  265. package/dist/holmes/review/replay-corpus.js +25 -9
  266. package/dist/holmes/review/requirement-triage.js +2 -2
  267. package/dist/holmes/review/run-provenance.d.ts +45 -0
  268. package/dist/holmes/review/run-provenance.js +314 -0
  269. package/dist/holmes/review/semantic-arm.d.ts +3 -3
  270. package/dist/holmes/review/semantic-arm.js +3 -3
  271. package/dist/holmes/review/test-evidence.d.ts +174 -0
  272. package/dist/holmes/review/test-evidence.js +330 -2
  273. package/dist/holmes/review/test-outcomes.js +3 -1
  274. package/dist/holmes/review/test-reports.d.ts +94 -0
  275. package/dist/holmes/review/test-reports.js +382 -0
  276. package/dist/holmes/review/test-runner.d.ts +180 -58
  277. package/dist/holmes/review/test-runner.js +560 -324
  278. package/dist/holmes/review/test-selection-breadth.js +2 -2
  279. package/dist/holmes/review/test-units.d.ts +159 -0
  280. package/dist/holmes/review/test-units.js +814 -0
  281. package/dist/holmes/review/verdicts.d.ts +105 -8
  282. package/dist/holmes/review/verdicts.js +640 -36
  283. package/dist/holmes/rtm/anchor-census.d.ts +9 -0
  284. package/dist/holmes/rtm/anchor-census.js +151 -0
  285. package/dist/holmes/rtm/anchor-ids.d.ts +25 -1
  286. package/dist/holmes/rtm/anchor-ids.js +45 -2
  287. package/dist/holmes/rtm/comment-ranges.d.ts +2 -0
  288. package/dist/holmes/rtm/comment-ranges.js +104 -0
  289. package/dist/holmes/rtm/counted-tests.d.ts +1 -0
  290. package/dist/holmes/rtm/counted-tests.js +63 -0
  291. package/dist/holmes/rtm/impact-advisory.d.ts +1 -1
  292. package/dist/holmes/rtm/known-defects.js +1 -1
  293. package/dist/holmes/rtm/localize.js +1 -1
  294. package/dist/holmes/rtm/taint-benchmark.d.ts +1 -1
  295. package/dist/holmes/rtm/taint-vocabulary.d.ts +1 -1
  296. package/dist/holmes/rtm/test-scope.d.ts +31 -0
  297. package/dist/holmes/rtm/test-scope.js +166 -5
  298. package/dist/holmes/rtm/trace-gaps.js +1 -1
  299. package/dist/holmes/runtime/dispatch.d.ts +10 -0
  300. package/dist/holmes/runtime/dispatch.js +12 -1
  301. package/dist/holmes/semantic/cloud-usage.d.ts +1 -1
  302. package/dist/holmes/semantic/cloud-usage.js +1 -1
  303. package/dist/holmes/semantic/unreadable-paths.d.ts +1 -1
  304. package/dist/holmes/semantic/unreadable-paths.js +1 -1
  305. package/dist/holmes/spec/approval-blockers.js +1 -1
  306. package/dist/holmes/spec/entity-store.d.ts +6 -1
  307. package/dist/holmes/spec/entity-store.js +16 -2
  308. package/dist/holmes/spec/entity-transaction.d.ts +7 -2
  309. package/dist/holmes/spec/entity-transaction.js +87 -170
  310. package/dist/holmes/spec/spec-store.d.ts +12 -6
  311. package/dist/holmes/spec/spec-store.js +4 -2
  312. package/dist/holmes/spec/spec-types.js +1 -1
  313. package/dist/holmes/spec/succession-guard.d.ts +56 -0
  314. package/dist/holmes/spec/succession-guard.js +187 -0
  315. package/dist/holmes/spec/succession.d.ts +70 -0
  316. package/dist/holmes/spec/succession.js +171 -0
  317. package/dist/holmes/spec/transition-policy.d.ts +2 -2
  318. package/docs/install-guide.md +9 -3
  319. package/docs/language-support.md +78 -0
  320. package/package.json +4 -3
  321. package/playbooks/author-slice/PLAYBOOK.md +1 -1
  322. package/playbooks/promote-slice/PLAYBOOK.md +5 -1
  323. package/playbooks/publish/PLAYBOOK.md +47 -34
  324. package/dist/holmes/review/manual-baseline.d.ts +0 -209
  325. package/dist/holmes/review/manual-baseline.js +0 -2847
@@ -33,18 +33,40 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.GRANT_NO_EXPIRY = exports.GRANTS_RELDIR = void 0;
36
+ exports.GrantSpendRefusal = exports.GrantSettlement = exports.CLAIM_PREFIX = exports.GRANT_NO_EXPIRY = exports.GRANTS_RELDIR = void 0;
37
37
  exports.readGrants = readGrants;
38
+ exports.ledgerSpendFacts = ledgerSpendFacts;
39
+ exports.readGrantFiles = readGrantFiles;
38
40
  exports.refusedGrantReasons = refusedGrantReasons;
39
41
  exports.pickCoveringGrant = pickCoveringGrant;
40
42
  exports.resolveApproval = resolveApproval;
41
43
  exports.consumeGrantFile = consumeGrantFile;
42
- // @implements A-SPEC-245, A-SPEC-532.5
44
+ exports.claimGrant = claimGrant;
45
+ exports.claimedCopiesOf = claimedCopiesOf;
46
+ exports.grantFileNames = grantFileNames;
47
+ exports.grantFileIdOf = grantFileIdOf;
48
+ exports.namesRequest = namesRequest;
49
+ exports.requestGrantState = requestGrantState;
50
+ exports.grantedStateOf = grantedStateOf;
51
+ exports.grantFileFacts = grantFileFacts;
52
+ exports.withGrant = withGrant;
53
+ exports.withGrantSync = withGrantSync;
54
+ exports.spendGrants = spendGrants;
55
+ exports.spendGrantApprovals = spendGrantApprovals;
56
+ exports.grantSpend = grantSpend;
57
+ exports.staleClaims = staleClaims;
58
+ // @implements A-SPEC-245, A-SPEC-532.5, A-SPEC-245.9, A-SPEC-245.15, A-SPEC-222.10, A-SPEC-794.4, A-SPEC-794.34, A-SPEC-794.35, A-SPEC-794.37
59
+ const crypto = __importStar(require("node:crypto"));
43
60
  const fs = __importStar(require("node:fs"));
44
61
  const path = __importStar(require("node:path"));
45
62
  const risk_gate_1 = require("../guardrail/risk-gate");
46
63
  const workspace_identity_1 = require("../project/workspace-identity");
47
64
  const approval_queue_1 = require("./approval-queue");
65
+ const approval_spend_1 = require("./approval-spend");
66
+ const provenance_chain_1 = require("./provenance-chain");
67
+ const ledger_store_1 = require("./ledger-store");
68
+ const spend_kinds_1 = require("./spend-kinds");
69
+ const provenance_ledger_1 = require("./provenance-ledger");
48
70
  /**
49
71
  * The grant file channel — approval delivery with no file editing and no reconnect.
50
72
  *
@@ -80,14 +102,91 @@ const isNarrow = (a) => Array.isArray(a.scope) && a.scope.length > 0 &&
80
102
  * be diagnosable, and a silent skip makes an inert grant indistinguishable from no grant.
81
103
  */
82
104
  function readGrants(root) {
83
- const dir = path.join(root, exports.GRANTS_RELDIR);
105
+ const files = readGrantFiles(root);
106
+ // @implements A-SPEC-245.9 (H-5), A-SPEC-245.15 (item 2) — usable only when its nonce is neither spent nor revoked on any
107
+ // chain and the chains verify: a spent grant file that came back (a release after a failed publish) covers nothing,
108
+ // so it cannot shadow a new grant of the same act; read through the N11 cache
109
+ if (files.grants.length === 0)
110
+ return files;
111
+ const facts = ledgerSpendFacts(root);
112
+ if (!facts.ok)
113
+ return { grants: [], ignored: files.ignored, unusable: facts.reason ?? 'the ledger does not verify' };
114
+ const grants = [];
115
+ const refused = [];
116
+ for (const g of files.grants) {
117
+ const nonce = String(g.nonce);
118
+ if (facts.spent(nonce))
119
+ refused.push({ nonce, reason: 'spent' });
120
+ else if (facts.revoked(nonce))
121
+ refused.push({ nonce, reason: 'revoked' });
122
+ else
123
+ grants.push(g);
124
+ }
125
+ refused.sort((a, b) => (a.nonce < b.nonce ? -1 : a.nonce > b.nonce ? 1 : 0));
126
+ return { grants, ignored: files.ignored, ...(refused.length > 0 ? { refused } : {}) };
127
+ }
128
+ // @implements A-SPEC-794.4 — a versioned file per schema, so an older holmes's v1 cache and this one never rewrite each other
129
+ const FACTS_FILE = ['.ax', 'state', 'ledger-facts.v2.json'];
130
+ const FACTS_SCHEMA = 'holmes-ledger-facts/2';
131
+ const FACT_FINGERPRINT = /^nonce:[0-9a-f]{12}$/;
132
+ function ledgerSpendFacts(root, ns = 'grant') {
133
+ const dir = path.join(root, '.ax', 'ledger');
134
+ const canon = (i) => (FACT_FINGERPRINT.test(i) ? i : (0, provenance_chain_1.nonceFingerprint)(i));
135
+ const answer = (f) => {
136
+ const spent = new Set(f.spent), revoked = new Set(f.revoked);
137
+ return { ok: f.ok, ...(f.reason !== undefined ? { reason: f.reason } : {}),
138
+ // A-SPEC-245.16 (6a): a nonce is looked up by its fingerprint too — a grant nonce that itself has the fingerprint
139
+ // shape (`nonce:…`) is spent under nonceFingerprint(nonce), which canon would not reach
140
+ spent: (n) => spent.has((0, provenance_chain_1.nonceFingerprint)(n)) || spent.has(canon(n)),
141
+ revoked: (n) => revoked.has((0, provenance_chain_1.nonceFingerprint)(n)) || revoked.has(canon(n)) };
142
+ };
84
143
  let names;
85
144
  try {
86
- names = fs.readdirSync(dir).filter((n) => n.endsWith('.json')).sort();
145
+ names = fs.readdirSync(dir).filter((n) => (0, provenance_ledger_1.isLedgerFilename)(n)).sort();
87
146
  }
88
147
  catch {
89
- return { grants: [], ignored: 0 };
148
+ return answer({ ok: true, spent: [], revoked: [] });
149
+ }
150
+ const key = JSON.stringify(names.map((n) => { try {
151
+ const s = fs.statSync(path.join(dir, n));
152
+ return [n, s.size, s.mtimeMs];
90
153
  }
154
+ catch {
155
+ return [n, -1, -1];
156
+ } }));
157
+ const cacheFile = path.join(root, ...FACTS_FILE);
158
+ try {
159
+ const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
160
+ const sets = cached.namespaces?.[ns];
161
+ if (cached.schema === FACTS_SCHEMA && cached.key === key && typeof cached.ok === 'boolean' && Array.isArray(sets?.spent) && Array.isArray(sets?.revoked)) {
162
+ return answer({ ok: cached.ok, ...(typeof cached.reason === 'string' ? { reason: cached.reason } : {}), spent: sets.spent, revoked: sets.revoked });
163
+ }
164
+ }
165
+ catch { /* no cache, or unreadable: computed below */ }
166
+ const store = new ledger_store_1.FileLedgerStore(dir);
167
+ const broken = store.verifyAll().broken.filter((b) => b.kind === 'chain' || b.kind === undefined);
168
+ const events = store.loadAll();
169
+ const of = (kind) => [...new Set(events.filter((e) => e.kind === kind).flatMap((e) => (e.inputs ?? []).filter((i) => !i.startsWith('event:')).map(canon)))];
170
+ const namespaces = Object.fromEntries(Object.keys(spend_kinds_1.SPEND_NAMESPACES)
171
+ .map((n) => [n, { spent: of((0, spend_kinds_1.spendKind)(n)), revoked: of((0, spend_kinds_1.revokeKind)(n)) }]));
172
+ const facts = { ok: broken.length === 0,
173
+ ...(broken.length > 0 ? { reason: `the ledger's chains do not verify (${broken.map((b) => `${b.replicaId ?? 'legacy'}: ${b.detail ?? 'broken'}`).join('; ')}) — no grant is usable until it is repaired` } : {}) };
174
+ try {
175
+ fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
176
+ const tmp = `${cacheFile}.${process.pid}.${Date.now()}.tmp`;
177
+ fs.writeFileSync(tmp, JSON.stringify({ schema: FACTS_SCHEMA, key, ...facts, namespaces }));
178
+ fs.renameSync(tmp, cacheFile);
179
+ }
180
+ catch { /* a cache that cannot be written is recomputed next time */ }
181
+ return answer({ ...facts, ...namespaces[ns] });
182
+ }
183
+ /**
184
+ * The grant files as they are on disk, judged only by their shape — for a path that removes the files of grants it has
185
+ * already spent (the usable judgement would hide them from it).
186
+ */
187
+ function readGrantFiles(root) {
188
+ const dir = path.join(root, exports.GRANTS_RELDIR);
189
+ const names = grantFileNames(root);
91
190
  const grants = [];
92
191
  let ignored = 0;
93
192
  for (const name of names) {
@@ -167,13 +266,18 @@ function pickCoveringGrant(grants, action, now) {
167
266
  * Env-first IS the backward compatibility: an adopter whose flows run on the env token sees not one
168
267
  * changed verdict, message, or consumed file from this slice.
169
268
  */
170
- function resolveApproval(root, envApproval, action, now) {
269
+ function resolveApproval(root, envApproval, action, now, spentByThisAct = []) {
171
270
  if ((0, risk_gate_1.approvalCovers)(envApproval, action, now))
172
271
  return { approval: envApproval, source: 'env' };
173
272
  // @implements A-SPEC-649 — a bound grant is a candidate only in its own workspace and for its own subject.
174
273
  const workspace = currentWorkspaceId(root);
175
274
  const grant = pickCoveringGrant(readGrants(root).grants.filter((g) => bindingRefusal(g, action, workspace) === null), action, now);
176
- return grant ? { approval: grant, source: 'grant' } : undefined;
275
+ if (grant)
276
+ return { approval: grant, source: 'grant' };
277
+ // @implements A-SPEC-245.15 (item 2) — a grant this very act already spent still authorizes the rest of that act (a
278
+ // transaction re-asks its authority at each step); spent grants of any other act stay unusable (H-5)
279
+ const own = pickCoveringGrant(spentByThisAct.filter((g) => bindingRefusal(g, action, workspace) === null), action, now);
280
+ return own ? { approval: own, source: 'grant' } : undefined;
177
281
  }
178
282
  /**
179
283
  * Best-effort single-use: remove the grant file after the act it authorized succeeded.
@@ -184,42 +288,517 @@ function resolveApproval(root, envApproval, action, now) {
184
288
  * The nonce is flattened to a basename so a traversal-shaped nonce cannot reach outside the dir.
185
289
  */
186
290
  function consumeGrantFile(root, nonce) {
187
- // @implements A-SPEC-596 — address the grant the SAME way `readGrants` does: by the nonce INSIDE
188
- // the file, never by a path built from it. Building the path meant a grant whose filename differed
189
- // from its nonce was honoured (reading scans, and never compares the two) yet never spent, with
190
- // `force: true` swallowing the miss — a single-use grant that stayed spendable forever. Scanning
191
- // also makes traversal structurally impossible: no nonce becomes a path, so none can point out.
291
+ spendGrants(root, [nonce]);
292
+ }
293
+ /**
294
+ * @implements A-SPEC-245.2 — a grant's lifetime has one seam. A claim moves the grant's file aside by an exclusive rename
295
+ * (one claimant wins; `readGrants` never reads a claimed file, so a claimed grant covers nothing else), then the act
296
+ * either commits it (removed) or releases it (renamed back). "Spend after success" had been repeated at 18 sites, and
297
+ * an `.ax/roles` Write spent its grant at one branch and was denied by the next (measured).
298
+ */
299
+ exports.CLAIM_PREFIX = '.claimed.';
300
+ /**
301
+ * Claim every grant file holding `nonce`, or null when there is none to claim (another claimant won, or none exists).
302
+ * @implements A-SPEC-596 — by the nonce INSIDE the file, never by a path built from it: a grant whose filename differed
303
+ * from its nonce was honoured yet never spent, and no nonce becomes a path, so none can point out of the directory.
304
+ */
305
+ function claimGrant(root, nonce) {
192
306
  const dir = path.join(root, exports.GRANTS_RELDIR);
193
307
  const wanted = String(nonce);
194
- let removed = 0;
308
+ const moved = [];
309
+ let names;
195
310
  try {
196
- for (const name of fs.readdirSync(dir).filter((n) => n.endsWith('.json'))) {
197
- const file = path.join(dir, name);
311
+ names = fs.readdirSync(dir).filter((n) => n.endsWith('.json') && !n.startsWith(exports.CLAIM_PREFIX));
312
+ }
313
+ catch {
314
+ return null;
315
+ }
316
+ for (const name of names) {
317
+ const file = path.join(dir, name);
318
+ try {
319
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
320
+ if (String(parsed?.nonce) !== wanted)
321
+ continue; // someone else's grant is not ours to claim
322
+ // A-SPEC-245.4 (c): a random suffix, so two claims in one millisecond of one process cannot share a name
323
+ const to = path.join(dir, `${exports.CLAIM_PREFIX}${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString('hex')}.${name}`);
324
+ fs.renameSync(file, to); // exclusive: a second claimant's rename finds no file
325
+ moved.push({ from: file, to });
326
+ }
327
+ catch { /* corrupt, vanished or claimed meanwhile: not ours */ }
328
+ }
329
+ if (moved.length === 0)
330
+ return null;
331
+ let settled = false;
332
+ return {
333
+ nonce: wanted,
334
+ commit() {
335
+ if (settled)
336
+ return;
337
+ settled = true;
338
+ const failed = [];
339
+ for (const m of moved) {
340
+ try {
341
+ fs.rmSync(m.to);
342
+ }
343
+ catch {
344
+ failed.push(m.to);
345
+ }
346
+ }
347
+ // @implements A-SPEC-649 — the spend is a queue event too. Best-effort.
198
348
  try {
199
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
200
- if (String(parsed?.nonce) !== wanted)
201
- continue; // someone else's grant is not ours to spend
202
- fs.rmSync(file, { force: true });
203
- removed++;
349
+ (0, approval_queue_1.appendQueueEvent)(root, { event: 'consumed', id: wanted });
204
350
  }
205
- catch { /* corrupt or vanished: it was never honoured either, so it is not ours to spend */ }
206
- }
351
+ catch { /* fire-and-forget */ }
352
+ // L3: a removal that failed is an error, not a silence; the file stays claimed, so it covers nothing
353
+ if (failed.length > 0)
354
+ throw new Error(`the spent approval grant could not be removed: ${failed.join(', ')} — it is claimed and covers nothing; remove it by hand`);
355
+ },
356
+ release() {
357
+ if (settled)
358
+ return;
359
+ settled = true;
360
+ // A-SPEC-245.4 (M3): a link fails when the name is taken (a newer grant is never overwritten), and a claimed copy
361
+ // that revokeGrant removed is not there to link (a revoked grant never comes back); either way the copy goes
362
+ for (const m of moved) {
363
+ try {
364
+ fs.linkSync(m.to, m.from);
365
+ }
366
+ catch (e) {
367
+ const why = e.code === 'EEXIST' ? 'a newer grant holds its name' : 'it was revoked or removed meanwhile';
368
+ process.stderr.write(`[Holmes-Kit] a claimed approval grant was not returned (${why}): ${path.basename(m.from)}\n`);
369
+ }
370
+ try {
371
+ fs.rmSync(m.to, { force: true });
372
+ }
373
+ catch {
374
+ process.stderr.write(`[Holmes-Kit] a claimed approval grant copy could not be removed: ${m.to}\n`);
375
+ }
376
+ }
377
+ },
378
+ };
379
+ }
380
+ /** The prefix a claimed copy's name carries before the grant file's own name. */
381
+ const CLAIMED_NAME = /^\.claimed\.\d+\.\d+\.(?:[0-9a-f]{8}\.)?/;
382
+ /** @implements A-SPEC-245.4 (M3) — the claimed copies of the grant file `name` (`<id>.json`), for revocation. */
383
+ function claimedCopiesOf(root, name) {
384
+ const dir = path.join(root, exports.GRANTS_RELDIR);
385
+ try {
386
+ return fs.readdirSync(dir).filter((n) => n.startsWith(exports.CLAIM_PREFIX) && CLAIMED_NAME.test(n)
387
+ && n.replace(CLAIMED_NAME, '') === name).map((n) => path.join(dir, n));
207
388
  }
208
389
  catch {
209
- // No directory, or it cannot be read: there is nothing to spend, which is an ordinary state.
210
- return;
390
+ return [];
391
+ }
392
+ }
393
+ /**
394
+ * @implements A-SPEC-245.2, A-SPEC-794.35 — the grant files the store reads: every `*.json` in the grant directory that is
395
+ * not a claimed copy (a claimed grant is in an act's hands and covers nothing else). One set, so a grant that covers its
396
+ * act is also one the screens list and `--revoke` reaches.
397
+ */
398
+ function grantFileNames(root) {
399
+ try {
400
+ return fs.readdirSync(path.join(root, exports.GRANTS_RELDIR)).filter((n) => n.endsWith('.json') && !n.startsWith(exports.CLAIM_PREFIX)).sort();
401
+ }
402
+ catch {
403
+ return [];
404
+ }
405
+ }
406
+ /**
407
+ * @implements A-SPEC-794.34, A-SPEC-794.35 — the grant name a file in the grant directory carries: a name in
408
+ * `grantFileNames` without `.json`, or a claimed copy's own name without it; null for anything else.
409
+ */
410
+ function grantFileIdOf(fileName) {
411
+ const claimed = fileName.startsWith(exports.CLAIM_PREFIX);
412
+ const own = claimed ? fileName.replace(CLAIMED_NAME, '') : fileName;
413
+ if ((claimed && own === fileName) || !own.endsWith('.json') || own.startsWith(exports.CLAIM_PREFIX))
414
+ return null;
415
+ return own.slice(0, -'.json'.length);
416
+ }
417
+ /** A grant field that names request `id`: the id itself or a re-grant `id.r<n>`. */
418
+ function namesRequest(value, id) {
419
+ return typeof value === 'string' && (value === id || (value.startsWith(`${id}.r`) && /^\d+$/.test(value.slice(id.length + 2))));
420
+ }
421
+ const readGrantJson = (file) => {
422
+ try {
423
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
424
+ }
425
+ catch {
426
+ return null;
427
+ }
428
+ };
429
+ const namedScopes = (g) => (Array.isArray(g?.scope) ? g.scope : []).filter((s) => typeof s?.kind === 'string' && typeof s?.pattern === 'string').map((s) => ({ kind: s.kind, pattern: s.pattern, exact: s.exact === true }));
430
+ /** The file in the grant directory that holds `nonce`, or the nonce when none does. */
431
+ function fileHolding(root, nonce) {
432
+ const dir = path.join(root, exports.GRANTS_RELDIR);
433
+ return grantFileNames(root).find((n) => readGrantJson(path.join(dir, n))?.nonce === nonce) ?? String(nonce);
434
+ }
435
+ /**
436
+ * @implements A-SPEC-794.35, A-SPEC-794.37 — the one judgement of a granted request's grant: `covers` when `resolveApproval`
437
+ * would authorise its act now (naming the covering file), `claimed` when a live process holds its grant, else `none` (and
438
+ * `staleClaim` when a dead process left its claim, which `doctor` names). A request the fold does not name (a refusal-log
439
+ * one) is judged on every exact act its own grants name. Judged without a subject: `spec_approve` compares it on consumption.
440
+ */
441
+ function requestGrantState(root, id, act, now) {
442
+ try {
443
+ const owned = act ? [] : readGrants(root).grants.filter((g) => namesRequest(g.request, id) || namesRequest(g.nonce, id));
444
+ const acts = act ? [act] : owned.flatMap((g) => namedScopes(g).filter((s) => s.exact).map((s) => ({ kind: s.kind, target: s.pattern })));
445
+ for (const a of acts) {
446
+ const hit = resolveApproval(root, undefined, a, now);
447
+ if (hit?.source === 'grant')
448
+ return { state: 'covers', grant: fileHolding(root, hit.approval.nonce) };
449
+ }
450
+ }
451
+ catch { /* an unreadable store covers nothing */ }
452
+ const dir = path.join(root, exports.GRANTS_RELDIR);
453
+ let copies = [];
454
+ try {
455
+ copies = fs.readdirSync(dir).filter((n) => n.startsWith(exports.CLAIM_PREFIX)).filter((n) => {
456
+ if (grantFileIdOf(n) === id)
457
+ return true;
458
+ const g = readGrantJson(path.join(dir, n));
459
+ return namesRequest(g?.request, id) || namesRequest(g?.nonce, id);
460
+ });
461
+ }
462
+ catch { /* no grant directory */ }
463
+ if (copies.length === 0)
464
+ return { state: 'none' };
465
+ const stale = new Set(staleClaims(root).map((s) => path.basename(s.file)));
466
+ return copies.some((n) => !stale.has(n)) ? { state: 'claimed' } : { state: 'none', staleClaim: true };
467
+ }
468
+ /**
469
+ * @implements A-SPEC-794.37 — the one order of a granted request's state, for `approval_status` and `--status`. A row whose
470
+ * expiry is past, empty or no date is not live whatever a file says (A-SPEC-245.18); a usable grant is live whatever a
471
+ * `consumed` row says (A-SPEC-794.33).
472
+ */
473
+ function grantedStateOf(g, nowMs) {
474
+ const exp = g.expires ? Date.parse(g.expires) : NaN;
475
+ const expired = g.expires !== undefined && (!Number.isFinite(exp) || (Number.isFinite(nowMs) && nowMs > exp));
476
+ if (g.covers && !expired)
477
+ return 'live';
478
+ if (g.claimed)
479
+ return 'claimed';
480
+ if (g.consumedTs)
481
+ return 'consumed';
482
+ return expired ? 'expired' : 'unusable';
483
+ }
484
+ /**
485
+ * @implements A-SPEC-794.37 — what each file the store reads holds, for the screens: its first scope, and whether it covers
486
+ * now (usable on the ledger, unexpired, not bound to another workspace).
487
+ */
488
+ function grantFileFacts(root, now) {
489
+ const dir = path.join(root, exports.GRANTS_RELDIR);
490
+ const usable = new Set();
491
+ try {
492
+ for (const g of readGrants(root).grants)
493
+ usable.add(g.nonce);
494
+ }
495
+ catch { /* covers nothing */ }
496
+ const workspace = currentWorkspaceId(root);
497
+ const nowMs = Date.parse(now);
498
+ return grantFileNames(root).map((file) => {
499
+ const g = readGrantJson(path.join(dir, file));
500
+ const first = namedScopes(g)[0];
501
+ const exp = typeof g?.expires === 'string' ? Date.parse(g.expires) : NaN;
502
+ const covers = g !== null && usable.has(g.nonce) && Number.isFinite(exp) && nowMs <= exp
503
+ && (typeof g.workspace !== 'string' || g.workspace === '' || g.workspace === workspace);
504
+ return { file, kind: first?.kind ?? '', pattern: first?.pattern ?? '', exact: first?.exact ?? false, covers };
505
+ });
506
+ }
507
+ /**
508
+ * @implements A-SPEC-245.4 — the grants one decision resolved, settled once when that decision is final. Each branch
509
+ * that resolves a grant holds it here; `settle(true)` claims every held grant (one lost claim returns the rest and
510
+ * answers 'lost') and commits them, `settle(false)` spends nothing. A counterfactual settlement never spends: the
511
+ * hook's audit re-asks its question with no approval, and that reading is not a decision.
512
+ */
513
+ class GrantSettlement {
514
+ spends;
515
+ held = new Map();
516
+ envHeld = new Map();
517
+ spent = [];
518
+ outcome = null;
519
+ why;
520
+ constructor(spends = true) {
521
+ this.spends = spends;
522
+ }
523
+ static counterfactual() { return new GrantSettlement(false); }
524
+ hold(root, nonce, approval) {
525
+ if (this.outcome !== null)
526
+ throw new Error('a settled GrantSettlement cannot hold another grant');
527
+ this.held.set(`${root}\0${nonce}`, { root, nonce, ...(approval ? { approval } : {}) });
528
+ }
529
+ /** @implements A-SPEC-245.9 (1b-2) — an environment single-use approval, spent with the grants when the decision is final. */
530
+ holdEnv(root, nonce, approval, summary) {
531
+ if (this.outcome !== null)
532
+ throw new Error('a settled GrantSettlement cannot hold another approval');
533
+ this.envHeld.set(`${root}\0${nonce}`, { root, nonce, approval, summary });
534
+ }
535
+ /** The approvals of the grants this settlement spent. */
536
+ get committed() { return this.spent; }
537
+ /** Why the spend refused (outcome `refused`). */
538
+ get refusal() { return this.why; }
539
+ /** @implements A-SPEC-245.9 (1b-2) — what a final allow would spend, as data another thread can settle. */
540
+ pending() {
541
+ return { held: [...this.held.values()], env: [...this.envHeld.values()] };
542
+ }
543
+ static fromPending(p) {
544
+ const s = new GrantSettlement();
545
+ for (const h of p.held)
546
+ s.hold(h.root, h.nonce, h.approval);
547
+ for (const e of p.env)
548
+ s.holdEnv(e.root, e.nonce, e.approval, e.summary);
549
+ return s;
211
550
  }
212
- // @implements A-SPEC-649 — the spend is a queue event too, so the decision surface can show the
213
- // grant's outcome without reading the provenance ledger. Best-effort, like the removal itself.
214
- if (removed > 0) {
551
+ /** @implements A-SPEC-245.9 (1b-2) — take the outcome another thread settled for this settlement's pending spends. */
552
+ adopt(r) {
553
+ if (this.outcome !== null)
554
+ return this.outcome;
555
+ this.spent.push(...r.committed);
556
+ this.why = r.refusal;
557
+ return (this.outcome = r.outcome);
558
+ }
559
+ /**
560
+ * @implements A-SPEC-245.4, A-SPEC-245.9 (1b-2) — on a final allow: claim every held grant (one lost claim returns the
561
+ * rest: `lost`), write every spend row — the grants' and the environment nonces' — in one spendApprovals call per root
562
+ * under the workspace spend lock (not ok: the claims are returned, `refused`), then commit the claims.
563
+ */
564
+ settle(allowed) {
565
+ if (this.outcome !== null)
566
+ return this.outcome;
567
+ if (!allowed || !this.spends || (this.held.size === 0 && this.envHeld.size === 0))
568
+ return (this.outcome = 'settled');
569
+ const claims = [];
570
+ for (const { root, nonce, approval } of this.held.values()) {
571
+ const claim = claimGrant(root, nonce);
572
+ if (claim === null) {
573
+ for (const c of claims)
574
+ c.claim.release();
575
+ return (this.outcome = 'lost');
576
+ }
577
+ claims.push({ claim, ...(approval ? { approval } : {}) });
578
+ }
579
+ const byRoot = new Map();
580
+ const add = (root, s) => byRoot.set(root, [...(byRoot.get(root) ?? []), s]);
581
+ for (const { root, nonce, approval } of this.held.values()) {
582
+ if (approval)
583
+ add(root, { nonce, actor: approval.actor, summary: 'consumed approval grant for: the hook judgement it allowed', rationale: approval.rationale, authorization: (0, provenance_chain_1.authorizationRef)(approval.actor, approval.token) });
584
+ }
585
+ for (const { root, nonce, approval, summary } of this.envHeld.values()) {
586
+ add(root, { nonce, actor: approval.actor, summary, rationale: approval.rationale, authorization: (0, provenance_chain_1.authorizationRef)(approval.actor, approval.token) });
587
+ }
588
+ for (const [root, spends] of byRoot) {
589
+ let r;
590
+ try {
591
+ r = (0, approval_spend_1.spendApprovals)(root, spends, {});
592
+ }
593
+ catch {
594
+ r = 'error';
595
+ }
596
+ if (r === 'error' || r.ok === false) {
597
+ for (const c of claims)
598
+ c.claim.release();
599
+ this.why = (0, approval_spend_1.spendRefusalReason)(r);
600
+ return (this.outcome = 'refused');
601
+ }
602
+ }
603
+ for (const { claim, approval } of claims) {
604
+ if (approval)
605
+ this.spent.push(approval);
606
+ try {
607
+ claim.commit();
608
+ }
609
+ catch (e) {
610
+ process.stderr.write(`[Holmes-Kit] ${e.message}\n`);
611
+ }
612
+ }
613
+ return (this.outcome = 'settled');
614
+ }
615
+ }
616
+ exports.GrantSettlement = GrantSettlement;
617
+ /**
618
+ * @implements A-SPEC-245.2 — the act inside a claim: committed when `succeeded` says so, released on a refusal or a throw.
619
+ * A claim lost to another act answers `lost()`; an act with no grant (an env approval) runs as it is.
620
+ */
621
+ async function withGrant(root, resolved, act, succeeded, lost, onThrow = () => 'release') {
622
+ if (!resolved || resolved.source !== 'grant' || !resolved.approval.nonce)
623
+ return act();
624
+ const claim = claimGrant(root, resolved.approval.nonce);
625
+ if (claim === null)
626
+ return lost();
627
+ let result;
628
+ try {
629
+ result = await act();
630
+ }
631
+ catch (e) {
632
+ // A-SPEC-245.15 (item 2): a throw after the spend was recorded commits — the grant is used and never comes back
633
+ if (onThrow() === 'commit') {
634
+ try {
635
+ claim.commit();
636
+ }
637
+ catch (c) {
638
+ process.stderr.write(`[Holmes-Kit] ${c.message}\n`);
639
+ }
640
+ }
641
+ else
642
+ claim.release();
643
+ throw e;
644
+ }
645
+ if (succeeded(result)) {
646
+ try {
647
+ claim.commit();
648
+ }
649
+ catch (e) {
650
+ process.stderr.write(`[Holmes-Kit] ${e.message}\n`);
651
+ }
652
+ }
653
+ else
654
+ claim.release();
655
+ return result;
656
+ }
657
+ /**
658
+ * @implements A-SPEC-245.4 — `withGrant` for an act that runs synchronously under a lock, so the claim is settled before
659
+ * the lock is released. `onThrow` says whether a throw comes after the act already did what the grant authorized.
660
+ */
661
+ function withGrantSync(root, resolved, act, succeeded, lost, onThrow = () => 'release') {
662
+ if (!resolved || resolved.source !== 'grant' || !resolved.approval.nonce)
663
+ return act();
664
+ const claim = claimGrant(root, resolved.approval.nonce);
665
+ if (claim === null)
666
+ return lost();
667
+ let result;
668
+ try {
669
+ result = act();
670
+ }
671
+ catch (e) {
672
+ if (onThrow() === 'commit') {
673
+ try {
674
+ claim.commit();
675
+ }
676
+ catch (c) {
677
+ process.stderr.write(`[Holmes-Kit] ${c.message}\n`);
678
+ }
679
+ }
680
+ else
681
+ claim.release();
682
+ throw e;
683
+ }
684
+ if (succeeded(result)) {
685
+ try {
686
+ claim.commit();
687
+ }
688
+ catch (e) {
689
+ process.stderr.write(`[Holmes-Kit] ${e.message}\n`);
690
+ }
691
+ }
692
+ else
693
+ claim.release();
694
+ return result;
695
+ }
696
+ /**
697
+ * @implements A-SPEC-245.2 — claim and commit, for a path that acted under its own lock (entity store, review evidence,
698
+ * runtime binding, the CLI's one-shot acts). A grant with nothing to claim is reported, as before.
699
+ */
700
+ function spendGrants(root, nonces) {
701
+ for (const nonce of nonces) {
702
+ const claim = claimGrant(root, nonce);
703
+ if (claim === null) {
704
+ process.stderr.write(`[Holmes-Kit] approval grant was used but no grant file matched it — the grant may still be spendable. Remove it by hand from ${exports.GRANTS_RELDIR}.\n`);
705
+ continue;
706
+ }
215
707
  try {
216
- (0, approval_queue_1.appendQueueEvent)(root, { event: 'consumed', id: wanted });
708
+ claim.commit();
217
709
  }
218
- catch { /* fire-and-forget */ }
710
+ catch (e) {
711
+ process.stderr.write(`[Holmes-Kit] ${e.message}\n`);
712
+ }
713
+ }
714
+ }
715
+ /**
716
+ * @implements A-SPEC-245.9 (1b-1) — an act that a spend refused: `spent` is a replay; `conflict` and `unconfirmed` name
717
+ * the spend-conflict-detected row; `error` is a spend lock or chain lock not obtained in its budget. Nothing acted.
718
+ */
719
+ class GrantSpendRefusal extends Error {
720
+ result;
721
+ holmesRefusal = true;
722
+ constructor(result) {
723
+ super((0, approval_spend_1.spendRefusalReason)(result));
724
+ this.result = result;
725
+ }
726
+ }
727
+ exports.GrantSpendRefusal = GrantSpendRefusal;
728
+ /**
729
+ * @implements A-SPEC-245.9 (1b-1) — spend grant approvals once across every replica chain: one nonce-consumed row per
730
+ * nonce under the workspace spend lock (spendApprovals), written where the act's first byte is about to be written and
731
+ * after every refusal that precedes it. `rationale` carries an entity operation's id, so its recovery can tell its own
732
+ * spend. Throws GrantSpendRefusal when the spend does not answer ok. The grant files stay with their claim or with
733
+ * `spendGrants`, which removes them after the act.
734
+ */
735
+ function spendGrantApprovals(root, approvals, what, rationale) {
736
+ // an operation's own earlier spend (same nonce, same op id in rationale) is not spent again: its recovery or retry
737
+ const own = rationale === undefined ? new Set() : ownSpends(root, rationale);
738
+ const spends = [...new Map(approvals.filter((a) => typeof a.nonce === 'string' && a.nonce.trim() !== '' && !own.has((0, provenance_chain_1.nonceFingerprint)(a.nonce)))
739
+ .map((a) => [String(a.nonce), a])).values()]
740
+ .map((a) => ({ nonce: String(a.nonce), actor: a.actor, summary: `${GRANT_SPEND_SUMMARY}${what}`.slice(0, 200),
741
+ rationale: rationale ?? a.rationale, authorization: (0, provenance_chain_1.authorizationRef)(a.actor, a.token) }));
742
+ if (spends.length === 0)
743
+ return;
744
+ let r;
745
+ try {
746
+ r = (0, approval_spend_1.spendApprovals)(root, spends, {});
747
+ }
748
+ catch {
749
+ r = 'error';
750
+ }
751
+ if (r === 'error' || r.ok === false)
752
+ throw new GrantSpendRefusal(r);
753
+ }
754
+ const GRANT_SPEND_SUMMARY = 'consumed approval grant for: ';
755
+ /** The fingerprints this operation (its op id in `rationale`) already spent. */
756
+ function ownSpends(root, rationale) {
757
+ const dir = path.join(root, '.ax', 'ledger');
758
+ if (!fs.existsSync(dir))
759
+ return new Set();
760
+ // A-SPEC-245.15 (6a): only this function's own entity spend rows count — kind, the summary it writes for an entity act,
761
+ // and the op key in rationale; a row of another path that happens to carry the same rationale is not ours
762
+ // @implements A-SPEC-222.10 — H-C: trusted rows only (a forged own-spend row would leave a single-use grant unspent)
763
+ const { TrustedLedgerStore } = require('./recorded-pairs');
764
+ return new Set(new TrustedLedgerStore(dir).loadAll().filter((e) => e.kind === (0, spend_kinds_1.spendKind)('grant') && e.rationale === rationale
765
+ && typeof e.summary === 'string' && e.summary.startsWith(`${GRANT_SPEND_SUMMARY}entity-`)).flatMap((e) => e.inputs ?? []));
766
+ }
767
+ /**
768
+ * @implements A-SPEC-245.9 (1b-1) — the store's beforePublish (A-SPEC-245.14) for an act a grant authorized: undefined
769
+ * when no grant authorized it (an env approval runs as before).
770
+ */
771
+ function grantSpend(resolved, what, onSpent) {
772
+ if (!resolved || resolved.source !== 'grant' || !resolved.root || !resolved.approval.nonce)
773
+ return undefined;
774
+ const { root, approval } = resolved;
775
+ return () => { spendGrantApprovals(root, [approval], what); onSpent?.(); return undefined; };
776
+ }
777
+ /** @implements A-SPEC-245.2 — claimed files whose process is gone: a crash between claim and settle, for `doctor`. */
778
+ function staleClaims(root) {
779
+ const dir = path.join(root, exports.GRANTS_RELDIR);
780
+ let names;
781
+ try {
782
+ names = fs.readdirSync(dir).filter((n) => n.startsWith(exports.CLAIM_PREFIX));
783
+ }
784
+ catch {
785
+ return [];
219
786
  }
220
- if (removed === 0) {
221
- // Consumption runs AFTER the act succeeded, so this must never throw — but it must not be silent
222
- // either: an unspent single-use grant is still spendable, and nobody would know.
223
- process.stderr.write(`[Holmes-Kit] approval grant was used but no grant file matched it — the grant may still be spendable. Remove it by hand from ${exports.GRANTS_RELDIR}.\n`);
787
+ const out = [];
788
+ for (const name of names) {
789
+ const m = /^\.claimed\.(\d+)\.(\d+)\./.exec(name);
790
+ if (!m)
791
+ continue;
792
+ const pid = Number(m[1]);
793
+ let alive = true;
794
+ try {
795
+ process.kill(pid, 0);
796
+ }
797
+ catch (e) {
798
+ alive = e.code === 'EPERM';
799
+ }
800
+ if (!alive)
801
+ out.push({ file: path.join(exports.GRANTS_RELDIR, name), pid, at: new Date(Number(m[2])).toISOString() });
224
802
  }
803
+ return out;
225
804
  }