blun-king-cli 9.1.643 → 9.1.645

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 (268) hide show
  1. package/CHANGELOG.md +19 -123
  2. package/LIESMICH.txt +17 -45
  3. package/README.md +15 -76
  4. package/RELEASE-9.1.645.md +29 -0
  5. package/bin/blun.js +3 -3
  6. package/bin/king.js +3 -3
  7. package/bin/launcher-mode.js +125 -126
  8. package/bin/launcher-runtime.js +603 -616
  9. package/bin/plugin-bootstrap.js +339 -405
  10. package/bin/rename-private-staging.cjs +2 -2
  11. package/bin/retired-bundled-plugins.cjs +84 -0
  12. package/bin/startup-security-host.cjs +105 -0
  13. package/bin/startup-security.cjs +9 -105
  14. package/bin/startup-warning-policy.cjs +22 -0
  15. package/bin/update-lease-installer.cjs +125 -0
  16. package/bin/update-lease-sockets.cjs +228 -0
  17. package/bin/update-lease.js +22 -327
  18. package/bin/verify-bundled-agent-sources.cjs +2 -4
  19. package/blun.mjs +77 -180
  20. package/bundled-agent-sources.json +1 -552
  21. package/package.json +3 -6
  22. package/tool-liveness642/receipt.json +1 -1
  23. package/worker-host.mjs +62 -120
  24. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  25. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  26. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  27. package/agent-spine-plugin/.mcp.json +0 -8
  28. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  29. package/agent-spine-plugin/LICENSE +0 -186
  30. package/agent-spine-plugin/README.md +0 -432
  31. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  32. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  33. package/agent-spine-plugin/bin/agentspine.js +0 -7
  34. package/agent-spine-plugin/blun.plugin.json +0 -68
  35. package/agent-spine-plugin/docs/acceptance.md +0 -61
  36. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  37. package/agent-spine-plugin/docs/host-integration.md +0 -193
  38. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  39. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  40. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  41. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  42. package/agent-spine-plugin/docs/source-roots.md +0 -113
  43. package/agent-spine-plugin/docs/world-model.md +0 -119
  44. package/agent-spine-plugin/hooks/codex.json +0 -47
  45. package/agent-spine-plugin/hooks/hooks.json +0 -106
  46. package/agent-spine-plugin/hooks/version.json +0 -5
  47. package/agent-spine-plugin/package.json +0 -77
  48. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  49. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  50. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  51. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  52. package/agent-spine-plugin/scripts/check-install.js +0 -478
  53. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  54. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  55. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  56. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  57. package/agent-spine-plugin/scripts/release-check.js +0 -150
  58. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  59. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  60. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  61. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  62. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  63. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  64. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  65. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  66. package/agent-spine-plugin/src/cli-agent.js +0 -315
  67. package/agent-spine-plugin/src/cli-attention.js +0 -95
  68. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  69. package/agent-spine-plugin/src/cli-common.js +0 -71
  70. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  71. package/agent-spine-plugin/src/cli-core.js +0 -128
  72. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  73. package/agent-spine-plugin/src/cli-host.js +0 -21
  74. package/agent-spine-plugin/src/cli-learning.js +0 -320
  75. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  76. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  77. package/agent-spine-plugin/src/cli.js +0 -181
  78. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  79. package/agent-spine-plugin/src/hook.js +0 -500
  80. package/agent-spine-plugin/src/index.js +0 -108
  81. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  82. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  83. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  84. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  85. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  86. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  87. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  88. package/agent-spine-plugin/src/lib/attention.js +0 -164
  89. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  90. package/agent-spine-plugin/src/lib/audit.js +0 -401
  91. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  92. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  93. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  94. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  95. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  96. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  97. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  98. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  99. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  100. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  101. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  102. package/agent-spine-plugin/src/lib/context.js +0 -156
  103. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  104. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  105. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  106. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  107. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  108. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  109. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  110. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  111. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  112. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  113. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  114. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  115. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  116. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  117. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  118. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  119. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  120. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  121. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  122. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  123. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  124. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  125. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  126. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  127. package/agent-spine-plugin/src/lib/documents.js +0 -239
  128. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  129. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  130. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  131. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  132. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  133. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  134. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  135. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  136. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  137. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  138. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  139. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  140. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  141. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  142. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  143. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  144. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  145. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  146. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  147. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  148. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  149. package/agent-spine-plugin/src/lib/graph.js +0 -337
  150. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  151. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  152. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  153. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  154. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  155. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  156. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  157. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  158. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  159. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  160. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  161. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  162. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  163. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  164. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  165. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  166. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  167. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  168. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  169. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  170. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  171. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  172. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  173. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  174. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  175. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  176. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  177. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  178. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  179. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  180. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  181. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  182. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  183. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  184. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  185. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  186. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  187. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  188. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  189. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  190. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  191. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  192. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  193. package/agent-spine-plugin/src/lib/learning.js +0 -36
  194. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  195. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  196. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  197. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  198. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  199. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  200. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  201. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  202. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  203. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  204. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  205. package/agent-spine-plugin/src/lib/paths.js +0 -109
  206. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  207. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  208. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  209. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  210. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  211. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  212. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  213. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  214. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  215. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  216. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  217. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  218. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  219. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  220. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  221. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  224. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  225. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  226. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  227. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  228. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  229. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  230. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  231. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  232. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  233. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  234. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  235. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  236. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  237. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  238. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  239. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  240. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  241. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  242. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  243. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  244. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  245. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  246. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  247. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  248. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  249. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  250. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  251. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  252. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  253. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  254. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  255. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  256. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  257. package/agent-spine-plugin/src/mcp.js +0 -456
  258. package/agent-spine-plugin/src/version.js +0 -1
  259. package/agent-spine-plugin/src/worker.js +0 -257
  260. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  261. package/bin/agentspine-king-goal-intake.mjs +0 -106
  262. package/bin/agentspine-king-host-runner.mjs +0 -109
  263. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  264. package/bin/agentspine-king-status-policy.mjs +0 -226
  265. package/bin/agentspine-king-worker-host.mjs +0 -160
  266. package/bin/managed-plugin-selection.cjs +0 -141
  267. package/bin/verify-agent-behavior.cjs +0 -122
  268. package/bin/verify-agent-components.cjs +0 -104
