@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
@@ -0,0 +1,718 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ADVISORY_SHORT = exports.WORDING_VERSION = exports.SILENT_STREAK_MAX = exports.REEMIT_AFTER = exports.MUST_SAY_MEANING = void 0;
37
+ exports.openEpoch = openEpoch;
38
+ exports.advisoryDetail = advisoryDetail;
39
+ exports.advisoryLine = advisoryLine;
40
+ exports.adviseWarn = adviseWarn;
41
+ exports.adviseClean = adviseClean;
42
+ exports.isGitCommit = isGitCommit;
43
+ exports.commitReminder = commitReminder;
44
+ exports.commitAdvisory = commitAdvisory;
45
+ // @implements A-SPEC-333.1, A-SPEC-333.2, A-SPEC-333.3, A-SPEC-333.4, A-SPEC-333.5, A-SPEC-333.6, A-SPEC-333.7, A-SPEC-333.8, A-SPEC-333.9, A-SPEC-333.10
46
+ const crypto = __importStar(require("node:crypto"));
47
+ const fs = __importStar(require("node:fs"));
48
+ const os = __importStar(require("node:os"));
49
+ const path = __importStar(require("node:path"));
50
+ const impact_gate_1 = require("./impact-gate");
51
+ /**
52
+ * A pre-edit warning said once, then not again while it is still in the reader's context.
53
+ *
54
+ * Measured over 379 transcripts of this repository (2026-11-05): 98.6% of the Holmes hook context was this gate's warning,
55
+ * and half of it repeated a sentence already shown. The decision never changes here — only what is said with it.
56
+ *
57
+ * Per compaction epoch (opened by SessionStart, every source), per session and agent, in a Claude Code session only
58
+ * (A-SPEC-333.4: the one harness whose compaction signal is observed):
59
+ * - each code's explanation is said once, with the call to clear it;
60
+ * - a line — codes, target, detail — is said once; again after REEMIT_AFTER warnings (context editing drops old results
61
+ * with no compact signal), after SILENT_STREAK_MAX silent judgements of the same file, and whenever its detail changes;
62
+ * - an allowed `git commit` names the files still at a refuse verdict, once per epoch.
63
+ * Nothing is recorded while judging: `commitAdvisory` records only what the final allow actually carried. Every committed
64
+ * warning of every harness also appends a judgement-ledger row, outside the epoch store (A-SPEC-333.5). Every doubt about
65
+ * the store, the epoch or the transcript means "say it in full".
66
+ */
67
+ /**
68
+ * MUST_SAY_MEANING — "must say" means at least once per epoch, and again whenever the wording (the detail) changes.
69
+ * So no code is exempt from the silent repeat: a repeat inside the epoch is already in the reader's context (supervisor
70
+ * decision (b), 2026-11-05; the measured cost of exempting contract-untested and multi-step codes was c/d 0.441).
71
+ */
72
+ exports.MUST_SAY_MEANING = 'at least once per epoch, and again whenever the detail changes';
73
+ /**
74
+ * Re-say a silent line after this many warnings in the session (A-SPEC-333.3). No context-horizon measurement exists to
75
+ * set it; the per-file silence cap below bounds silence on the file being edited (A-SPEC-333.4, 333.5).
76
+ */
77
+ exports.REEMIT_AFTER = 29;
78
+ /** A file judged silent this many times since it was last said is said again on its next judgement (A-SPEC-333.5). */
79
+ exports.SILENT_STREAK_MAX = 5;
80
+ /** The ledger rows' wording, so the wording's effect on behaviour can be measured apart (A-SPEC-333.5). */
81
+ exports.WORDING_VERSION = 2;
82
+ /** The next step for each code, short and without call arguments: the first explanation carries those. */
83
+ exports.ADVISORY_SHORT = {
84
+ 'no-analysis': 'run maintenance_analyze naming this file',
85
+ 'basis-drift': 're-analyze on this commit',
86
+ 'target-drift': 'own edit: re-analyze before commit; else re-analyze now',
87
+ 'target-out-of-scope': 're-analyze with a request naming this file',
88
+ 'contract-untested': 'approve the T-SPEC for the impacted A-SPEC',
89
+ 'unproven-absence': 'widen the analysis (changedFiles, coverage, bounds)',
90
+ 'architecture-unchecked': 'pass changedFiles to maintenance_analyze',
91
+ 'security-unchecked': 're-analyze on a tree it can scan',
92
+ 'compatibility-unchecked': 're-analyze where the spec store is readable',
93
+ 'basis-unverifiable': 're-analyze at this HEAD',
94
+ 'trace-gap': 'anchor the declaring A-SPEC or widen the analysis',
95
+ };
96
+ const STORE_MAX_BYTES = 64 * 1024;
97
+ const LEDGER_MAX_BYTES = 1024 * 1024;
98
+ const LEDGER_ROTATED_MAX = 5;
99
+ const TAIL_BYTES = 256 * 1024;
100
+ const READ_BUDGET_MS = 50;
101
+ const OWN_BOUNDARY_MS = 2000;
102
+ const REMINDER_NAMES = 3;
103
+ const hex32 = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 32);
104
+ const tkeyOf = (target) => hex32(target).slice(0, 16);
105
+ function baseDir(dir) {
106
+ if (dir)
107
+ return path.resolve(dir);
108
+ let tmp = os.tmpdir();
109
+ try {
110
+ tmp = fs.realpathSync(tmp);
111
+ }
112
+ catch { /* the inside-project check still applies */ }
113
+ const uid = typeof process.getuid === 'function' ? String(process.getuid()) : 'user';
114
+ return path.join(tmp, `holmes-kit-${uid}`, 'advisory-seen');
115
+ }
116
+ const within = (child, parent) => { const r = path.relative(parent, child); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
117
+ function insideProject(d, projectRoot) {
118
+ let root = path.resolve(projectRoot);
119
+ try {
120
+ root = fs.realpathSync(projectRoot);
121
+ }
122
+ catch { /* compare the given path */ }
123
+ return within(d, root) || within(d, path.resolve(projectRoot));
124
+ }
125
+ /** `<base>/<session>/<project>`: any SessionStart of a session empties every project table of it. null inside the project. */
126
+ function storeDir(projectRoot, session, dir) {
127
+ const d = path.join(baseDir(dir), hex32(session).slice(0, 16), hex32(path.resolve(projectRoot)).slice(0, 16));
128
+ return insideProject(d, projectRoot) ? null : d;
129
+ }
130
+ /**
131
+ * A directory we made, and every directory above it up to `holmes-kit-<uid>`: real directories (no link), ours, written by
132
+ * nobody else. In a shared temp directory another user could otherwise plant the parent.
133
+ */
134
+ function trustedDir(d, dir) {
135
+ const top = path.dirname(baseDir(dir));
136
+ for (let p = d;; p = path.dirname(p)) {
137
+ const st = fs.lstatSync(p);
138
+ if (!st.isDirectory())
139
+ return false;
140
+ if (typeof process.getuid === 'function' && (st.uid !== process.getuid() || (st.mode & 0o022) !== 0))
141
+ return false;
142
+ if (p === top || p === path.dirname(p))
143
+ return true;
144
+ }
145
+ }
146
+ /** Read a regular file without following a link and without blocking; null for anything else. Optionally only its tail. */
147
+ function readRegular(file, tail) {
148
+ const st = fs.lstatSync(file);
149
+ if (!st.isFile())
150
+ return null;
151
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
152
+ try {
153
+ if (tail === undefined)
154
+ return fs.readFileSync(fd, 'utf8');
155
+ const len = Math.min(tail, st.size);
156
+ const buf = Buffer.alloc(len);
157
+ fs.readSync(fd, buf, 0, len, st.size - len);
158
+ return buf.toString('utf8');
159
+ }
160
+ finally {
161
+ fs.closeSync(fd);
162
+ }
163
+ }
164
+ /**
165
+ * SessionStart, first act: a new epoch for the session. Every epoch marker of the session goes first, then every table,
166
+ * then the new marker with its time, the transcript's size and the SessionStart source. The judgement ledger is outside
167
+ * and is never touched. Fail-quiet: without a marker the gate says everything in full.
168
+ */
169
+ function openEpoch(projectRoot, session, opts) {
170
+ const o = typeof opts === 'string' ? { dir: opts } : (opts ?? {});
171
+ try {
172
+ const d = storeDir(projectRoot, session, o.dir);
173
+ if (!d || !session)
174
+ return;
175
+ const sess = path.dirname(d);
176
+ try {
177
+ for (const p of fs.readdirSync(sess)) {
178
+ try {
179
+ fs.unlinkSync(path.join(sess, p, 'epoch'));
180
+ }
181
+ catch { /* none */ }
182
+ }
183
+ }
184
+ catch { /* no session yet */ }
185
+ fs.mkdirSync(d, { recursive: true, mode: 0o700 });
186
+ if (!trustedDir(d, o.dir))
187
+ return; // a planted or shared parent: no epoch, so everything stays in full
188
+ fs.rmSync(sess, { recursive: true, force: true });
189
+ fs.mkdirSync(d, { recursive: true, mode: 0o700 });
190
+ let transcriptSize = 0;
191
+ try {
192
+ if (o.transcriptPath) {
193
+ const st = fs.lstatSync(o.transcriptPath);
194
+ if (st.isFile())
195
+ transcriptSize = st.size;
196
+ }
197
+ }
198
+ catch { /* unknown size: 0 */ }
199
+ const fd = fs.openSync(path.join(d, 'epoch'), fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
200
+ try {
201
+ fs.writeSync(fd, `${JSON.stringify({ ts: new Date().toISOString(), transcriptSize, source: o.source ?? '' })}\n`);
202
+ }
203
+ finally {
204
+ fs.closeSync(fd);
205
+ }
206
+ }
207
+ catch { /* no epoch: the gate says everything in full */ }
208
+ }
209
+ /**
210
+ * The epoch is void when the transcript shrank since it opened, or when a compact boundary newer than it sits in the tail.
211
+ * A boundary is a line that parses as `{ type: 'system', subtype: 'compact_boundary' }` — never a string that mentions one.
212
+ * An epoch a compact SessionStart opened owns the first boundary within two seconds after it: the same compaction.
213
+ */
214
+ function epochHolds(epoch, transcriptPath) {
215
+ if (!transcriptPath)
216
+ return true;
217
+ let st;
218
+ try {
219
+ st = fs.lstatSync(transcriptPath);
220
+ }
221
+ catch {
222
+ return true;
223
+ } // no transcript to judge by: the marker stands
224
+ if (!st.isFile())
225
+ return false;
226
+ if (st.size < epoch.transcriptSize)
227
+ return false;
228
+ const tail = readRegular(transcriptPath, TAIL_BYTES);
229
+ if (tail === null)
230
+ return false;
231
+ let owned = epoch.source !== 'compact';
232
+ for (const row of tail.split('\n')) {
233
+ if (!row.includes('compact_boundary'))
234
+ continue;
235
+ let o;
236
+ try {
237
+ o = JSON.parse(row);
238
+ }
239
+ catch {
240
+ continue;
241
+ } // a cut first line of the tail
242
+ if (o.type !== 'system' || o.subtype !== 'compact_boundary' || typeof o.timestamp !== 'string' || !(o.timestamp > epoch.ts))
243
+ continue;
244
+ if (!owned && Date.parse(o.timestamp) - Date.parse(epoch.ts) <= OWN_BOUNDARY_MS) {
245
+ owned = true;
246
+ continue;
247
+ }
248
+ return false;
249
+ }
250
+ return true;
251
+ }
252
+ /**
253
+ * @implements A-SPEC-333.6 — every agent table of the epoch merged by time: a file is still warned when its latest W
254
+ * (a refuse verdict) is newer than its latest K (another verdict, or a clean allow), whichever agent wrote them.
255
+ */
256
+ function epochStanding(d) {
257
+ const w = new Map();
258
+ const k = new Map();
259
+ let reminded = false;
260
+ for (const name of fs.readdirSync(d)) {
261
+ if (!name.endsWith('.txt'))
262
+ continue;
263
+ // A-SPEC-333.8 — another agent's table is bounded like this agent's: anything larger was not written by this module
264
+ let size = Infinity;
265
+ try {
266
+ size = fs.lstatSync(path.join(d, name)).size;
267
+ }
268
+ catch { /* gone: skipped */ }
269
+ if (size > STORE_MAX_BYTES + 4096)
270
+ continue;
271
+ const text = readRegular(path.join(d, name));
272
+ if (text === null)
273
+ continue;
274
+ for (const row of text.split('\n')) {
275
+ const [kind, a, b, c] = row.split(' ');
276
+ if (kind === 'W' && a && b) {
277
+ const at = Number(c) || 0;
278
+ if (at >= (w.get(a)?.at ?? -1))
279
+ w.set(a, { target: Buffer.from(b, 'base64').toString('utf8'), at });
280
+ }
281
+ else if (kind === 'K' && a)
282
+ k.set(a, Math.max(k.get(a) ?? -1, Number(b) || 0));
283
+ else if (kind === 'R')
284
+ reminded = true;
285
+ }
286
+ }
287
+ const unresolved = new Map();
288
+ for (const [tkey, { target, at }] of [...w].sort((x, y) => x[1].at - y[1].at))
289
+ if (at > (k.get(tkey) ?? -1))
290
+ unresolved.set(tkey, target);
291
+ return { unresolved, reminded };
292
+ }
293
+ /** The session's tables, read only. null: say it in full (no epoch, a void epoch, an untrusted store, damage, an error, over budget). */
294
+ function readState(projectRoot, ctx) {
295
+ const started = Date.now();
296
+ try {
297
+ if (!ctx.session)
298
+ return null;
299
+ const d = storeDir(projectRoot, ctx.session, ctx.dir);
300
+ if (!d || !trustedDir(d, ctx.dir))
301
+ return null;
302
+ const markerFile = path.join(d, 'epoch');
303
+ const marker = readRegular(markerFile);
304
+ if (marker === null)
305
+ return null;
306
+ let epoch;
307
+ try {
308
+ const e = JSON.parse(marker);
309
+ epoch = { ts: String(e.ts ?? ''), transcriptSize: Number(e.transcriptSize) || 0, source: String(e.source ?? '') };
310
+ }
311
+ catch {
312
+ return null;
313
+ }
314
+ if (!epochHolds(epoch, ctx.transcriptPath)) {
315
+ // A-SPEC-333.5 — the void persists: once the boundary leaves the tail, the old tables must not come back
316
+ try {
317
+ fs.unlinkSync(markerFile);
318
+ }
319
+ catch { /* full text either way */ }
320
+ return null;
321
+ }
322
+ const file = path.join(d, `${hex32(ctx.agent ?? '').slice(0, 16)}.txt`);
323
+ const state = { dir: d, file, epoch: epoch.ts, explained: new Set(), lines: new Map(), count: 0, streaks: new Map(), unresolved: new Map(), reminded: false, contractSaid: new Map() };
324
+ let st = null;
325
+ try {
326
+ st = fs.lstatSync(file);
327
+ }
328
+ catch (e) {
329
+ if (e.code !== 'ENOENT')
330
+ return null;
331
+ }
332
+ if (st) {
333
+ // eviction keeps the file at 64KB plus one append; anything larger was not written by this module
334
+ if (!st.isFile() || st.size > STORE_MAX_BYTES + 4096)
335
+ return null;
336
+ const text = readRegular(file);
337
+ if (text === null)
338
+ return null;
339
+ for (const row of text.split('\n')) {
340
+ const [kind, a, b] = row.split(' ');
341
+ if (kind === 'C')
342
+ state.count += Number(a) || 0;
343
+ else if (kind === 'V')
344
+ state.count++;
345
+ else if (kind === 'E' && a)
346
+ state.explained.add(a);
347
+ else if (kind === 'L' && a)
348
+ state.lines.set(a, Number(b) || 0);
349
+ else if (kind === 'J' && a)
350
+ state.streaks.set(a, b === 's' ? (state.streaks.get(a) ?? 0) + 1 : 0);
351
+ else if (kind === 'S' && a)
352
+ state.streaks.set(a, Number(b) || 0);
353
+ else if (kind === 'R')
354
+ state.reminded = true;
355
+ // A-SPEC-333.8 — this agent's own table only: a parent's context does not hold what its subagent was told
356
+ else if (kind === 'P' && a)
357
+ state.contractSaid.set(a, Number(row.split(' ')[3]) || 0);
358
+ }
359
+ // A-SPEC-333.4 — a line said at an index the count never reached was not written by this module
360
+ for (const idx of state.lines.values())
361
+ if (idx > state.count)
362
+ return null;
363
+ }
364
+ // A-SPEC-333.6 — the files still warned and the reminder mark are the epoch's, across every agent's table
365
+ const merged = epochStanding(d);
366
+ state.unresolved = merged.unresolved;
367
+ state.reminded = state.reminded || merged.reminded;
368
+ return Date.now() - started > READ_BUDGET_MS ? null : state;
369
+ }
370
+ catch {
371
+ return null;
372
+ }
373
+ }
374
+ /** The detail a line names: the analysis it read, and HEAD only when HEAD is the reason. (The hook's evidence carries no trace gaps.) */
375
+ function advisoryDetail(o) {
376
+ const parts = [];
377
+ if (o.artifactDigest)
378
+ parts.push(o.artifactDigest.replace(/^sha256:/, '').slice(0, 12));
379
+ if (o.traceGaps && o.traceGaps.length > 0)
380
+ parts.push([...new Set(o.traceGaps.map((g) => g.id))].sort().join(','));
381
+ if (o.codes.some((c) => c === 'basis-drift' || c === 'basis-unverifiable'))
382
+ parts.push(`head ${o.head.slice(0, 12)}`);
383
+ return parts.join(' ');
384
+ }
385
+ /** The line: the verdict's strength and the outcome first, then what clears it (no "required": nothing enforces it under warn). */
386
+ function advisoryLine(verdict, target, detail = '') {
387
+ const codes = verdict.reasons.map((r) => r.code);
388
+ const steps = [...new Set(codes.map((c) => exports.ADVISORY_SHORT[c]))].join('; ');
389
+ return `[Holmes-Kit:${codes.join(',')}] ${target} — ${verdict.decision}→allowed (warn); to clear: ${steps}${detail ? ` [${detail}]` : ''}`;
390
+ }
391
+ /**
392
+ * What to say for a warn allow. `undefined`: say `full`, the A-SPEC-333 sentence (no session, no compression for this
393
+ * harness, no epoch, a void epoch, an untrusted store). `null`: say nothing. A string: say it. What the caller commits
394
+ * after the final decision goes into `ctx.pending`, the ledger row with it — a ledger row in every case.
395
+ */
396
+ function adviseWarn(projectRoot, ctx, verdict, target, detail, full = '') {
397
+ if (!ctx)
398
+ return undefined;
399
+ const codes = verdict.reasons.map((r) => r.code);
400
+ const state = readState(projectRoot, ctx);
401
+ // A-SPEC-333.8 — the characters said and the full sentence's, so occupancy can be judged from the ledger alone
402
+ const row = (kind, said) => ({ ts: new Date().toISOString(), project: hex32(path.resolve(projectRoot)).slice(0, 16), agent: ctx.agent ?? '', tool_use_id: ctx.toolUseId ?? '', target, codes,
403
+ verdict: verdict.decision, kind, epoch: state?.epoch ?? '', k_index: state?.count ?? -1, wording_version: exports.WORDING_VERSION, said_chars: said.length, full_chars: full.length,
404
+ harness: ctx.harness ?? '', compress: ctx.compress });
405
+ if (!state) {
406
+ ctx.pending.push({ file: '', entries: [], said: full, ledger: row('said', full) });
407
+ return undefined;
408
+ }
409
+ const tkey = tkeyOf(target);
410
+ // A-SPEC-333.5 — the reminder lists a file only while its last judgement was a refuse verdict
411
+ const now = Date.now();
412
+ const standing = verdict.decision === 'refuse' ? [`W ${tkey} ${Buffer.from(target, 'utf8').toString('base64')} ${now}`] : [`K ${tkey} ${now}`];
413
+ if (!ctx.compress) {
414
+ ctx.pending.push({ file: state.file, entries: [`J ${tkey} f`, ...standing, 'V'], said: full, ledger: row('said', full) });
415
+ return undefined;
416
+ }
417
+ const index = state.count;
418
+ const streak = state.streaks.get(tkey) ?? 0;
419
+ const silent = () => {
420
+ ctx.pending.push({ file: state.file, entries: [`J ${tkey} s`, ...standing, 'V'], said: '', ledger: row('silent', '') });
421
+ return null;
422
+ };
423
+ // A-SPEC-333.7 — contract-untested belongs to the analysis, not the file: said once per analysis detail in an epoch.
424
+ // A-SPEC-333.8 — by this agent; a warning that has nothing else to say keeps the caps every other silence keeps.
425
+ const recent = (codesOf) => {
426
+ const last = state.lines.get(hex32(JSON.stringify([[...codesOf].sort(), target, detail])));
427
+ return last !== undefined && index - last < exports.REEMIT_AFTER && streak < exports.SILENT_STREAK_MAX && codesOf.every((c) => state.explained.has(c));
428
+ };
429
+ // the very line just said, codes and all, is a repeat before contract-untested is dropped from anything
430
+ if (recent(codes))
431
+ return silent();
432
+ const pkey = detail ? hex32(detail).slice(0, 16) : '';
433
+ const saidAt = pkey !== '' ? state.contractSaid.get(pkey) : undefined;
434
+ const others = verdict.reasons.filter((r) => r.code !== 'contract-untested');
435
+ if (saidAt !== undefined && others.length === 0 && index - saidAt < exports.REEMIT_AFTER && streak < exports.SILENT_STREAK_MAX)
436
+ return silent();
437
+ // A-SPEC-333.9 — mixed with other codes, it is left out only while it is recent (the same REEMIT_AFTER bound)
438
+ // A-SPEC-333.10 — and while the file's silences hold: a re-say forced by the streak cap carries it, as a lone one does
439
+ const reasons = saidAt !== undefined && others.length > 0 && index - saidAt < exports.REEMIT_AFTER && streak < exports.SILENT_STREAK_MAX ? others : verdict.reasons;
440
+ const shown = reasons.map((r) => r.code);
441
+ const key = hex32(JSON.stringify([[...shown].sort(), target, detail]));
442
+ const unexplained = reasons.filter((r, i) => !state.explained.has(r.code) && shown.indexOf(r.code) === i);
443
+ if (recent(shown))
444
+ return silent();
445
+ const text = [advisoryLine({ ...verdict, reasons }, target, detail), ...unexplained.map((r) => `${r.code}: ${r.detail} ${(0, impact_gate_1.remediationFor)(r.code)}`)].join('\n');
446
+ const contractMark = pkey !== '' && shown.includes('contract-untested') ? [`P ${pkey} ${now} ${index}`] : [];
447
+ ctx.pending.push({ file: state.file, entries: [...unexplained.map((r) => `E ${r.code}`), `L ${key} ${index}`, `J ${tkey} l`, ...contractMark, ...standing, 'V'], said: text, ledger: row('line', text) });
448
+ return text;
449
+ }
450
+ /** A clean allow of a file: it is no longer warned (the commit reminder drops it). Recorded with the final allow. */
451
+ function adviseClean(projectRoot, ctx, target) {
452
+ if (!ctx)
453
+ return;
454
+ const state = readState(projectRoot, ctx);
455
+ if (!state || !state.unresolved.has(tkeyOf(target)))
456
+ return;
457
+ ctx.pending.push({ file: state.file, entries: [`K ${tkeyOf(target)} ${Date.now()}`], said: '' });
458
+ }
459
+ /**
460
+ * The shell's simple commands, quote-aware: single quotes, double quotes and backslash escapes; `;`, `&`, `|`, parentheses
461
+ * and newlines end a command only outside quotes (A-SPEC-333.6).
462
+ */
463
+ function shellCommands(text) {
464
+ const commands = [];
465
+ let words = [];
466
+ let word = '';
467
+ let inWord = false;
468
+ const endWord = () => { if (inWord)
469
+ words.push(word); word = ''; inWord = false; };
470
+ const endCommand = () => { endWord(); if (words.length > 0)
471
+ commands.push(words); words = []; };
472
+ for (let i = 0; i < text.length; i++) {
473
+ const ch = text[i];
474
+ if (ch === "'") {
475
+ const close = text.indexOf("'", i + 1);
476
+ const end = close < 0 ? text.length : close;
477
+ word += text.slice(i + 1, end);
478
+ inWord = true;
479
+ i = end;
480
+ }
481
+ else if (ch === '"') {
482
+ let j = i + 1;
483
+ for (; j < text.length && text[j] !== '"'; j++) {
484
+ // A-SPEC-333.8 — a backslash before a newline is removed with it, inside double quotes as outside
485
+ if (text[j] === '\\' && text[j + 1] === '\n')
486
+ j++;
487
+ else if (text[j] === '\\' && j + 1 < text.length) {
488
+ word += text[j + 1];
489
+ j++;
490
+ }
491
+ else
492
+ word += text[j];
493
+ }
494
+ inWord = true;
495
+ i = j;
496
+ }
497
+ else if (ch === '\\' && text[i + 1] === '\n') {
498
+ i++; // A-SPEC-333.8 — a line continuation joins the two lines, as the shell does
499
+ }
500
+ else if (ch === '\\' && i + 1 < text.length) {
501
+ word += text[i + 1];
502
+ inWord = true;
503
+ i++;
504
+ }
505
+ else if (ch === '\n' || ';&|()'.includes(ch)) {
506
+ endCommand();
507
+ }
508
+ else if (/\s/.test(ch)) {
509
+ endWord();
510
+ }
511
+ else {
512
+ word += ch;
513
+ inWord = true;
514
+ }
515
+ }
516
+ endCommand();
517
+ return commands;
518
+ }
519
+ /**
520
+ * `git commit` as the shell runs it: leading assignments and the prefixes `env` (with its options and assignments),
521
+ * `command`, `time` and `nohup` are skipped; `git` is matched by its basename; git's global options before the subcommand
522
+ * are skipped; `sh|bash|zsh|dash -c <script>` is read again, a few levels deep. `commit-tree`, `HEAD^{commit}`, a quoted
523
+ * mention and `--dry-run` are not a commit (A-SPEC-333.5, 333.6).
524
+ */
525
+ function isGitCommit(command, depth = 0) {
526
+ for (const words of shellCommands(command)) {
527
+ let i = 0;
528
+ const assignment = (w) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(w);
529
+ for (;;) {
530
+ while (i < words.length && assignment(words[i]))
531
+ i++;
532
+ const w = words[i];
533
+ if (w === 'env') {
534
+ i++;
535
+ while (i < words.length && (words[i].startsWith('-') || assignment(words[i])))
536
+ i++;
537
+ continue;
538
+ }
539
+ if (w === 'command' || w === 'time' || w === 'nohup') {
540
+ i++;
541
+ while (i < words.length && words[i].startsWith('-'))
542
+ i++;
543
+ continue;
544
+ }
545
+ break;
546
+ }
547
+ const program = path.basename(words[i] ?? '');
548
+ if (['sh', 'bash', 'zsh', 'dash'].includes(program)) {
549
+ const flag = words.findIndex((x, j) => j > i && /^-[A-Za-z]*c[A-Za-z]*$/.test(x));
550
+ if (flag > 0 && depth < 3 && isGitCommit(words[flag + 1] ?? '', depth + 1))
551
+ return true;
552
+ continue;
553
+ }
554
+ if (program !== 'git')
555
+ continue;
556
+ i++;
557
+ while (i < words.length && words[i].startsWith('-')) {
558
+ i += /^(-C|-c|--git-dir|--work-tree|--namespace|--exec-path)$/.test(words[i]) ? 2 : 1;
559
+ }
560
+ if (words[i] === 'commit' && !words.slice(i + 1).includes('--dry-run'))
561
+ return true;
562
+ }
563
+ return false;
564
+ }
565
+ /**
566
+ * One line for an allowed `git commit`, at most once per epoch: up to three files whose last judgement in the epoch was a
567
+ * refuse verdict, and how many more. Its own record waits in `ctx.pending` like a warning's.
568
+ */
569
+ function commitReminder(projectRoot, ctx) {
570
+ if (!ctx)
571
+ return null;
572
+ const state = readState(projectRoot, ctx);
573
+ if (!state || state.reminded || state.unresolved.size === 0)
574
+ return null;
575
+ const names = [...state.unresolved.values()];
576
+ const more = names.length > REMINDER_NAMES ? ` (+${names.length - REMINDER_NAMES} more)` : '';
577
+ const line = `[Holmes-Kit] before this commit, still warned: ${names.slice(0, REMINDER_NAMES).join(', ')}${more} — run maintenance_analyze for them`;
578
+ // A-SPEC-333.9 — the reminder's characters count toward occupancy, so a said reminder is a ledger row too
579
+ ctx.pending.push({ file: state.file, entries: ['R'], said: line, ledger: { ts: new Date().toISOString(), project: hex32(path.resolve(projectRoot)).slice(0, 16),
580
+ agent: ctx.agent ?? '', tool_use_id: ctx.toolUseId ?? '', target: '', codes: [], verdict: '', kind: 'reminder', epoch: state.epoch, k_index: state.count,
581
+ wording_version: exports.WORDING_VERSION, said_chars: line.length, full_chars: 0, harness: ctx.harness ?? '', compress: ctx.compress } });
582
+ return line;
583
+ }
584
+ /** After the final decision: record what an allow actually carried. A deny, or a record whose text is absent, records nothing. */
585
+ function commitAdvisory(projectRoot, ctx, out) {
586
+ if (!ctx || out.permissionDecision !== 'allow')
587
+ return;
588
+ const reason = out.permissionDecisionReason ?? '';
589
+ for (const rec of ctx.pending.splice(0)) {
590
+ if (rec.said !== '' && !reason.includes(rec.said))
591
+ continue;
592
+ try {
593
+ if (rec.file !== '' && rec.entries.length > 0)
594
+ appendTable(projectRoot, ctx, rec);
595
+ }
596
+ catch { /* an unrecorded sighting is said again */ }
597
+ try {
598
+ if (rec.ledger)
599
+ appendLedger(projectRoot, ctx, `${JSON.stringify(rec.ledger)}\n`);
600
+ }
601
+ catch { /* the ledger never blocks the gate */ }
602
+ }
603
+ }
604
+ function appendTable(projectRoot, ctx, rec) {
605
+ const d = path.dirname(rec.file);
606
+ if (storeDir(projectRoot, ctx.session, ctx.dir) !== d || !trustedDir(d, ctx.dir))
607
+ return;
608
+ const add = rec.entries.map((e) => `${e}\n`).join('');
609
+ let size = 0;
610
+ try {
611
+ const st = fs.lstatSync(rec.file);
612
+ if (!st.isFile())
613
+ return;
614
+ size = st.size;
615
+ }
616
+ catch (e) {
617
+ if (e.code !== 'ENOENT')
618
+ return;
619
+ }
620
+ if (size + add.length > STORE_MAX_BYTES)
621
+ evict(rec.file, add);
622
+ else
623
+ appendTo(rec.file, add);
624
+ }
625
+ function appendTo(file, text) {
626
+ // O_NONBLOCK: a FIFO put in the file's place between the lstat and this open fails here instead of holding the hook
627
+ const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 0o600);
628
+ try {
629
+ fs.writeSync(fd, text);
630
+ }
631
+ finally {
632
+ fs.closeSync(fd);
633
+ }
634
+ }
635
+ /**
636
+ * The judgement ledger: `<base>/ledger/<session>.jsonl`, outside every epoch directory, so compactions never erase it.
637
+ * Rotated at 1MB to a name no other writer takes (time and process id).
638
+ */
639
+ function appendLedger(projectRoot, ctx, row) {
640
+ if (!ctx.session)
641
+ return;
642
+ const ld = path.join(baseDir(ctx.dir), 'ledger');
643
+ if (insideProject(ld, projectRoot))
644
+ return;
645
+ fs.mkdirSync(ld, { recursive: true, mode: 0o700 });
646
+ if (!trustedDir(ld, ctx.dir))
647
+ return;
648
+ const name = hex32(ctx.session).slice(0, 16);
649
+ const file = path.join(ld, `${name}.jsonl`);
650
+ try {
651
+ const st = fs.lstatSync(file);
652
+ if (!st.isFile())
653
+ return;
654
+ if (st.size + row.length > LEDGER_MAX_BYTES) {
655
+ fs.renameSync(file, path.join(ld, `${name}.${Date.now()}.${process.pid}.jsonl`));
656
+ // A-SPEC-333.6 — at most LEDGER_ROTATED_MAX rotated files per session: the oldest goes
657
+ const rotated = fs.readdirSync(ld).filter((n) => n.startsWith(`${name}.`) && /^\w+\.\d+\.\d+\.jsonl$/.test(n))
658
+ .sort((x, y) => Number(x.split('.')[1]) - Number(y.split('.')[1]));
659
+ for (const old of rotated.slice(0, Math.max(0, rotated.length - LEDGER_ROTATED_MAX)))
660
+ fs.unlinkSync(path.join(ld, old));
661
+ }
662
+ }
663
+ catch (e) {
664
+ if (e.code !== 'ENOENT')
665
+ return;
666
+ }
667
+ appendTo(file, row);
668
+ }
669
+ /** Keep the count, the explained codes, the reminder mark, open warnings, streaks and the newer half of the lines. */
670
+ function evict(file, add) {
671
+ const text = readRegular(file);
672
+ if (text === null)
673
+ return;
674
+ let count = 0;
675
+ let reminded = false;
676
+ const explained = new Set();
677
+ const lines = new Map();
678
+ const streaks = new Map();
679
+ const standing = new Map();
680
+ const contract = new Map();
681
+ // A-SPEC-333.6 — a Map re-inserted on every sighting keeps the latest judgement last, so "newer half" means recent
682
+ const touch = (m, k, v) => { m.delete(k); m.set(k, v); };
683
+ for (const row of (text + add).split('\n')) {
684
+ const [kind, a, b] = row.split(' ');
685
+ if (kind === 'C')
686
+ count += Number(a) || 0;
687
+ else if (kind === 'V')
688
+ count++;
689
+ else if (kind === 'E' && a)
690
+ explained.add(a);
691
+ else if (kind === 'L' && a)
692
+ touch(lines, a, row);
693
+ else if (kind === 'J' && a)
694
+ touch(streaks, a, b === 's' ? (streaks.get(a) ?? 0) + 1 : 0);
695
+ else if (kind === 'S' && a)
696
+ touch(streaks, a, Number(b) || 0);
697
+ else if ((kind === 'W' || kind === 'K') && a)
698
+ touch(standing, a, row);
699
+ else if (kind === 'R')
700
+ reminded = true;
701
+ else if (kind === 'P' && a)
702
+ touch(contract, a, row);
703
+ }
704
+ const recent = [...lines.values()];
705
+ // the reminder names three; the newest 50 W/K rows keep the file bounded however many files were warned
706
+ const kept = [`C ${count}`, ...(reminded ? ['R'] : []), ...[...explained].map((c) => `E ${c}`), ...[...standing.values()].slice(-50),
707
+ ...[...contract.values()].slice(-50),
708
+ ...[...streaks].filter(([, n]) => n > 0).slice(-50).map(([k, n]) => `S ${k} ${n}`), ...recent.slice(Math.floor(recent.length / 2))].join('\n') + '\n';
709
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
710
+ const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
711
+ try {
712
+ fs.writeSync(fd, kept);
713
+ }
714
+ finally {
715
+ fs.closeSync(fd);
716
+ }
717
+ fs.renameSync(tmp, file);
718
+ }