@holmes-lab/holmes-kit 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/CHANGELOG.md +370 -6
  2. package/README.md +58 -40
  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 +50 -13
  47. package/dist/holmes/cli/approve.js +260 -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 +45 -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 +206 -424
  65. package/dist/holmes/cli/init.js +33 -0
  66. package/dist/holmes/cli/lock-recover.d.ts +5 -0
  67. package/dist/holmes/cli/lock-recover.js +126 -0
  68. package/dist/holmes/cli/mcp-processes.d.ts +32 -0
  69. package/dist/holmes/cli/mcp-processes.js +132 -0
  70. package/dist/holmes/cli/release-docs.js +1 -1
  71. package/dist/holmes/cli/run-exec.d.ts +141 -0
  72. package/dist/holmes/cli/run-exec.js +1435 -0
  73. package/dist/holmes/cli/run-provision.d.ts +8 -0
  74. package/dist/holmes/cli/run-provision.js +325 -0
  75. package/dist/holmes/cli/run-wiring.d.ts +69 -0
  76. package/dist/holmes/cli/run-wiring.js +270 -0
  77. package/dist/holmes/cli/run.d.ts +26 -0
  78. package/dist/holmes/cli/run.js +364 -83
  79. package/dist/holmes/cli/runtime-binding-approval.js +32 -19
  80. package/dist/holmes/cli/screen-safe.d.ts +3 -92
  81. package/dist/holmes/cli/screen-safe.js +18 -756
  82. package/dist/holmes/config/config.d.ts +2 -0
  83. package/dist/holmes/config/config.js +5 -2
  84. package/dist/holmes/cpg/foundation/language-matrix.js +2 -2
  85. package/dist/holmes/cpg/import-resolver.js +1 -1
  86. package/dist/holmes/governance/approval-decisions.d.ts +47 -0
  87. package/dist/holmes/governance/approval-decisions.js +29 -0
  88. package/dist/holmes/governance/approval-grants.d.ts +220 -1
  89. package/dist/holmes/governance/approval-grants.js +612 -33
  90. package/dist/holmes/governance/approval-queue.d.ts +31 -0
  91. package/dist/holmes/governance/approval-queue.js +122 -11
  92. package/dist/holmes/governance/approval-spend.d.ts +95 -0
  93. package/dist/holmes/governance/approval-spend.js +191 -0
  94. package/dist/holmes/governance/autonomous-shell.d.ts +61 -0
  95. package/dist/holmes/governance/autonomous-shell.js +332 -0
  96. package/dist/holmes/governance/autonomy.d.ts +5 -0
  97. package/dist/holmes/governance/autonomy.js +16 -11
  98. package/dist/holmes/governance/constitution.d.ts +5 -0
  99. package/dist/holmes/governance/constitution.js +32 -12
  100. package/dist/holmes/governance/full-autonomy.d.ts +10 -0
  101. package/dist/holmes/governance/full-autonomy.js +103 -7
  102. package/dist/holmes/governance/harness-catalog.d.ts +103 -0
  103. package/dist/holmes/governance/harness-catalog.js +348 -0
  104. package/dist/holmes/governance/human-channel.d.ts +38 -0
  105. package/dist/holmes/governance/human-channel.js +49 -0
  106. package/dist/holmes/governance/install-manifest.d.ts +22 -0
  107. package/dist/holmes/governance/install-manifest.js +160 -0
  108. package/dist/holmes/governance/ledger-rechain.js +2 -0
  109. package/dist/holmes/governance/ledger-store.conformance.d.ts +7 -1
  110. package/dist/holmes/governance/ledger-store.conformance.js +66 -0
  111. package/dist/holmes/governance/ledger-store.d.ts +88 -11
  112. package/dist/holmes/governance/ledger-store.js +186 -8
  113. package/dist/holmes/governance/provenance-chain.d.ts +16 -4
  114. package/dist/holmes/governance/provenance-chain.js +19 -4
  115. package/dist/holmes/governance/provenance-ledger.d.ts +6 -3
  116. package/dist/holmes/governance/provenance-ledger.js +53 -18
  117. package/dist/holmes/governance/push-gate-runner.js +11 -7
  118. package/dist/holmes/governance/recorded-pairs.d.ts +96 -0
  119. package/dist/holmes/governance/recorded-pairs.js +522 -0
  120. package/dist/holmes/governance/replica-id.d.ts +1 -1
  121. package/dist/holmes/governance/replica-id.js +1 -1
  122. package/dist/holmes/governance/spec-seam.d.ts +59 -0
  123. package/dist/holmes/governance/spec-seam.js +587 -0
  124. package/dist/holmes/governance/spend-kinds.d.ts +16 -0
  125. package/dist/holmes/governance/spend-kinds.js +18 -0
  126. package/dist/holmes/governance/tool-actions.js +2 -0
  127. package/dist/holmes/guardrail/decision-ledger.d.ts +2 -1
  128. package/dist/holmes/guardrail/decision-ledger.js +2 -1
  129. package/dist/holmes/guardrail/impact-gate.d.ts +1 -0
  130. package/dist/holmes/guardrail/impact-gate.js +1 -1
  131. package/dist/holmes/guardrail/line-continuation.d.ts +8 -0
  132. package/dist/holmes/guardrail/line-continuation.js +39 -0
  133. package/dist/holmes/guardrail/operator-person.d.ts +28 -4
  134. package/dist/holmes/guardrail/operator-person.js +57 -11
  135. package/dist/holmes/guardrail/refusal-codes.d.ts +8 -3
  136. package/dist/holmes/guardrail/refusal-codes.js +70 -10
  137. package/dist/holmes/guardrail/risk-classifier.d.ts +15 -9
  138. package/dist/holmes/guardrail/risk-classifier.js +245 -15
  139. package/dist/holmes/guardrail/risk-gate.d.ts +2 -8
  140. package/dist/holmes/guardrail/risk-gate.js +7 -34
  141. package/dist/holmes/guardrail/risk-types.d.ts +10 -0
  142. package/dist/holmes/guardrail/run-plan-scope.js +3 -1
  143. package/dist/holmes/guardrail/run-refusals.d.ts +6 -1
  144. package/dist/holmes/guardrail/run-refusals.js +36 -14
  145. package/dist/holmes/guardrail/run-stages.d.ts +10 -0
  146. package/dist/holmes/guardrail/run-stages.js +46 -6
  147. package/dist/holmes/guardrail/scope-judgment.js +1 -1
  148. package/dist/holmes/guardrail/shell-words.js +24 -3
  149. package/dist/holmes/guardrail/unresolved-write.d.ts +40 -0
  150. package/dist/holmes/guardrail/unresolved-write.js +556 -0
  151. package/dist/holmes/guardrail/write-target.d.ts +3 -0
  152. package/dist/holmes/guardrail/write-target.js +26 -5
  153. package/dist/holmes/hooks/pre-tool-use.d.ts +105 -1
  154. package/dist/holmes/hooks/pre-tool-use.js +1167 -168
  155. package/dist/holmes/hooks/rtm-refresh-child.d.ts +1 -1
  156. package/dist/holmes/hooks/rtm-refresh-child.js +1 -1
  157. package/dist/holmes/hooks/session-start.d.ts +5 -0
  158. package/dist/holmes/hooks/session-start.js +29 -1
  159. package/dist/holmes/hooks/stop.d.ts +23 -0
  160. package/dist/holmes/hooks/stop.js +88 -33
  161. package/dist/holmes/mcp/approval-adapters.js +3 -1
  162. package/dist/holmes/mcp/approval-commit.js +3 -2
  163. package/dist/holmes/mcp/approval-policy.d.ts +2 -1
  164. package/dist/holmes/mcp/approval-policy.js +3 -1
  165. package/dist/holmes/mcp/handlers/adoption.d.ts +1 -1
  166. package/dist/holmes/mcp/handlers/approval-ask.d.ts +14 -0
  167. package/dist/holmes/mcp/handlers/approval-ask.js +31 -6
  168. package/dist/holmes/mcp/handlers/entity-integration.d.ts +3 -3
  169. package/dist/holmes/mcp/handlers/entity-integration.js +29 -11
  170. package/dist/holmes/mcp/handlers/entity-renumber.d.ts +4 -4
  171. package/dist/holmes/mcp/handlers/entity-renumber.js +29 -11
  172. package/dist/holmes/mcp/handlers/entity-store.d.ts +2 -2
  173. package/dist/holmes/mcp/handlers/entity-store.js +133 -59
  174. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +9 -5
  175. package/dist/holmes/mcp/handlers/operator-inspection.js +79 -16
  176. package/dist/holmes/mcp/handlers/phase-queries.d.ts +1 -1
  177. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +4 -4
  178. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -2
  179. package/dist/holmes/mcp/handlers/review-evidence.js +35 -11
  180. package/dist/holmes/mcp/handlers/review-queries.d.ts +5 -0
  181. package/dist/holmes/mcp/handlers/review-queries.js +8 -1
  182. package/dist/holmes/mcp/handlers/review-verdict.d.ts +3 -0
  183. package/dist/holmes/mcp/handlers/review-verdict.js +10 -3
  184. package/dist/holmes/mcp/handlers/risk-assessment.d.ts +7 -2
  185. package/dist/holmes/mcp/handlers/risk-assessment.js +34 -12
  186. package/dist/holmes/mcp/handlers/runtime-binding-tool.d.ts +2 -2
  187. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +6 -1
  188. package/dist/holmes/mcp/handlers/slice-orchestration.js +14 -1
  189. package/dist/holmes/mcp/handlers/spec-approval.d.ts +15 -3
  190. package/dist/holmes/mcp/handlers/spec-approval.js +32 -5
  191. package/dist/holmes/mcp/handlers/spec-authoring.d.ts +2 -2
  192. package/dist/holmes/mcp/handlers/spec-authoring.js +19 -2
  193. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +11 -38
  194. package/dist/holmes/mcp/handlers/spec-lifecycle.js +441 -94
  195. package/dist/holmes/mcp/handlers/spec-queries.d.ts +2 -2
  196. package/dist/holmes/mcp/handlers/taint-screening.d.ts +1 -1
  197. package/dist/holmes/mcp/handlers/taint-screening.js +2 -2
  198. package/dist/holmes/mcp/handlers/test-execution.d.ts +1 -1
  199. package/dist/holmes/mcp/handlers/workspace-preflight.d.ts +5 -0
  200. package/dist/holmes/mcp/handlers/workspace-preflight.js +10 -2
  201. package/dist/holmes/mcp/handlers/workspace-queries.d.ts +2 -2
  202. package/dist/holmes/mcp/handlers.d.ts +99 -79
  203. package/dist/holmes/mcp/handlers.js +93 -25
  204. package/dist/holmes/mcp/harness-attestation.d.ts +78 -5
  205. package/dist/holmes/mcp/harness-attestation.js +325 -53
  206. package/dist/holmes/mcp/maintenance-analyze.d.ts +1 -1
  207. package/dist/holmes/mcp/maintenance-analyze.js +9 -9
  208. package/dist/holmes/mcp/maintenance-evidence.js +31 -2
  209. package/dist/holmes/mcp/requirement-triage-evidence.js +22 -13
  210. package/dist/holmes/mcp/server-staleness.d.ts +43 -0
  211. package/dist/holmes/mcp/server-staleness.js +158 -0
  212. package/dist/holmes/mcp/server.js +34 -9
  213. package/dist/holmes/mcp/spec-id-guard.js +1 -1
  214. package/dist/holmes/mcp/tool-schemas.d.ts +13 -0
  215. package/dist/holmes/mcp/tool-schemas.js +42 -2
  216. package/dist/holmes/project/act-root.d.ts +19 -0
  217. package/dist/holmes/project/act-root.js +100 -0
  218. package/dist/holmes/project/baseline.js +4 -3
  219. package/dist/holmes/project/bounded-group.d.ts +47 -0
  220. package/dist/holmes/project/bounded-group.js +140 -0
  221. package/dist/holmes/project/bounded-io.d.ts +50 -2
  222. package/dist/holmes/project/bounded-io.js +138 -6
  223. package/dist/holmes/project/change-source.js +2 -2
  224. package/dist/holmes/project/instance-id.d.ts +10 -0
  225. package/dist/holmes/project/instance-id.js +233 -0
  226. package/dist/holmes/project/machine-identity.d.ts +25 -0
  227. package/dist/holmes/project/machine-identity.js +133 -0
  228. package/dist/holmes/project/owned-lock.d.ts +84 -0
  229. package/dist/holmes/project/owned-lock.js +263 -0
  230. package/dist/holmes/project/plain-lock-fs.d.ts +2 -0
  231. package/dist/holmes/project/plain-lock-fs.js +126 -0
  232. package/dist/holmes/project/request-lock.d.ts +85 -0
  233. package/dist/holmes/project/request-lock.js +459 -0
  234. package/dist/holmes/project/root.d.ts +12 -4
  235. package/dist/holmes/project/root.js +26 -7
  236. package/dist/holmes/project/run-records.d.ts +19 -0
  237. package/dist/holmes/project/run-records.js +94 -12
  238. package/dist/holmes/project/screen-text.d.ts +94 -0
  239. package/dist/holmes/project/screen-text.js +763 -0
  240. package/dist/holmes/project/spend-lock.d.ts +82 -0
  241. package/dist/holmes/project/spend-lock.js +413 -0
  242. package/dist/holmes/project/workspace-preflight.d.ts +5 -0
  243. package/dist/holmes/project/workspace-preflight.js +24 -1
  244. package/dist/holmes/refresh/freshness-coordinator.d.ts +1 -1
  245. package/dist/holmes/refresh/freshness-coordinator.js +1 -1
  246. package/dist/holmes/review/condition-hunk-replay.js +4 -2
  247. package/dist/holmes/review/confidence-calibration.d.ts +1 -1
  248. package/dist/holmes/review/confidence-calibration.js +1 -1
  249. package/dist/holmes/review/content-verify.js +1 -1
  250. package/dist/holmes/review/hop-ablation.d.ts +4 -4
  251. package/dist/holmes/review/hop-ablation.js +5 -5
  252. package/dist/holmes/review/point-in-time-replay.js +12 -3
  253. package/dist/holmes/review/rank-diagnosis.d.ts +2 -2
  254. package/dist/holmes/review/rank-diagnosis.js +1 -1
  255. package/dist/holmes/review/replay-corpus.d.ts +10 -4
  256. package/dist/holmes/review/replay-corpus.js +25 -9
  257. package/dist/holmes/review/requirement-triage.js +2 -2
  258. package/dist/holmes/review/semantic-arm.d.ts +3 -3
  259. package/dist/holmes/review/semantic-arm.js +3 -3
  260. package/dist/holmes/review/test-outcomes.js +3 -1
  261. package/dist/holmes/review/test-runner.d.ts +11 -0
  262. package/dist/holmes/review/test-runner.js +31 -10
  263. package/dist/holmes/review/test-selection-breadth.js +2 -2
  264. package/dist/holmes/review/verdicts.d.ts +109 -7
  265. package/dist/holmes/review/verdicts.js +653 -34
  266. package/dist/holmes/rtm/anchor-census.d.ts +9 -0
  267. package/dist/holmes/rtm/anchor-census.js +151 -0
  268. package/dist/holmes/rtm/anchor-ids.d.ts +25 -1
  269. package/dist/holmes/rtm/anchor-ids.js +45 -2
  270. package/dist/holmes/rtm/comment-ranges.d.ts +2 -0
  271. package/dist/holmes/rtm/comment-ranges.js +104 -0
  272. package/dist/holmes/rtm/counted-tests.d.ts +1 -0
  273. package/dist/holmes/rtm/counted-tests.js +63 -0
  274. package/dist/holmes/rtm/impact-advisory.d.ts +1 -1
  275. package/dist/holmes/rtm/known-defects.js +1 -1
  276. package/dist/holmes/rtm/localize.js +1 -1
  277. package/dist/holmes/rtm/taint-benchmark.d.ts +1 -1
  278. package/dist/holmes/rtm/taint-vocabulary.d.ts +1 -1
  279. package/dist/holmes/rtm/test-scope.d.ts +31 -0
  280. package/dist/holmes/rtm/test-scope.js +166 -5
  281. package/dist/holmes/rtm/trace-gaps.js +1 -1
  282. package/dist/holmes/runtime/dispatch.d.ts +10 -0
  283. package/dist/holmes/runtime/dispatch.js +12 -1
  284. package/dist/holmes/semantic/cloud-usage.d.ts +1 -1
  285. package/dist/holmes/semantic/cloud-usage.js +1 -1
  286. package/dist/holmes/semantic/unreadable-paths.d.ts +1 -1
  287. package/dist/holmes/semantic/unreadable-paths.js +1 -1
  288. package/dist/holmes/spec/approval-blockers.js +1 -1
  289. package/dist/holmes/spec/entity-store.d.ts +6 -1
  290. package/dist/holmes/spec/entity-store.js +16 -2
  291. package/dist/holmes/spec/entity-transaction.d.ts +7 -2
  292. package/dist/holmes/spec/entity-transaction.js +87 -170
  293. package/dist/holmes/spec/spec-store.d.ts +12 -6
  294. package/dist/holmes/spec/spec-store.js +4 -2
  295. package/dist/holmes/spec/spec-types.js +1 -1
  296. package/dist/holmes/spec/succession-guard.d.ts +56 -0
  297. package/dist/holmes/spec/succession-guard.js +187 -0
  298. package/dist/holmes/spec/succession.d.ts +70 -0
  299. package/dist/holmes/spec/succession.js +171 -0
  300. package/dist/holmes/spec/transition-policy.d.ts +2 -2
  301. package/docs/install-guide.md +9 -3
  302. package/docs/language-support.md +78 -0
  303. package/package.json +4 -3
  304. package/playbooks/author-slice/PLAYBOOK.md +1 -1
  305. package/playbooks/promote-slice/PLAYBOOK.md +5 -1
  306. package/playbooks/publish/PLAYBOOK.md +45 -33
  307. package/dist/holmes/review/manual-baseline.d.ts +0 -209
  308. package/dist/holmes/review/manual-baseline.js +0 -2847