@@ -1,445 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { replaceFileWithRetry } from "./filesystem-retry.js";
5
- import { withOwnedFileLock } from "./owned-file-lock.js";
6
- import { canonicalPath, projectStateDir } from "./paths.js";
7
- import { commandFromInput, deliveryToolActions, isSuccessMarkerClause } from "./delivery-command-actions.js";
8
- import { deliveryWriteIdDigest } from "./delivery-premortem-binding.js";
9
-
10
- export { deliveryToolActions } from "./delivery-command-actions.js";
11
-
12
- export const DELIVERY_VERIFICATION_SCHEMA = "agentspine.delivery-verification/v1";
13
- const DIGEST_RE = /^[a-f0-9]{64}$/;
14
- const MAX_STATE_BYTES = 64 * 1024;
15
- const MAX_RECENT_EVENTS = 32;
16
- const MAX_PENDING_WRITE_INTENTS = 32;
17
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_.@/-]{0,127}$/;
18
- const TEST_PROOF_GUIDANCE = "AgentSpine saw a test command without verified success. Use structured exit_code 0, "
19
- + "or append && node -e \"console.log('AGENTSPINE_TEST_OK')\" and keep that marker as the final output line.";
20
-
21
- function sha256(value) {
22
- return createHash("sha256").update(value).digest("hex");
23
- }
24
-
25
- function stateMaterial(state) {
26
- return {
27
- schema: state.schema,
28
- laneDigest: state.laneDigest,
29
- revision: state.revision,
30
- lastWrite: state.lastWrite,
31
- lastTest: state.lastTest,
32
- verifiedWriteDigest: state.verifiedWriteDigest,
33
- pauseEventDigest: state.pauseEventDigest,
34
- conflict: state.conflict,
35
- pendingWriteIntents: state.pendingWriteIntents,
36
- recentEvents: state.recentEvents,
37
- authority: "verification-state-only"
38
- };
39
- }
40
-
41
- function legacyStateMaterial(state) {
42
- const material = stateMaterial(state);
43
- delete material.pendingWriteIntents;
44
- return material;
45
- }
46
-
47
- function seal(state) {
48
- state.integrityDigest = sha256(JSON.stringify(stateMaterial(state)));
49
- return state;
50
- }
51
-
52
- function emptyState(laneDigest) {
53
- return seal({
54
- schema: DELIVERY_VERIFICATION_SCHEMA,
55
- laneDigest,
56
- revision: 0,
57
- lastWrite: null,
58
- lastTest: null,
59
- verifiedWriteDigest: null,
60
- pauseEventDigest: null,
61
- conflict: null,
62
- pendingWriteIntents: [],
63
- recentEvents: [],
64
- integrityDigest: null,
65
- authority: "verification-state-only"
66
- });
67
- }
68
-
69
- function validReceipt(receipt) {
70
- return receipt === null || (receipt && typeof receipt === "object" && !Array.isArray(receipt)
71
- && DIGEST_RE.test(receipt.eventDigest || "") && typeof receipt.toolName === "string"
72
- && receipt.toolName.length <= 128 && typeof receipt.at === "string"
73
- && Number.isFinite(new Date(receipt.at).getTime())
74
- && (receipt.family === null || typeof receipt.family === "string"));
75
- }
76
-
77
- function normalizeState(value, laneDigest) {
78
- const pendingWriteIntents = value?.pendingWriteIntents ?? [];
79
- const legacyIntegrity = value?.pendingWriteIntents === undefined
80
- && value?.integrityDigest === sha256(JSON.stringify(legacyStateMaterial(value)));
81
- if (!(value && value.schema === DELIVERY_VERIFICATION_SCHEMA && value.laneDigest === laneDigest
82
- && Number.isInteger(value.revision) && value.revision >= 0
83
- && validReceipt(value.lastWrite) && validReceipt(value.lastTest)
84
- && (value.verifiedWriteDigest === null || DIGEST_RE.test(value.verifiedWriteDigest))
85
- && (value.pauseEventDigest === null || DIGEST_RE.test(value.pauseEventDigest))
86
- && (value.conflict === null || DIGEST_RE.test(value.conflict))
87
- && Array.isArray(pendingWriteIntents) && pendingWriteIntents.length <= MAX_PENDING_WRITE_INTENTS
88
- && pendingWriteIntents.every((item) => validReceipt(item) && DIGEST_RE.test(item.idDigest || "")
89
- && DIGEST_RE.test(item.intentDigest || ""))
90
- && Array.isArray(value.recentEvents) && value.recentEvents.length <= MAX_RECENT_EVENTS
91
- && value.recentEvents.every((item) => DIGEST_RE.test(item?.idDigest || "")
92
- && DIGEST_RE.test(item?.eventDigest || "")
93
- && (item.intentDigest === undefined || item.intentDigest === null || DIGEST_RE.test(item.intentDigest)))
94
- && value.authority === "verification-state-only"
95
- && DIGEST_RE.test(value.integrityDigest || "")
96
- && (value.integrityDigest === sha256(JSON.stringify(stateMaterial(value))) || legacyIntegrity))) {
97
- throw new Error("delivery verification state failed integrity validation");
98
- }
99
- return value.pendingWriteIntents === undefined ? seal({ ...value, pendingWriteIntents }) : value;
100
- }
101
-
102
- function timestamp(value) {
103
- const date = new Date(value || Date.now());
104
- return Number.isFinite(date.getTime()) ? date.toISOString() : new Date().toISOString();
105
- }
106
-
107
- function scopeValue(scope, name) {
108
- const value = scope?.[name];
109
- return typeof value === "string" && value ? value : "";
110
- }
111
-
112
- function exactGatewayAttempt(scope) {
113
- const value = scope?.gatewayAttempt;
114
- return Number.isSafeInteger(value) && value > 0 ? String(value) : "";
115
- }
116
-
117
- function laneMaterial({ host, sessionId, scope }) {
118
- const taskBound = scopeValue(scope, "entityId") && scopeValue(scope, "projectId")
119
- && scopeValue(scope, "currentTaskId");
120
- if (taskBound) {
121
- const queueId = scopeValue(scope, "queueId");
122
- const gatewayAttempt = exactGatewayAttempt(scope);
123
- if (queueId && gatewayAttempt) {
124
- return ["delivery", host || "unknown", scopeValue(scope, "entityId"),
125
- scopeValue(scope, "tenantId"), scopeValue(scope, "groupId"), scopeValue(scope, "projectId"),
126
- scopeValue(scope, "currentTaskId"), queueId, gatewayAttempt, scopeValue(scope, "goalId"),
127
- scopeValue(scope, "goalStepId"), scopeValue(scope, "planDefinitionsDigest")].join("\0");
128
- }
129
- const values = ["task", host || "unknown", scopeValue(scope, "entityId"),
130
- scopeValue(scope, "projectId"), scopeValue(scope, "currentTaskId")];
131
- if (typeof sessionId === "string" && sessionId) values.push(sessionId);
132
- return values.join("\0");
133
- }
134
- return typeof sessionId === "string" && sessionId ? ["session", host || "unknown", sessionId].join("\0") : null;
135
- }
136
-
137
- export function deliveryActorSession(input) {
138
- const hostSession = input?.session_id ?? input?.sessionId;
139
- if (typeof hostSession !== "string" || !ID_RE.test(hostSession)) return null;
140
- const turn = input?.turn_id ?? input?.turnId;
141
- if (turn !== null && turn !== undefined && turn !== ""
142
- && (typeof turn !== "string" || !ID_RE.test(turn))) throw new Error("turnId is invalid");
143
- return hostSession;
144
- }
145
-
146
- function eventIdentity(input, actions, success) {
147
- const supplied = input.tool_use_id ?? input.event_id ?? input.hook_event_id;
148
- const idDigest = sha256(typeof supplied === "string" && supplied
149
- ? supplied : JSON.stringify([input.timestamp || null, input.tool_name || null, input.tool_input || input.tool_args || null]));
150
- return {
151
- idDigest,
152
- eventDigest: sha256(JSON.stringify([idDigest, input.tool_name || null, actions, Boolean(success)]))
153
- };
154
- }
155
-
156
- function stableToolIdentity(input, actions) {
157
- const idDigest = deliveryWriteIdDigest(input);
158
- return {
159
- idDigest,
160
- intentDigest: sha256(JSON.stringify([
161
- idDigest, input.tool_name || null, actions, input.tool_input ?? input.tool_args ?? null
162
- ]))
163
- };
164
- }
165
-
166
- function resultValues(input) {
167
- return [input?.tool_result, input?.tool_response, input?.result].filter((value) => value !== undefined);
168
- }
169
-
170
- function markerOutputTexts(value) {
171
- if (typeof value === "string") return [value];
172
- if (Array.isArray(value)) return value.flatMap(markerOutputTexts);
173
- if (!value || typeof value !== "object") return [];
174
- return ["stdout", "output", "text", "content", "stderr"].flatMap((key) => markerOutputTexts(value[key]));
175
- }
176
-
177
- function hasBoundSuccessMarker(input) {
178
- const command = commandFromInput(input);
179
- const parts = command.split(/\s*&&\s*/);
180
- if (parts.length < 2 || !isSuccessMarkerClause(parts.at(-1))) return false;
181
- const output = resultValues(input).flatMap(markerOutputTexts).join("\n").trimEnd();
182
- return output.split(/\r?\n/).at(-1)?.trim() === "AGENTSPINE_TEST_OK";
183
- }
184
-
185
- export function deliverySuccessEvidence(input) {
186
- if (input?.success === false || input?.is_error === true || input?.tool_error) return false;
187
- if (resultValues(input).some((value) => value && typeof value === "object"
188
- && (value.isError === true || value.exit_code > 0 || value.exitCode > 0))) return false;
189
- // Host transport success means only that the tool invocation returned. A
190
- // test is verified by its own structured process exit or the bound marker.
191
- return resultValues(input).some((value) => value && typeof value === "object"
192
- && (value.exit_code === 0 || value.exitCode === 0))
193
- || hasBoundSuccessMarker(input);
194
- }
195
-
196
- async function statePaths(root, laneDigest) {
197
- const directory = join(await projectStateDir(await canonicalPath(root)), "delivery-verification");
198
- await mkdir(directory, { recursive: true, mode: 0o700 });
199
- const path = join(directory, `${laneDigest}.json`);
200
- return { path, lockPath: `${path}.lock` };
201
- }
202
-
203
- async function readState(path, laneDigest) {
204
- try {
205
- const content = await readFile(path, "utf8");
206
- if (Buffer.byteLength(content) > MAX_STATE_BYTES) throw new Error("delivery verification state exceeds 64 KiB");
207
- return normalizeState(JSON.parse(content), laneDigest);
208
- } catch (error) {
209
- if (error.code === "ENOENT") return emptyState(laneDigest);
210
- if (error instanceof SyntaxError) throw new Error("delivery verification state is not valid JSON");
211
- throw error;
212
- }
213
- }
214
-
215
- async function saveState(path, state, assertOwned) {
216
- seal(state);
217
- const content = `${JSON.stringify(state, null, 2)}\n`;
218
- if (Buffer.byteLength(content) > MAX_STATE_BYTES) throw new Error("delivery verification state exceeds 64 KiB");
219
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
220
- try {
221
- await writeFile(temporary, content, { mode: 0o600 });
222
- await assertOwned();
223
- await replaceFileWithRetry(temporary, path);
224
- } finally {
225
- await unlink(temporary).catch((error) => { if (error.code !== "ENOENT") throw error; });
226
- }
227
- }
228
-
229
- function receipt(input, eventDigest, family = null) {
230
- return {
231
- eventDigest,
232
- toolName: String(input.tool_name || "unknown").slice(0, 128),
233
- family,
234
- at: timestamp(input.timestamp)
235
- };
236
- }
237
-
238
- function pendingIntentReceipt(input, identity) {
239
- return {
240
- ...receipt(input, identity.intentDigest),
241
- idDigest: identity.idDigest,
242
- intentDigest: identity.intentDigest
243
- };
244
- }
245
-
246
- function unresolvedIntentReason(state) {
247
- const tools = [...new Set(state.pendingWriteIntents.map((item) => item.toolName))].sort();
248
- return `AgentSpine cannot accept this delivery: ${state.pendingWriteIntents.length} write intent(s) `
249
- + `(${tools.join(", ")}) have no auditable PostToolUse result. Run a successful test after the intended mutation. `
250
- + `If the hook supplies no success field, append && node -e \"console.log('AGENTSPINE_TEST_OK')\"; `
251
- + `the marker must be the final output line.`;
252
- }
253
-
254
- export async function recordDeliveryWriteIntent({ root, host, sessionId, scope, input }) {
255
- const material = laneMaterial({ host, sessionId, scope });
256
- const actions = deliveryToolActions(input);
257
- if (!material || !actions.some((item) => item.kind === "write")) {
258
- return { status: "not-applicable", blocked: false };
259
- }
260
- const identity = stableToolIdentity(input, actions);
261
- const laneDigest = sha256(material);
262
- const paths = await statePaths(root, laneDigest);
263
- try {
264
- return await withOwnedFileLock(paths.lockPath, async ({ assertOwned }) => {
265
- const state = await readState(paths.path, laneDigest);
266
- const resolved = state.recentEvents.find((item) => item.idDigest === identity.idDigest);
267
- if (resolved) {
268
- if (resolved.intentDigest && resolved.intentDigest !== identity.intentDigest) {
269
- state.conflict = identity.idDigest;
270
- state.revision += 1;
271
- await saveState(paths.path, state, assertOwned);
272
- return { status: "conflict", blocked: true,
273
- reason: "AgentSpine write tool_use_id was reused with a different mutation." };
274
- }
275
- return { status: "already-resolved", blocked: false };
276
- }
277
- const pending = state.pendingWriteIntents.find((item) => item.idDigest === identity.idDigest);
278
- if (pending) {
279
- if (pending.intentDigest !== identity.intentDigest) {
280
- state.conflict = identity.idDigest;
281
- state.revision += 1;
282
- await saveState(paths.path, state, assertOwned);
283
- return { status: "conflict", blocked: true,
284
- reason: "AgentSpine write tool_use_id was reused with a different mutation." };
285
- }
286
- return { status: "duplicate-intent", blocked: false };
287
- }
288
- if (state.pendingWriteIntents.length >= MAX_PENDING_WRITE_INTENTS) {
289
- state.conflict = sha256(`pending-write-intent-overflow\0${laneDigest}`);
290
- state.revision += 1;
291
- await saveState(paths.path, state, assertOwned);
292
- return { status: "conflict", blocked: true,
293
- reason: `AgentSpine cannot track more than ${MAX_PENDING_WRITE_INTENTS} concurrent write intents.` };
294
- }
295
- state.pendingWriteIntents.push(pendingIntentReceipt(input, identity));
296
- // A resumed mutation makes a prior paused Stop event stale. Keep the
297
- // invalidation in the same locked state transition as the intent so an
298
- // identical later completion event cannot bypass the pending-test gate.
299
- state.pauseEventDigest = null;
300
- state.revision += 1;
301
- await saveState(paths.path, state, assertOwned);
302
- return { status: "intent-recorded", blocked: false, pending: true };
303
- });
304
- } catch (error) {
305
- return { status: "degraded", blocked: false, reason: error.message };
306
- }
307
- }
308
-
309
- export async function recordDeliveryToolUse({ root, host, sessionId, scope, input, success }) {
310
- const material = laneMaterial({ host, sessionId, scope });
311
- const actions = deliveryToolActions(input);
312
- if (!material || !actions.length) return { status: "not-applicable", blocked: false };
313
- const laneDigest = sha256(material);
314
- const paths = await statePaths(root, laneDigest);
315
- try {
316
- return await withOwnedFileLock(paths.lockPath, async ({ assertOwned }) => {
317
- const state = await readState(paths.path, laneDigest);
318
- const identity = eventIdentity(input, actions, success);
319
- const stableIdentity = stableToolIdentity(input, actions);
320
- const known = state.recentEvents.find((item) => item.idDigest === identity.idDigest);
321
- if (known) {
322
- if (known.eventDigest !== identity.eventDigest) {
323
- state.conflict = identity.idDigest;
324
- state.revision += 1;
325
- await saveState(paths.path, state, assertOwned);
326
- return { status: "conflict", blocked: false };
327
- }
328
- return { status: "duplicate", blocked: false };
329
- }
330
- const writes = actions.some((item) => item.kind === "write");
331
- if (writes) {
332
- const pending = state.pendingWriteIntents.find((item) => item.idDigest === stableIdentity.idDigest);
333
- if (pending && pending.intentDigest !== stableIdentity.intentDigest) {
334
- state.conflict = stableIdentity.idDigest;
335
- state.revision += 1;
336
- await saveState(paths.path, state, assertOwned);
337
- return { status: "conflict", blocked: false };
338
- }
339
- state.pendingWriteIntents = state.pendingWriteIntents
340
- .filter((item) => item.idDigest !== stableIdentity.idDigest);
341
- }
342
- for (const action of actions) {
343
- if (action.kind === "write") {
344
- state.lastWrite = receipt(input, identity.eventDigest);
345
- state.pauseEventDigest = null;
346
- } else if (success) {
347
- if (state.pendingWriteIntents.length) {
348
- const intendedWrite = state.pendingWriteIntents.at(-1);
349
- state.lastWrite = {
350
- eventDigest: intendedWrite.intentDigest, toolName: intendedWrite.toolName,
351
- family: null, at: intendedWrite.at
352
- };
353
- state.pendingWriteIntents = [];
354
- state.pauseEventDigest = null;
355
- }
356
- state.lastTest = receipt(input, identity.eventDigest, action.family);
357
- state.verifiedWriteDigest = state.lastWrite?.eventDigest || null;
358
- } else {
359
- // A later failed or unverified test cannot inherit an earlier success.
360
- // Preserve that receipt as history, but require fresh post-write evidence.
361
- state.verifiedWriteDigest = null;
362
- }
363
- }
364
- state.recentEvents.push({ ...identity, intentDigest: stableIdentity.intentDigest });
365
- state.recentEvents = state.recentEvents.slice(-MAX_RECENT_EVENTS);
366
- state.revision += 1;
367
- await saveState(paths.path, state, assertOwned);
368
- return {
369
- status: actions.some((item) => item.kind === "write") ? "write-recorded" : success ? "test-recorded" : "test-failed",
370
- blocked: false,
371
- ...(!writes && !success ? { reason: TEST_PROOF_GUIDANCE } : {}),
372
- pending: Boolean(state.lastWrite && state.verifiedWriteDigest !== state.lastWrite.eventDigest)
373
- };
374
- });
375
- } catch (error) {
376
- return { status: "degraded", blocked: false, reason: error.message };
377
- }
378
- }
379
-
380
- export async function recordDeliveryPause({ root, host, sessionId, scope, eventId }) {
381
- const material = laneMaterial({ host, sessionId, scope });
382
- if (!material) {
383
- return { status: "paused-job", blocked: false };
384
- }
385
- const laneDigest = sha256(material);
386
- const paths = await statePaths(root, laneDigest);
387
- try {
388
- return await withOwnedFileLock(paths.lockPath, async ({ assertOwned }) => {
389
- const state = await readState(paths.path, laneDigest);
390
- if (state.pendingWriteIntents.length) {
391
- return { status: "blocked", blocked: true, reason: unresolvedIntentReason(state) };
392
- }
393
- // A pause may deduplicate only this exact Stop event. A session identity is
394
- // deliberately insufficient because it could bypass a later completion.
395
- const pauseEventDigest = typeof eventId === "string" && eventId ? sha256(`event\0${eventId}`) : null;
396
- if (state.pauseEventDigest !== pauseEventDigest) {
397
- state.pauseEventDigest = pauseEventDigest;
398
- state.revision += 1;
399
- await saveState(paths.path, state, assertOwned);
400
- }
401
- return { status: "paused-job", blocked: false };
402
- });
403
- } catch (error) {
404
- return { status: "degraded-pause", blocked: false, reason: error.message };
405
- }
406
- }
407
-
408
- export async function verifyDeliveryStop({ root, host, sessionId, scope, eventId = null }) {
409
- const material = laneMaterial({ host, sessionId, scope });
410
- if (!material) return { status: "not-applicable", blocked: false };
411
- const laneDigest = sha256(material);
412
- const paths = await statePaths(root, laneDigest);
413
- try {
414
- return await withOwnedFileLock(paths.lockPath, async () => {
415
- const state = await readState(paths.path, laneDigest);
416
- const pauseEventDigest = typeof eventId === "string" && eventId ? sha256(`event\0${eventId}`) : null;
417
- if (state.conflict) {
418
- return { status: "blocked", blocked: true,
419
- reason: "AgentSpine cannot verify tool history because one tool delivery ID had conflicting results." };
420
- }
421
- if (state.pendingWriteIntents.length) {
422
- return { status: "blocked", blocked: true, reason: unresolvedIntentReason(state) };
423
- }
424
- if (pauseEventDigest && state.pauseEventDigest === pauseEventDigest) {
425
- return { status: "paused-job", blocked: false, stateDigest: state.integrityDigest };
426
- }
427
- if (state.lastWrite && state.verifiedWriteDigest !== state.lastWrite.eventDigest) {
428
- return { status: "blocked", blocked: true,
429
- reason: "AgentSpine cannot accept this delivery: run a successful test after the latest write "
430
- + `(node --test, npm test, npm run check, or pytest). ${TEST_PROOF_GUIDANCE}` };
431
- }
432
- return { status: state.lastWrite ? "verified" : "no-write", blocked: false,
433
- testFamily: state.lastTest?.family || null, stateDigest: state.integrityDigest };
434
- });
435
- } catch (error) {
436
- return { status: "blocked", blocked: true,
437
- reason: `AgentSpine cannot verify post-write tests: ${String(error.message).slice(0, 400)}` };
438
- }
439
- }
440
-
441
- export async function deliveryVerificationPath({ root, host, sessionId, scope }) {
442
- const material = laneMaterial({ host, sessionId, scope });
443
- if (!material) return null;
444
- return (await statePaths(root, sha256(material))).path;
445
- }
@@ -1,239 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { lstat, opendir, readFile, realpath, stat } from "node:fs/promises";
3
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
- import { recordHookScanAudit } from "./hook-audit.js";
5
- import { skippableTraversalError } from "./source-tree-scan.js";
6
-
7
- const SKIP_DIRS = new Set([
8
- ".git", ".hg", ".svn", ".next", ".nuxt", ".turbo", ".venv",
9
- "build", "coverage", "dist", "node_modules", "target", "vendor"
10
- ]);
11
-
12
- const RULE_NAMES = new Set([
13
- "AGENTS.md", "AGENTS.override.md", "CLAUDE.md", "CLAUDE.local.md",
14
- "GEMINI.md", "CONSTITUTION.md", "RULES.md"
15
- ]);
16
-
17
- const MEMORY_NAMES = new Set(["MEMORY.md"]);
18
- const SOUL_RE = /(^|[_-])(soul|persona|voice)([_-]|\.)/i;
19
- const MEMORY_PATH_RE = /(^|\/)(memory|memories)(\/|$)/i;
20
- const DOCUMENT_CONTENT = new WeakMap();
21
-
22
- function sha256(buffer) {
23
- return createHash("sha256").update(buffer).digest("hex");
24
- }
25
-
26
- function classify(relativePath) {
27
- const name = basename(relativePath);
28
- if (RULE_NAMES.has(name)) return { layer: "constitution", protected: true };
29
- if (MEMORY_NAMES.has(name)) return { layer: "memory-index", protected: true };
30
- if (SOUL_RE.test(name) || name === "SOUL.md") return { layer: "soul", protected: true };
31
- if (MEMORY_PATH_RE.test(relativePath)) return { layer: "memory-fact", protected: true };
32
- return { layer: "reference", protected: false };
33
- }
34
-
35
- function authorityFor(layer) {
36
- if (layer === "constitution") return "host-instruction-candidate";
37
- return "context-only";
38
- }
39
-
40
- function hostsFor(name) {
41
- if (name === "AGENTS.md" || name === "AGENTS.override.md") return ["codex"];
42
- if (name === "CLAUDE.md" || name === "CLAUDE.local.md") return ["claude"];
43
- if (name === "GEMINI.md") return ["gemini"];
44
- return ["generic"];
45
- }
46
-
47
- export function documentSnapshotContent(document) {
48
- const value = DOCUMENT_CONTENT.get(document);
49
- return value ? Buffer.from(value) : null;
50
- }
51
-
52
- export function attachDocumentSnapshot(document, buffer) {
53
- if (buffer) DOCUMENT_CONTENT.set(document, Buffer.from(buffer));
54
- return document;
55
- }
56
-
57
- export function markdownOutsideCode(text) {
58
- let fence = null;
59
- return String(text).split(/\r?\n/).map((line) => {
60
- const marker = line.match(/^\s{0,3}(`{3,}|~{3,})/)?.[1] || null;
61
- if (!fence && marker) { fence = marker[0]; return ""; }
62
- if (fence && marker?.[0] === fence) { fence = null; return ""; }
63
- if (fence) return "";
64
- return line.replace(/`+[^`\n]*`+/g, "");
65
- }).join("\n");
66
- }
67
-
68
- export async function indexExplicitDocuments(entries) {
69
- const documents = [];
70
- for (const entry of entries) {
71
- let path;
72
- let metadata;
73
- let buffer;
74
- if (entry.snapshot) {
75
- path = entry.snapshot.path;
76
- metadata = entry.snapshot.metadata;
77
- buffer = Buffer.from(entry.snapshot.buffer);
78
- if (buffer.byteLength !== metadata.bytes || sha256(buffer) !== metadata.sha256) {
79
- throw new Error(`source snapshot integrity failed: ${entry.id}`);
80
- }
81
- } else {
82
- const supplied = await lstat(entry.path);
83
- if (supplied.isSymbolicLink() || !supplied.isFile()) throw new Error(`source is not a regular non-symlink file: ${entry.id}`);
84
- path = await realpath(entry.path);
85
- metadata = await lstat(path);
86
- if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error(`source is not a regular non-symlink file: ${entry.id}`);
87
- buffer = await readFile(path);
88
- }
89
- if (buffer.byteLength > (entry.maxBytes || 4 * 1024 * 1024)) throw new Error(`source exceeds its byte limit: ${entry.id}`);
90
- const classification = classify(entry.id);
91
- const document = {
92
- path,
93
- relativePath: entry.id,
94
- name: basename(path),
95
- ...classification,
96
- layer: entry.layer || classification.layer,
97
- protected: entry.protected ?? classification.protected,
98
- authority: authorityFor(entry.layer || classification.layer),
99
- classificationSource: "host-native-source-binding",
100
- hosts: [entry.host],
101
- bytes: buffer.byteLength,
102
- modifiedAt: entry.snapshot ? metadata.modifiedAt : metadata.mtime.toISOString(),
103
- sha256: entry.snapshot ? metadata.sha256 : sha256(buffer),
104
- links: [],
105
- sourceScope: entry.scope,
106
- sourceBinding: entry.binding,
107
- precedence: entry.precedence,
108
- relevance: entry.relevance || null
109
- };
110
- attachDocumentSnapshot(document, entry.snapshot ? buffer : null);
111
- documents.push(document);
112
- }
113
- return documents;
114
- }
115
-
116
- export function extractMarkdownLinks(text, filePath, root) {
117
- const links = new Set();
118
- text = markdownOutsideCode(text);
119
- const patterns = [
120
- /\[[^\]]*\]\(([^)]+\.md)(?:#[^)]+)?\)/gi,
121
- /(?:^|\s)@([^\s`'\"]+\.md)(?:\s|$)/gim
122
- ];
123
- for (const pattern of patterns) {
124
- for (const match of text.matchAll(pattern)) {
125
- const raw = match[1].trim().replace(/^<|>$/g, "");
126
- if (/^[a-z]+:/i.test(raw)) continue;
127
- let decoded = raw;
128
- try { decoded = decodeURIComponent(raw); } catch { /* Keep malformed URLs visible instead of failing the scan. */ }
129
- const target = resolve(dirname(filePath), decoded);
130
- const rel = relative(root, target).replaceAll("\\", "/");
131
- if (!rel.startsWith("../") && rel !== "..") links.add(rel);
132
- }
133
- }
134
- return [...links].sort();
135
- }
136
-
137
- function isInside(parent, child) {
138
- const value = relative(parent, child);
139
- return value === "" || (!isAbsolute(value) && !value.startsWith(`..${sep}`) && value !== "..");
140
- }
141
-
142
- async function walk(directory, found, excludedRoots, env) {
143
- let stream;
144
- try {
145
- stream = await opendir(directory);
146
- } catch (error) {
147
- if (!skippableTraversalError(error)) throw error;
148
- await recordHookScanAudit({
149
- event: "CatalogScan", phase: "document-discovery", error,
150
- path: error.path || directory, operation: "opendir", env
151
- });
152
- return;
153
- }
154
- const entries = [];
155
- try {
156
- for await (const entry of stream) entries.push(entry);
157
- } catch (error) {
158
- if (!skippableTraversalError(error)) throw error;
159
- await recordHookScanAudit({
160
- event: "CatalogScan", phase: "document-discovery", error,
161
- path: error.path || directory, operation: "readdir", env
162
- });
163
- return;
164
- }
165
- entries.sort((a, b) => a.name.localeCompare(b.name));
166
- for (const entry of entries) {
167
- if (entry.isSymbolicLink()) continue;
168
- const fullPath = join(directory, entry.name);
169
- if (entry.isDirectory()) {
170
- if (!SKIP_DIRS.has(entry.name) && !excludedRoots.some((root) => isInside(root, fullPath))) {
171
- await walk(fullPath, found, excludedRoots, env);
172
- }
173
- } else if (entry.isFile() && extname(entry.name).toLowerCase() === ".md") {
174
- found.push(fullPath);
175
- }
176
- }
177
- }
178
-
179
- export async function discoverDocuments(root, { excludeRoots = [], env = process.env } = {}) {
180
- const files = [];
181
- // Canonicalize existing exclusion roots just like the scanned root. On macOS
182
- // temporary directories commonly cross /var -> /private/var, while Windows
183
- // may expose the same directory through differently cased/normalized paths.
184
- // Comparing only resolved spellings would therefore walk the private state
185
- // directory even though it is the configured exclusion boundary.
186
- const excludedRoots = (await Promise.all(excludeRoots.map(async (path) => {
187
- try { return await realpath(resolve(path)); } catch (error) {
188
- if (error.code === "ENOENT") return resolve(path);
189
- throw error;
190
- }
191
- }))).filter((path) => isInside(root, path));
192
- await walk(root, files, excludedRoots, env);
193
- const documents = new Array(files.length);
194
- let cursor = 0;
195
- async function worker() {
196
- while (cursor < files.length) {
197
- const index = cursor++;
198
- const path = files[index];
199
- const [buffer, metadata] = await Promise.all([readFile(path), stat(path)]);
200
- const relativePath = relative(root, path).replaceAll("\\", "/");
201
- const classification = classify(relativePath);
202
- documents[index] = {
203
- path,
204
- relativePath,
205
- name: basename(path),
206
- ...classification,
207
- authority: authorityFor(classification.layer),
208
- classificationSource: "filename-and-path-hint",
209
- hosts: hostsFor(basename(path)),
210
- bytes: buffer.byteLength,
211
- modifiedAt: metadata.mtime.toISOString(),
212
- sha256: sha256(buffer),
213
- links: extractMarkdownLinks(buffer.toString("utf8"), path, root)
214
- };
215
- }
216
- }
217
- const concurrency = Math.max(1, Math.min(16, files.length));
218
- await Promise.all(Array.from({ length: concurrency }, () => worker()));
219
-
220
- const byPath = new Map(documents.map((document) => [document.relativePath, document]));
221
- const queue = documents.filter((document) => document.protected);
222
- const visited = new Set(queue.map((document) => document.relativePath));
223
- while (queue.length) {
224
- const current = queue.shift();
225
- for (const linkedPath of current.links) {
226
- const linked = byPath.get(linkedPath);
227
- if (linked && !visited.has(linkedPath)) {
228
- linked.protected = true;
229
- visited.add(linkedPath);
230
- queue.push(linked);
231
- }
232
- }
233
- }
234
- return documents;
235
- }
236
-
237
- export function isRuleDocument(name) {
238
- return RULE_NAMES.has(name);
239
- }