@@ -51,11 +51,12 @@ exports.settleEntityTransients = settleEntityTransients;
51
51
  exports.applyEntityByteChange = applyEntityByteChange;
52
52
  exports.isTransientWindowsFsError = isTransientWindowsFsError;
53
53
  exports.renameWithTransientRetry = renameWithTransientRetry;
54
+ exports.toEntityStoreError = toEntityStoreError;
54
55
  exports.withEntityStoreLock = withEntityStoreLock;
55
56
  exports.withEntityStoreLockAsync = withEntityStoreLockAsync;
56
57
  exports.entityLockHolderAlive = entityLockHolderAlive;
57
58
  exports.withEntityRecoveryLock = withEntityRecoveryLock;
58
- // @implements A-SPEC-629, A-SPEC-627
59
+ // @implements A-SPEC-629, A-SPEC-627, A-SPEC-245.8, A-SPEC-245.10, A-SPEC-245.11
59
60
  // @implements A-SPEC-640
60
61
  // @implements A-SPEC-639
61
62
  // @implements A-SPEC-638
@@ -64,6 +65,8 @@ exports.withEntityRecoveryLock = withEntityRecoveryLock;
64
65
  const fs = __importStar(require("node:fs"));
65
66
  const path = __importStar(require("node:path"));
66
67
  const node_crypto_1 = require("node:crypto");
68
+ const owned_lock_1 = require("../project/owned-lock");
69
+ Object.defineProperty(exports, "LOCK_STAGING_STALE_MS", { enumerable: true, get: function () { return owned_lock_1.LOCK_STAGING_STALE_MS; } });
67
70
  class EntityStoreError extends Error {
68
71
  code;
69
72
  holmesRefusal = true;
@@ -496,97 +499,84 @@ function renameWithTransientRetry(from, to, deps = {}) {
496
499
  }
497
500
  }
498
501
  }
499
- function retireOwnedLock(root, dir, expected, owned) {
500
- const current = entityStat(dir);
501
- if (current?.dev !== expected.dev || current?.ino !== expected.ino)
502
- throw new EntityStoreError('unknown-owner', 'Lock directory changed before retirement.');
503
- for (const name of fs.readdirSync(dir))
504
- if (!owned.has(path.join(dir, name)))
505
- throw new EntityStoreError('cleanup-conflict', 'Unknown lock contents must be preserved.');
506
- const retired = entityDirectory(root, '.ax/state/entity-retired-locks', true);
507
- const destination = path.join(retired, (0, node_crypto_1.randomUUID)());
508
- if (entityStat(destination))
509
- throw new EntityStoreError('retirement-conflict', 'Lock retirement destination is occupied.');
510
- // Release the active pathname in one step, retaining owner evidence until then.
511
- renameWithTransientRetry(dir, destination);
512
- for (const file of owned)
513
- fs.unlinkSync(path.join(destination, path.basename(file)));
514
- fs.rmdirSync(destination);
502
+ /**
503
+ * @implements A-SPEC-245.8 — the lock protocol lives in owned-lock.ts; its errors become this store's, with the busy
504
+ * message of each site and every other code and message unchanged. Anything that is not a LockError passes through.
505
+ */
506
+ function toEntityStoreError(e) {
507
+ if (!(e instanceof owned_lock_1.LockError))
508
+ return e;
509
+ if (e.code === 'lock-busy') {
510
+ const message = e.site === 'recover-live' ? 'The lock owner is still running; elapsed time does not permit recovery.'
511
+ : e.site === 'recover-claim' ? 'Another recovery owns this generation.'
512
+ : 'Entity store is owned by another or interrupted operation; inspect before recovery.';
513
+ return new EntityStoreError('store-busy', message);
514
+ }
515
+ return new EntityStoreError(e.code, e.message);
516
+ }
517
+ const translated = (f) => { try {
518
+ return f();
519
+ }
520
+ catch (e) {
521
+ throw toEntityStoreError(e);
522
+ } };
523
+ /** The entity store's guarded primitives, handed to the lock protocol. */
524
+ function entityLockFs(root) {
525
+ return {
526
+ stat: entityStat,
527
+ directory: (relative, create) => entityDirectory(root, relative, create),
528
+ readBytes: readEntityBytes,
529
+ publish: (relative, bytes) => publishEntityRecord(root, relative, bytes),
530
+ rename: (from, to) => renameWithTransientRetry(from, to),
531
+ replace: (relative, before, after) => applyEntityByteChange(root, { locator: relative, before: Buffer.from(before).toString('base64'), after: Buffer.from(after).toString('base64') }),
532
+ // @implements A-SPEC-245.10 — every file operation of the protocol through this port, each as the entity lock did it
533
+ // @implements A-SPEC-245.11 — the staging rename is one plain rename again (no transient retry on Windows)
534
+ renameNew: (from, to) => fs.renameSync(from, to),
535
+ appendLine: (file, line) => fs.appendFileSync(file, line + '\n'),
536
+ list: (dir) => fs.readdirSync(dir),
537
+ makeDir: (dir) => fs.mkdirSync(dir),
538
+ writeNew: (file, bytes) => fs.writeFileSync(file, bytes, { flag: 'wx', mode: 0o600 }),
539
+ unlink: (file) => fs.unlinkSync(file),
540
+ removeDir: (dir) => fs.rmdirSync(dir),
541
+ removeTree: (dir) => fs.rmSync(dir, { recursive: true, force: true }),
542
+ isOwnTransient: (name) => /^\.entity-[0-9a-f-]+\.tmp$/.test(name),
543
+ };
544
+ }
545
+ function entityLockLayout(locator) {
546
+ const hash = (0, node_crypto_1.createHash)('sha256').update(locator).digest('hex');
547
+ return { parent: '.ax/state/entity-locks', name: hash, claims: path.join('.ax/state/entity-recovery-claims', hash), retired: '.ax/state/entity-retired-locks' };
548
+ }
549
+ /** The entity policy: today's holder whitelist and locator check; a probe answering anything but ESRCH is unknown-owner. */
550
+ function entityRecoveryPolicy(locator) {
551
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
552
+ return {
553
+ kind: 'entity',
554
+ valid: (r) => {
555
+ const owner = r;
556
+ return !(!owner || !uuid.test(owner.token) || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || owner.storeLocator !== locator
557
+ || Object.keys(owner).some(k => !['token', 'pid', 'storeLocator', 'released'].includes(k)) || (owner.released !== undefined && owner.released !== true));
558
+ },
559
+ judgeDead: (owner) => {
560
+ try {
561
+ process.kill(owner.pid, 0);
562
+ throw new owned_lock_1.LockError('lock-busy', 'recover-live', 'The lock owner is still running; elapsed time does not permit recovery.');
563
+ }
564
+ catch (e) {
565
+ if (e.code !== 'ESRCH')
566
+ throw e instanceof owned_lock_1.LockError ? e : new owned_lock_1.LockError('unknown-owner', 'inspect', 'Cannot establish that the lock owner stopped.');
567
+ }
568
+ },
569
+ claim: () => ({ token: (0, node_crypto_1.randomUUID)(), pid: process.pid, storeLocator: locator }),
570
+ };
515
571
  }
516
572
  /** The shared source-publication coordination namespace, independent of every configured spec store (A-SPEC-634: exported so recovery can release it without importing the renumber module). */
517
573
  exports.SOURCE_PUBLICATION_LOCATOR = '.ax/state/entity-renumber-source-publication';
518
- /** Age after which a `.staging-*` entry beside the locks is treated as abandoned by a publisher that died before its rename (A-SPEC-633). */
519
- exports.LOCK_STAGING_STALE_MS = 10 * 60_000;
520
574
  /** Never steals a live or uncertain hold by age. Crash-owner recovery is a separate act. */
521
575
  function acquireEntityStoreLock(root, locator) {
522
- const locks = entityDirectory(root, path.join('.ax', 'state', 'entity-locks'), true);
523
- const dir = path.join(locks, (0, node_crypto_1.createHash)('sha256').update(locator).digest('hex'));
524
- // @implements A-SPEC-633 — the lock APPEARS atomically. Measured 2026-09-13 with the previous
525
- // mkdir-then-write order: a reader looping entityLockOwner beside a looping writer saw the
526
- // directory before its owner record 17,518 times in four seconds. So the owner record is written
527
- // and fsynced inside a private staging directory, and the staging directory is renamed into the
528
- // lock path: a contender observes no lock or a complete one, and loses the rename with
529
- // EEXIST/ENOTEMPTY (POSIX) or EPERM/EEXIST (Windows) — all "busy", never "unknown owner".
530
- sweepAbandonedStaging(locks);
531
- // An existing directory is busy whatever it holds: rename(2) would silently REPLACE an empty
532
- // one, and an empty lock directory is exactly the legacy/foreign state that must be preserved
533
- // for explicit recovery (a live winner between this check and the rename loses it with
534
- // ENOTEMPTY/EEXIST below).
535
- if (entityStat(dir))
536
- throw new EntityStoreError('store-busy', 'Entity store is owned by another or interrupted operation; inspect before recovery.');
537
- const staging = path.join(locks, '.staging-' + (0, node_crypto_1.randomUUID)()), token = (0, node_crypto_1.randomUUID)();
538
- fs.mkdirSync(staging);
539
- const record = JSON.stringify({ token, pid: process.pid, storeLocator: locator });
540
- try {
541
- // No fsync: the guarantee is atomic VISIBILITY to concurrent processes (the rename), not
542
- // durability across power loss — the previous protocol never synced either, and measured
543
- // 2026-09-13 an fsync per acquisition cut throughput from thousands to ~76 per second, on a
544
- // lock every adopted-store read takes.
545
- fs.writeFileSync(path.join(staging, 'owner.json'), record, { flag: 'wx', mode: 0o600 });
546
- fs.renameSync(staging, dir);
547
- }
548
- catch (e) {
549
- try {
550
- fs.rmSync(staging, { recursive: true, force: true });
551
- }
552
- catch { /* best effort */ }
553
- const code = e.code;
554
- if (code === 'EEXIST' || code === 'ENOTEMPTY' || code === 'EPERM')
555
- throw new EntityStoreError('store-busy', 'Entity store is owned by another or interrupted operation; inspect before recovery.');
556
- throw e;
557
- }
558
- const ownership = fs.lstatSync(dir);
559
- const release = () => {
560
- const current = entityStat(dir);
561
- if (current?.dev === ownership.dev && current?.ino === ownership.ino) {
562
- const ownerFile = path.join(dir, 'owner.json');
563
- const owner = readEntityBytes(ownerFile);
564
- if (owner && JSON.parse(owner.toString('utf8')).token === token) {
565
- retireOwnedLock(root, dir, ownership, new Set([ownerFile]));
566
- }
567
- }
568
- };
569
- return release;
570
- }
571
- /** Remove `.staging-*` entries older than the bound: a publisher that died before its rename. Younger entries may belong to a live acquirer; hashed lock directories are never touched. */
572
- function sweepAbandonedStaging(locks) {
573
- let names;
574
- try {
575
- names = fs.readdirSync(locks);
576
- }
577
- catch {
578
- return;
579
- }
580
- for (const name of names) {
581
- if (!name.startsWith('.staging-'))
582
- continue;
583
- const entry = path.join(locks, name);
584
- try {
585
- if (Date.now() - fs.lstatSync(entry).mtimeMs > exports.LOCK_STAGING_STALE_MS)
586
- fs.rmSync(entry, { recursive: true, force: true });
587
- }
588
- catch { /* raced with its owner or already gone */ }
589
- }
576
+ // @implements A-SPEC-633 — the lock APPEARS atomically (owned-lock.ts: a staged owner record renamed into place).
577
+ // The holder record is unchanged, and no machine identity is read on this path.
578
+ const release = translated(() => (0, owned_lock_1.acquireOwnedLock)(entityLockFs(root), entityLockLayout(locator), { token: (0, node_crypto_1.randomUUID)(), pid: process.pid, storeLocator: locator }));
579
+ return () => translated(release);
590
580
  }
591
581
  function withEntityStoreLock(root, locator, act) {
592
582
  const release = acquireEntityStoreLock(root, locator);
@@ -654,88 +644,15 @@ function entityLockHolderAlive(root, locator) {
654
644
  }
655
645
  /** Claim a dead owner's immutable generation without deleting or replacing its lock. */
656
646
  function withEntityRecoveryLock(root, locator, act) {
657
- const relative = path.join('.ax/state/entity-locks', (0, node_crypto_1.createHash)('sha256').update(locator).digest('hex'));
658
- const dir = entityDirectory(root, relative);
659
- if (!entityStat(dir))
660
- return withEntityStoreLock(root, locator, act);
661
- const directory = fs.lstatSync(dir), records = [], tokens = new Set();
662
- let file = path.join(dir, 'owner.json');
663
- const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
664
- for (let depth = 0; depth < 128; depth++) {
665
- const bytes = readEntityBytes(file);
666
- let owner;
667
- try {
668
- owner = JSON.parse(bytes?.toString('utf8') ?? 'null');
669
- }
670
- catch {
671
- throw new EntityStoreError('unknown-owner', 'Malformed lock ownership must be preserved.');
672
- }
673
- if (!owner || !uuid.test(owner.token) || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || owner.storeLocator !== locator || Object.keys(owner).some(k => !['token', 'pid', 'storeLocator', 'released'].includes(k)) || (owner.released !== undefined && owner.released !== true) || (records.length === 0 && owner.released) || tokens.has(owner.token))
674
- throw new EntityStoreError('unknown-owner', 'Invalid or cyclic lock ownership must be preserved.');
675
- tokens.add(owner.token);
676
- records.push(file);
677
- if (!owner.released) {
678
- try {
679
- process.kill(owner.pid, 0);
680
- throw new EntityStoreError('store-busy', 'The lock owner is still running; elapsed time does not permit recovery.');
681
- }
682
- catch (e) {
683
- if (e.code !== 'ESRCH')
684
- throw e instanceof EntityStoreError ? e : new EntityStoreError('unknown-owner', 'Cannot establish that the lock owner stopped.');
685
- }
686
- }
687
- const legacySuccessor = path.join(dir, 'successor-' + owner.token + '.json');
688
- const claims = entityDirectory(root, path.join('.ax/state/entity-recovery-claims', (0, node_crypto_1.createHash)('sha256').update(locator).digest('hex')), true);
689
- const externalSuccessor = path.join(claims, 'successor-' + owner.token + '.json');
690
- if (entityStat(legacySuccessor) && entityStat(externalSuccessor))
691
- throw new EntityStoreError('unknown-owner', 'Conflicting ownership generations must be preserved.');
692
- const successor = entityStat(legacySuccessor) ? legacySuccessor : externalSuccessor;
693
- if (entityStat(successor)) {
694
- file = successor;
695
- continue;
696
- }
697
- const claim = { token: (0, node_crypto_1.randomUUID)(), pid: process.pid, storeLocator: locator };
698
- try {
699
- publishEntityRecord(root, path.relative(root, successor), JSON.stringify(claim));
700
- }
701
- catch (e) {
702
- if (e.code === 'EEXIST')
703
- throw new EntityStoreError('store-busy', 'Another recovery owns this generation.');
704
- throw e;
705
- }
706
- records.push(successor);
707
- try {
708
- const current = entityStat(dir);
709
- if (current?.dev !== directory.dev || current?.ino !== directory.ino)
710
- throw new EntityStoreError('unknown-owner', 'Lock directory changed during recovery claim.');
711
- // Only known generation files and their same-inode publication hardlinks belong to us.
712
- // External generation claims survive retirement so delayed contenders cannot
713
- // claim an old token against a newer directory at the reused active path.
714
- const localRecords = records.filter(r => path.dirname(r) === dir);
715
- const owned = new Set(localRecords);
716
- const inodes = localRecords.map(r => fs.lstatSync(r));
717
- for (const name of fs.readdirSync(dir)) {
718
- const candidate = path.join(dir, name);
719
- if (owned.has(candidate))
720
- continue;
721
- const s = fs.lstatSync(candidate);
722
- if (/^\.entity-[0-9a-f-]+\.tmp$/.test(name) && s.isFile() && !s.isSymbolicLink() && inodes.some(i => i.dev === s.dev && i.ino === s.ino))
723
- owned.add(candidate);
724
- else
725
- throw new EntityStoreError('cleanup-conflict', 'Unknown lock contents are preserved for inspection.');
726
- }
727
- const result = act();
728
- retireOwnedLock(root, dir, directory, owned);
729
- return result;
730
- }
731
- catch (e) {
732
- // A failed live recovery must not strand its PID as an active owner forever.
733
- // Mark only our generation released; another claimant appends a new generation.
734
- const bytes = readEntityBytes(successor);
735
- if (bytes?.toString('utf8') === JSON.stringify(claim))
736
- applyEntityByteChange(root, { locator: path.relative(root, successor), before: bytes.toString('base64'), after: Buffer.from(JSON.stringify({ ...claim, released: true })).toString('base64') });
737
- throw e;
738
- }
647
+ // @implements A-SPEC-245.8 — the recovery protocol is owned-lock.ts's, under the entity policy; recovery stays this
648
+ // separate act, never automatic
649
+ try {
650
+ return (0, owned_lock_1.recoverOwnedLock)(entityLockFs(root), entityLockLayout(locator), entityRecoveryPolicy(locator), act, () => acquireEntityStoreLock(root, locator));
651
+ }
652
+ catch (e) {
653
+ // A-SPEC-245.10 — only the protocol's own errors are translated; what `act` threw arrives as it was thrown
654
+ if (e instanceof owned_lock_1.ActError)
655
+ throw e.inner;
656
+ throw toEntityStoreError(e);
739
657
  }
740
- throw new EntityStoreError('unknown-owner', 'Recovery ownership chain exceeds the supported inspection bound.');
741
658
  }
@@ -38,6 +38,15 @@ export declare class TargetPathOccupiedError extends Error {
38
38
  * than an absent one, since it is exactly what causes the core-wide rework ADR-001 set out to avoid.
39
39
  * A lock would also duplicate what optimistic concurrency replaces. Widen when a caller appears.
40
40
  */
41
+ /**
42
+ * @implements A-SPEC-245.14 — `beforePublish` is called once, after the version and destination checks and before the
43
+ * first byte (inside the entity-store lock on the entity path); a refusal before it never calls it, and a throw from it
44
+ * writes nothing and propagates as thrown. Its caller is the single-use spend of a seal (A-SPEC-245.9).
45
+ */
46
+ export interface SpecWriteOptions {
47
+ expectedVersion?: string;
48
+ beforePublish?: () => undefined;
49
+ }
41
50
  export interface SpecStore {
42
51
  read(id: string): Promise<{
43
52
  spec: Spec;
@@ -45,6 +54,7 @@ export interface SpecStore {
45
54
  } | null>;
46
55
  write(spec: Spec, opts?: {
47
56
  expectedVersion?: string;
57
+ beforePublish?: () => undefined;
48
58
  }): Promise<{
49
59
  version: string;
50
60
  }>;
@@ -100,9 +110,7 @@ export declare class LocalMarkdownRepository implements SpecStore {
100
110
  * entity-store lock across asynchronous lookups, coordinating with explicit adoption.
101
111
  */
102
112
  private writeChain;
103
- write(spec: Spec, opts?: {
104
- expectedVersion?: string;
105
- }): Promise<{
113
+ write(spec: Spec, opts?: SpecWriteOptions): Promise<{
106
114
  version: string;
107
115
  }>;
108
116
  private writeSerialized;
@@ -131,9 +139,7 @@ export declare class MemorySpecStore implements SpecStore {
131
139
  spec: Spec;
132
140
  version: string;
133
141
  } | null>;
134
- write(spec: Spec, opts?: {
135
- expectedVersion?: string;
136
- }): Promise<{
142
+ write(spec: Spec, opts?: SpecWriteOptions): Promise<{
137
143
  version: string;
138
144
  }>;
139
145
  list(): Promise<Spec[]>;
@@ -36,7 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.MemorySpecStore = exports.LocalMarkdownRepository = exports.TargetPathOccupiedError = exports.SpecVersionConflictError = void 0;
37
37
  exports.unreadableSpecFiles = unreadableSpecFiles;
38
38
  exports.notFoundReason = notFoundReason;
39
- // @implements A-SPEC-627, A-SPEC-151, A-SPEC-100.1
39
+ // @implements A-SPEC-627, A-SPEC-151, A-SPEC-100.1, A-SPEC-245.14, A-SPEC-245.15
40
40
  const node_crypto_1 = require("node:crypto");
41
41
  const entity_store_1 = require("./entity-store");
42
42
  const fs = __importStar(require("node:fs"));
@@ -201,7 +201,7 @@ class LocalMarkdownRepository {
201
201
  async writeSerialized(spec, opts) {
202
202
  const newPath = this.targetPathFor(spec);
203
203
  try {
204
- return await (0, entity_store_1.writeEntityRepository)(this.root, spec, newPath, opts?.expectedVersion, () => this.writeLegacy(spec, opts));
204
+ return await (0, entity_store_1.writeEntityRepository)(this.root, spec, newPath, opts?.expectedVersion, () => this.writeLegacy(spec, opts), opts?.beforePublish);
205
205
  }
206
206
  catch (e) {
207
207
  if (e instanceof entity_store_1.EntityStoreError && e.code === 'version-conflict')
@@ -233,6 +233,7 @@ class LocalMarkdownRepository {
233
233
  if (currentPath !== newPath && fs.existsSync(newPath)) {
234
234
  throw new TargetPathOccupiedError(`spec ${spec.id}: destination ${newPath} is occupied by a file the store cannot read as this spec — a human must move or fix it first`, newPath);
235
235
  }
236
+ (0, entity_store_1.callBeforePublish)(opts?.beforePublish); // A-SPEC-245.14 — after both checks, before the first byte
236
237
  // Remove orphaned files with same id from different paths (e.g., after req_type change)
237
238
  const allSpecs = await this.list();
238
239
  for (const existing of allSpecs) {
@@ -367,6 +368,7 @@ class MemorySpecStore {
367
368
  throw new SpecVersionConflictError(`spec ${spec.id} changed since it was read (expected ${opts.expectedVersion}, found ${version ?? 'nothing'})`);
368
369
  }
369
370
  }
371
+ (0, entity_store_1.callBeforePublish)(opts?.beforePublish); // A-SPEC-245.14
370
372
  this.items.set(spec.id, spec);
371
373
  return { version: this.versionOf(spec) };
372
374
  }
@@ -108,7 +108,7 @@ exports.SPEC_TYPES = {
108
108
  // A DECISION, not a functional contract: a root type (no parent, like REQ) that records why a
109
109
  // choice was made and inherits the store's authoring governance (stub → validate → seal → ledger
110
110
  // → tamper-block). It carries NO T-SPEC/anchor/FtT duty — that is the No-Spec-No-Code chain, a
111
- // separate axis. Its number space is its own (see spec-id-guard), so jarvis's ADR-0001 does not
111
+ // separate axis. Its number space is its own (see spec-id-guard), so a consumer workspace's ADR-0001 does not
112
112
  // collide with the functional chain's max. 4-digit zero-padded ids are accepted (ADR-0001).
113
113
  'ADR': {
114
114
  type: 'ADR', idRegex: /^ADR-\d{3,}$/, example: 'ADR-0001', folder: '06_adr', parents: [],
@@ -0,0 +1,56 @@
1
+ import { Spec } from './spec-parser';
2
+ import { type ApprovedSeal, type RecordedPair } from './succession';
3
+ import { type IgnoredEvent } from '../governance/recorded-pairs';
4
+ /**
5
+ * A-SPEC-222.8 N2 — who succeeds a spec is the tools' record, never a hand edit: a write whose result changes
6
+ * superseded_by or replaces is refused, whatever approval is held (the route is spec_retire). `edited` is the edit
7
+ * applied to `disk` (null when it applies nowhere, 'too-large' past the gate's bound); with no result, a payload that
8
+ * writes either field is refused.
9
+ */
10
+ export declare function successionFieldEditRefusal(disk: string | null, edited: string | null | 'too-large', id: string, newString?: string): string | null;
11
+ /**
12
+ * @implements A-SPEC-222.15 (item 2) — the top-level keys of the FIRST frontmatter block (`---` … `---` at the start),
13
+ * read line by line for a file whose YAML does not parse: a scalar with its trailing ` # comment` and quotes removed, or
14
+ * a block list of `- item` lines. Lines that are neither (a conflict marker, say) are skipped. Null with no block.
15
+ */
16
+ export declare function lenientFrontmatter(text: string): Record<string, string | string[]> | null;
17
+ /**
18
+ * A-SPEC-222.4 and A-SPEC-222.6 — whether the FILE changes only by anchor moves: `after` is `before` with a non-empty
19
+ * subset of the RTM anchor tokens of `x` (string literals excluded, as the RTM reads them) turned into `y`, and no other
20
+ * character differs. Judged on the file, never on the edit text (AU1-b.1 F1: a literal, a compared value or a prose
21
+ * line moved with the marker); no replacement pattern is interpreted (F2); an id followed by an id character or `-` is
22
+ * not the id (L4). A-SPEC-222.8 N1/N3: the per-format reading the gate uses, and in a code format only tokens inside a
23
+ * comment of a language with a reader; a code language with no reader moves nothing. `relPath` is required (A-SPEC-222.9
24
+ * low item: a default path read every file as TypeScript).
25
+ */
26
+ export declare function anchorMoveOnly(before: string, after: string, x: string, y: string, relPath: string): boolean;
27
+ export interface AnchorMove {
28
+ x: string;
29
+ y: string;
30
+ digest: string;
31
+ after: string;
32
+ }
33
+ export interface MoveDeps {
34
+ specs: Spec[];
35
+ resolveSpec(id: string): Spec | undefined;
36
+ /** The trusted record, read once and only when a move is asked for (the port reads the ledger and git). */
37
+ record(): {
38
+ recorded: RecordedPair;
39
+ approved: ApprovedSeal;
40
+ ignored: IgnoredEvent[];
41
+ };
42
+ }
43
+ /**
44
+ * The anchor moves an Edit makes (A-SPEC-222.4, A-SPEC-222.6): each governing outdated X whose superseded_by Y is on
45
+ * the trusted record, that holds its seal, that Y qualifies for, and whose file changes only by the move. `note` says
46
+ * why a move that was asked for was not taken, naming the ignored ledger entries, so the refusal can say it.
47
+ */
48
+ export declare function movedAnchors(input: {
49
+ before: string;
50
+ after: string | null;
51
+ governingIds: string[];
52
+ relPath: string;
53
+ }, deps: MoveDeps): {
54
+ moves: AnchorMove[];
55
+ note: string;
56
+ };
@@ -0,0 +1,187 @@
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.successionFieldEditRefusal = successionFieldEditRefusal;
37
+ exports.lenientFrontmatter = lenientFrontmatter;
38
+ exports.anchorMoveOnly = anchorMoveOnly;
39
+ exports.movedAnchors = movedAnchors;
40
+ // @implements A-SPEC-222.9, A-SPEC-222.10, A-SPEC-222.15
41
+ /**
42
+ * The code gate's two succession responsibilities, out of `evaluateHook` (SD1 finding 1; A-SPEC-222.6 and A-SPEC-222.8
43
+ * had put them inline): the refusal of a hand edit to a spec's succession fields, and the anchor-move judgment. The
44
+ * gate calls these and decides nothing about succession itself.
45
+ */
46
+ const crypto = __importStar(require("node:crypto"));
47
+ const spec_parser_1 = require("./spec-parser");
48
+ const spec_digest_1 = require("./spec-digest");
49
+ const succession_1 = require("./succession");
50
+ const recorded_pairs_1 = require("../governance/recorded-pairs");
51
+ /**
52
+ * A-SPEC-222.8 N2 — who succeeds a spec is the tools' record, never a hand edit: a write whose result changes
53
+ * superseded_by or replaces is refused, whatever approval is held (the route is spec_retire). `edited` is the edit
54
+ * applied to `disk` (null when it applies nowhere, 'too-large' past the gate's bound); with no result, a payload that
55
+ * writes either field is refused.
56
+ */
57
+ function successionFieldEditRefusal(disk, edited, id, newString) {
58
+ const succession = (text) => {
59
+ if (text === null)
60
+ return JSON.stringify([null, null]);
61
+ try {
62
+ const fm = (0, spec_parser_1.parseSpec)(text).frontmatter;
63
+ return JSON.stringify([fm.superseded_by ?? null, fm.replaces ?? null]);
64
+ }
65
+ catch {
66
+ // @implements A-SPEC-222.15 (item 3) — a file whose YAML does not parse is read leniently, so a repair that keeps
67
+ // the fields is no change (it read as `unparsed:<len>` and refused every repair of a retired spec with a successor)
68
+ const fm = lenientFrontmatter(text);
69
+ if (fm !== null)
70
+ return JSON.stringify([fm.superseded_by ?? null, fm.replaces ?? null]);
71
+ return /^\s*(?:superseded_by|replaces)\s*:/m.test(text) ? `unparsed:${text.length}` : JSON.stringify([null, null]);
72
+ }
73
+ };
74
+ const touches = edited === 'too-large' || (typeof edited === 'string' && succession(edited) !== succession(disk))
75
+ || (edited === null && typeof newString === 'string' && /^\s*(?:superseded_by|replaces)\s*:/m.test(newString));
76
+ return touches ? `[Holmes-Kit] ${id}: superseded_by and replaces are written by the tools, not by an edit — use spec_retire({ id, supersededBy, directive }) (A-SPEC-222.8)` : null;
77
+ }
78
+ /**
79
+ * @implements A-SPEC-222.15 (item 2) — the top-level keys of the FIRST frontmatter block (`---` … `---` at the start),
80
+ * read line by line for a file whose YAML does not parse: a scalar with its trailing ` # comment` and quotes removed, or
81
+ * a block list of `- item` lines. Lines that are neither (a conflict marker, say) are skipped. Null with no block.
82
+ */
83
+ function lenientFrontmatter(text) {
84
+ const m = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
85
+ if (!m)
86
+ return null;
87
+ const out = {};
88
+ const lines = m[1].split(/\r?\n/);
89
+ for (let i = 0; i < lines.length; i++) {
90
+ const kv = /^([A-Za-z_][\w-]*):(?:[ \t]+(.*))?$/.exec(lines[i]);
91
+ if (!kv)
92
+ continue;
93
+ const raw = (kv[2] ?? '').replace(/[ \t]+#.*$/, '').trim();
94
+ if (raw !== '' && raw !== '>-' && raw !== '|') {
95
+ out[kv[1]] = raw.replace(/^(['"])(.*)\1$/, '$2');
96
+ continue;
97
+ }
98
+ const items = [];
99
+ while (i + 1 < lines.length && /^[ \t]+-[ \t]+/.test(lines[i + 1]))
100
+ items.push(lines[++i].replace(/^[ \t]+-[ \t]+/, '').replace(/[ \t]+#.*$/, '').trim().replace(/^(['"])(.*)\1$/, '$2'));
101
+ if (items.length > 0)
102
+ out[kv[1]] = items;
103
+ }
104
+ return out;
105
+ }
106
+ /**
107
+ * A-SPEC-222.4 and A-SPEC-222.6 — whether the FILE changes only by anchor moves: `after` is `before` with a non-empty
108
+ * subset of the RTM anchor tokens of `x` (string literals excluded, as the RTM reads them) turned into `y`, and no other
109
+ * character differs. Judged on the file, never on the edit text (AU1-b.1 F1: a literal, a compared value or a prose
110
+ * line moved with the marker); no replacement pattern is interpreted (F2); an id followed by an id character or `-` is
111
+ * not the id (L4). A-SPEC-222.8 N1/N3: the per-format reading the gate uses, and in a code format only tokens inside a
112
+ * comment of a language with a reader; a code language with no reader moves nothing. `relPath` is required (A-SPEC-222.9
113
+ * low item: a default path read every file as TypeScript).
114
+ */
115
+ function anchorMoveOnly(before, after, x, y, relPath) {
116
+ const ID = /^A-SPEC-\d{3,}(?:\.\d+)?$/;
117
+ if (!ID.test(x) || !ID.test(y) || x === y || before === after)
118
+ return false;
119
+ const idChar = (c) => c !== undefined && /[\w.-]/.test(c);
120
+ const { anchorIdSpansFor, anchorCodeFormat } = require('../rtm/anchor-ids');
121
+ let comments = null;
122
+ if (anchorCodeFormat(relPath)) {
123
+ comments = require('../rtm/comment-ranges').commentRanges(relPath, before);
124
+ if (comments === null)
125
+ return false;
126
+ }
127
+ const inComment = (s) => comments === null || comments.some(([a, b]) => a <= s.start && s.end <= b);
128
+ const spans = anchorIdSpansFor(relPath, before).filter((s) => s.spec === x && !idChar(before[s.end]) && inComment(s));
129
+ let i = 0;
130
+ let j = 0;
131
+ let moved = 0;
132
+ for (const s of spans) {
133
+ const gap = before.slice(i, s.start);
134
+ if (after.slice(j, j + gap.length) !== gap)
135
+ return false;
136
+ j += gap.length;
137
+ if (after.startsWith(y, j) && !idChar(after[j + y.length])) {
138
+ j += y.length;
139
+ moved++;
140
+ }
141
+ else if (after.startsWith(x, j) && !idChar(after[j + x.length]))
142
+ j += x.length;
143
+ else
144
+ return false;
145
+ i = s.end;
146
+ }
147
+ return moved > 0 && after.slice(j) === before.slice(i);
148
+ }
149
+ /**
150
+ * The anchor moves an Edit makes (A-SPEC-222.4, A-SPEC-222.6): each governing outdated X whose superseded_by Y is on
151
+ * the trusted record, that holds its seal, that Y qualifies for, and whose file changes only by the move. `note` says
152
+ * why a move that was asked for was not taken, naming the ignored ledger entries, so the refusal can say it.
153
+ */
154
+ function movedAnchors(input, deps) {
155
+ if (input.after === null)
156
+ return { moves: [], note: '' };
157
+ let record = null;
158
+ const moves = [];
159
+ const why = [];
160
+ for (const x of input.governingIds) {
161
+ const xs = deps.resolveSpec(x);
162
+ const y = xs && xs.status === 'outdated' ? String(xs.frontmatter.superseded_by ?? '').trim() : '';
163
+ if (!xs || !y || !anchorMoveOnly(input.before, input.after, x, y, input.relPath))
164
+ continue;
165
+ if (record === null) {
166
+ try {
167
+ record = deps.record();
168
+ }
169
+ catch {
170
+ record = { recorded: () => false, approved: () => false, ignored: [{ file: '.ax/ledger', why: 'the ledger could not be read' }] };
171
+ }
172
+ }
173
+ const judge = new succession_1.SuccessionJudge({ specs: deps.specs, recorded: record.recorded, approved: record.approved, counted: () => 0 });
174
+ if (!judge.recorded(x, y)) {
175
+ why.push(`${x} → ${y} is not on the trusted record`);
176
+ continue;
177
+ }
178
+ const refused = judge.aspec(xs, y);
179
+ if (refused !== null) {
180
+ why.push(`${x} → ${y}: ${refused}`);
181
+ continue;
182
+ }
183
+ moves.push({ x, y, digest: String((0, spec_digest_1.sealOf)(deps.resolveSpec(y)).approvedDigest), after: crypto.createHash('sha256').update(input.after).digest('hex') });
184
+ }
185
+ const ignored = record ? (0, recorded_pairs_1.describeIgnored)(record.ignored) : '';
186
+ return { moves, note: why.length === 0 ? '' : `anchor move not taken (A-SPEC-222.9): ${why.join('; ')}${ignored ? ` — ${ignored}` : ''}` };
187
+ }