blun-king-cli 9.1.643 → 9.1.644

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 (266) hide show
  1. package/LIESMICH.txt +18 -0
  2. package/README.md +20 -6
  3. package/bin/blun.js +3 -3
  4. package/bin/king.js +3 -3
  5. package/bin/launcher-mode.js +125 -126
  6. package/bin/launcher-runtime.js +603 -616
  7. package/bin/plugin-bootstrap.js +339 -405
  8. package/bin/rename-private-staging.cjs +2 -2
  9. package/bin/retired-bundled-plugins.cjs +84 -0
  10. package/bin/startup-security-host.cjs +105 -0
  11. package/bin/startup-security.cjs +9 -105
  12. package/bin/startup-warning-policy.cjs +22 -0
  13. package/bin/update-lease-installer.cjs +125 -0
  14. package/bin/update-lease-sockets.cjs +228 -0
  15. package/bin/update-lease.js +22 -327
  16. package/bin/verify-bundled-agent-sources.cjs +2 -4
  17. package/blun.mjs +18 -179
  18. package/bundled-agent-sources.json +1 -552
  19. package/package.json +1 -5
  20. package/tool-liveness642/receipt.json +1 -1
  21. package/worker-host.mjs +3 -119
  22. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  23. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  24. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  25. package/agent-spine-plugin/.mcp.json +0 -8
  26. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  27. package/agent-spine-plugin/LICENSE +0 -186
  28. package/agent-spine-plugin/README.md +0 -432
  29. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  30. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  31. package/agent-spine-plugin/bin/agentspine.js +0 -7
  32. package/agent-spine-plugin/blun.plugin.json +0 -68
  33. package/agent-spine-plugin/docs/acceptance.md +0 -61
  34. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  35. package/agent-spine-plugin/docs/host-integration.md +0 -193
  36. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  37. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  38. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  39. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  40. package/agent-spine-plugin/docs/source-roots.md +0 -113
  41. package/agent-spine-plugin/docs/world-model.md +0 -119
  42. package/agent-spine-plugin/hooks/codex.json +0 -47
  43. package/agent-spine-plugin/hooks/hooks.json +0 -106
  44. package/agent-spine-plugin/hooks/version.json +0 -5
  45. package/agent-spine-plugin/package.json +0 -77
  46. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  47. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  48. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  49. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  50. package/agent-spine-plugin/scripts/check-install.js +0 -478
  51. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  52. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  53. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  54. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  55. package/agent-spine-plugin/scripts/release-check.js +0 -150
  56. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  57. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  58. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  59. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  60. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  61. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  62. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  63. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  64. package/agent-spine-plugin/src/cli-agent.js +0 -315
  65. package/agent-spine-plugin/src/cli-attention.js +0 -95
  66. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  67. package/agent-spine-plugin/src/cli-common.js +0 -71
  68. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  69. package/agent-spine-plugin/src/cli-core.js +0 -128
  70. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  71. package/agent-spine-plugin/src/cli-host.js +0 -21
  72. package/agent-spine-plugin/src/cli-learning.js +0 -320
  73. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  74. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  75. package/agent-spine-plugin/src/cli.js +0 -181
  76. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  77. package/agent-spine-plugin/src/hook.js +0 -500
  78. package/agent-spine-plugin/src/index.js +0 -108
  79. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  80. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  81. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  82. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  83. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  84. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  85. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  86. package/agent-spine-plugin/src/lib/attention.js +0 -164
  87. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  88. package/agent-spine-plugin/src/lib/audit.js +0 -401
  89. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  90. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  91. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  92. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  93. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  94. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  95. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  96. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  97. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  98. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  99. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  100. package/agent-spine-plugin/src/lib/context.js +0 -156
  101. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  102. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  103. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  104. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  105. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  106. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  107. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  108. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  109. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  110. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  111. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  112. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  113. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  114. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  115. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  116. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  117. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  118. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  119. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  120. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  121. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  122. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  123. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  124. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  125. package/agent-spine-plugin/src/lib/documents.js +0 -239
  126. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  127. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  128. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  129. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  130. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  131. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  132. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  133. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  134. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  135. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  136. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  137. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  138. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  139. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  140. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  141. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  142. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  143. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  144. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  145. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  146. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  147. package/agent-spine-plugin/src/lib/graph.js +0 -337
  148. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  149. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  150. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  151. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  152. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  153. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  154. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  155. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  156. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  157. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  158. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  159. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  160. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  161. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  162. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  163. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  164. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  165. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  166. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  167. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  168. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  169. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  170. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  171. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  172. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  173. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  174. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  175. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  176. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  177. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  178. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  179. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  180. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  181. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  182. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  183. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  184. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  185. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  186. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  187. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  188. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  189. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  190. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  191. package/agent-spine-plugin/src/lib/learning.js +0 -36
  192. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  193. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  194. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  195. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  196. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  197. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  198. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  199. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  200. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  201. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  202. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  203. package/agent-spine-plugin/src/lib/paths.js +0 -109
  204. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  205. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  206. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  207. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  208. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  209. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  210. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  211. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  212. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  213. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  214. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  215. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  216. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  217. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  218. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  219. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  220. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  221. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  224. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  225. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  226. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  227. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  228. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  229. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  230. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  231. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  232. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  233. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  234. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  235. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  236. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  237. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  238. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  239. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  240. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  241. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  242. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  243. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  244. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  245. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  246. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  247. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  248. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  249. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  250. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  251. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  252. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  253. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  254. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  255. package/agent-spine-plugin/src/mcp.js +0 -456
  256. package/agent-spine-plugin/src/version.js +0 -1
  257. package/agent-spine-plugin/src/worker.js +0 -257
  258. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  259. package/bin/agentspine-king-goal-intake.mjs +0 -106
  260. package/bin/agentspine-king-host-runner.mjs +0 -109
  261. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  262. package/bin/agentspine-king-status-policy.mjs +0 -226
  263. package/bin/agentspine-king-worker-host.mjs +0 -160
  264. package/bin/managed-plugin-selection.cjs +0 -141
  265. package/bin/verify-agent-behavior.cjs +0 -122
  266. package/bin/verify-agent-components.cjs +0 -104
@@ -1,475 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { homedir } from "node:os";
3
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
- import { lstat, mkdir, open, readFile, stat, unlink, writeFile } from "node:fs/promises";
5
- import { ancestorsBetween, canonicalPath, isInside, stateRoot } from "./paths.js";
6
- import { indexExplicitDocuments } from "./documents.js";
7
- import { isFileLockContention, replaceFileWithRetry } from "./filesystem-retry.js";
8
- import { purgeIndexedMemoryCache, resolveIndexedMemory } from "./indexed-memory.js";
9
- import { hookMemoryQuery, loadLessonRecallSelection, rememberLessonRecallSelection } from "./lesson-recall-session.js";
10
- import { catalogScanPolicy } from "./catalog.js";
11
- import { isKingHost, KING_SOURCE_BYTES } from "./host-instruction-budget.js";
12
- import {
13
- SOURCE_SCAN_INCOMPLETE, boundedMarkdownTree, existingDirectory, existingRegular, sourceScanError
14
- } from "./source-tree-scan.js";
15
-
16
- export const SOURCE_REGISTRY_SCHEMA = "agentspine.source-roots/v1";
17
- const MAX_REGISTRY_BYTES = 1024 * 1024;
18
- const MAX_SOURCES = 256;
19
- const MAX_RULE_FILES = 128;
20
- const MAX_PROJECT_FILES = 240;
21
- const MAX_TOTAL_SOURCE_BYTES = 8 * 1024 * 1024;
22
- const MAX_DIRECTORY_ENTRIES = 4096;
23
- const MAX_PROJECT_DIRECTORY_ENTRIES = 8192;
24
- const SOURCE_RESOLUTION_MS = 2000;
25
- const SAFE_NAME = /^[A-Za-z0-9._-]{1,128}$/;
26
-
27
- function digest(value) { return createHash("sha256").update(value).digest("hex"); }
28
- async function partitionSources(sources, env) {
29
- if (!isKingHost(env)) return { sources, unverified: [] };
30
- const loaded = [], unverified = []; let used = 0;
31
- for (const source of sources) {
32
- if (!source.id.startsWith("codex:")) { loaded.push(source); continue; }
33
- const bytes = (await lstat(source.path)).size, limit = source.maxBytes || KING_SOURCE_BYTES;
34
- const total = bytes <= limit && used + bytes > MAX_TOTAL_SOURCE_BYTES;
35
- if (bytes <= limit && !total) { loaded.push(source); used += bytes; continue; }
36
- const ceiling = total ? MAX_TOTAL_SOURCE_BYTES : limit;
37
- const message = `King rule ${source.id} (${bytes} bytes) exceeds AgentSpine's ${ceiling}-byte ${total ? "total " : ""}reader budget; AgentSpine did not load or verify it. Native rules apply. Continue; no retry.`;
38
- unverified.push({ id: source.id, path: source.path, bytes, message });
39
- }
40
- return { sources: loaded, unverified };
41
- }
42
- function registryPath(env = process.env) { return join(stateRoot(env), "source-roots.json"); }
43
- function emptyRegistry() { return { schema: SOURCE_REGISTRY_SCHEMA, revision: 0, bindings: [], history: [] }; }
44
-
45
- function normalizeRegistry(value) {
46
- if (!value || value.schema !== SOURCE_REGISTRY_SCHEMA || !Number.isInteger(value.revision)
47
- || !Array.isArray(value.bindings) || !Array.isArray(value.history)) {
48
- throw new Error("source-root registry is corrupt; host-native recall is disabled until repaired");
49
- }
50
- for (const binding of value.bindings) {
51
- if (!binding || typeof binding.id !== "string" || !["all", "claude", "codex"].includes(binding.host)
52
- || !["project-memory", "state-user"].includes(binding.scope) || typeof binding.profileKey !== "string"
53
- || typeof binding.projectRoot !== "string" || typeof binding.sourceRoot !== "string"
54
- || typeof binding.provenance !== "string" || typeof binding.active !== "boolean"
55
- || binding.authority !== "context-only") throw new Error("source-root registry contains an unsafe binding");
56
- }
57
- if (value.history.some((item) => !item || item.authority !== "context-only")) {
58
- throw new Error("source-root registry history contains an authority violation");
59
- }
60
- return value;
61
- }
62
-
63
- async function readRegistry(env = process.env) {
64
- const path = registryPath(env);
65
- try {
66
- const metadata = await stat(path);
67
- if (metadata.size > MAX_REGISTRY_BYTES) throw new Error("source-root registry exceeds 1 MiB");
68
- return { registry: normalizeRegistry(JSON.parse(await readFile(path, "utf8"))), path };
69
- } catch (error) {
70
- if (error.code !== "ENOENT") throw error;
71
- return { registry: emptyRegistry(), path };
72
- }
73
- }
74
-
75
- async function mutateRegistry(task, env = process.env) {
76
- const path = registryPath(env);
77
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
78
- const lock = `${path}.lock`;
79
- let handle;
80
- for (let attempt = 0; attempt < 80; attempt += 1) {
81
- try { handle = await open(lock, "wx", 0o600); break; } catch (error) {
82
- if (!isFileLockContention(error)) throw error;
83
- await new Promise((done) => setTimeout(done, 25));
84
- }
85
- }
86
- if (!handle) throw new Error("source-root registry is busy; retry shortly");
87
- try {
88
- const { registry } = await readRegistry(env);
89
- const result = await task(registry);
90
- registry.revision += 1;
91
- const content = `${JSON.stringify(registry, null, 2)}\n`;
92
- if (Buffer.byteLength(content) > MAX_REGISTRY_BYTES) throw new Error("source-root registry exceeds 1 MiB");
93
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
94
- await writeFile(temporary, content, { mode: 0o600 });
95
- await replaceFileWithRetry(temporary, path);
96
- return { ...result, registryPath: path, revision: registry.revision };
97
- } finally {
98
- await handle.close();
99
- await unlink(lock).catch((error) => { if (error.code !== "ENOENT") throw error; });
100
- }
101
- }
102
-
103
- function expandHome(value, home) {
104
- if (value === "~") return home;
105
- if (value.startsWith("~/") || value.startsWith("~\\")) return join(home, value.slice(2));
106
- return value;
107
- }
108
-
109
- function samePath(left, right) {
110
- const normalize = (value) => resolve(value).replace(/[\\/]+$/, "");
111
- const a = normalize(left);
112
- const b = normalize(right);
113
- return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
114
- }
115
-
116
- async function homeRoots(env) {
117
- const candidates = [homedir(), env.HOME, env.USERPROFILE,
118
- env.HOMEDRIVE && env.HOMEPATH ? `${env.HOMEDRIVE}${env.HOMEPATH}` : null]
119
- .filter((value) => typeof value === "string" && value && isAbsolute(value));
120
- return [...new Set(await Promise.all(candidates.map(async (value) =>
121
- await existingDirectory(value) || resolve(value))))];
122
- }
123
-
124
- async function readJsonObject(path) {
125
- const file = await existingRegular(path);
126
- if (!file) return null;
127
- const metadata = await stat(file);
128
- if (metadata.size > 1024 * 1024) throw new Error(`host settings exceed 1 MiB: ${basename(path)}`);
129
- const value = JSON.parse(await readFile(file, "utf8"));
130
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`host settings are not an object: ${basename(path)}`);
131
- return value;
132
- }
133
-
134
- function parseTomlArray(text, key) {
135
- const match = text.match(new RegExp(`^\\s*${key}\\s*=\\s*\\[([^\\]]*)\\]`, "m"));
136
- if (!match) return null;
137
- const values = [];
138
- for (const item of match[1].matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)) {
139
- const value = item[1] === undefined ? item[2] : JSON.parse(`"${item[1]}"`);
140
- if (!SAFE_NAME.test(value) || value.includes("/") || value.includes("\\")) throw new Error(`unsafe ${key} entry`);
141
- values.push(value);
142
- }
143
- return values;
144
- }
145
-
146
- async function codexConfig(home) {
147
- const path = join(home, "config.toml");
148
- const file = await existingRegular(path);
149
- if (!file) return { fallbackNames: [], rootMarkers: [".git"], maxBytes: 32768 };
150
- const metadata = await stat(file);
151
- if (metadata.size > 1024 * 1024) throw new Error("Codex config exceeds 1 MiB");
152
- const text = await readFile(file, "utf8");
153
- const bytes = Number(text.match(/^\s*project_doc_max_bytes\s*=\s*(\d+)/m)?.[1] || 32768);
154
- return {
155
- fallbackNames: parseTomlArray(text, "project_doc_fallback_filenames") || [],
156
- rootMarkers: parseTomlArray(text, "project_root_markers") || [".git"],
157
- maxBytes: Number.isInteger(bytes) && bytes >= 1024 && bytes <= 4 * 1024 * 1024 ? bytes : 32768
158
- };
159
- }
160
-
161
- async function findRoot(cwd, markers) {
162
- let cursor = cwd;
163
- while (true) {
164
- for (const marker of markers) {
165
- try { await lstat(join(cursor, marker)); return { root: cursor, resolution: "project-marker" }; } catch (error) {
166
- if (error.code !== "ENOENT") throw sourceScanError(error);
167
- }
168
- }
169
- const parent = dirname(cursor);
170
- if (parent === cursor) return { root: cwd, resolution: "cwd-fallback" };
171
- cursor = parent;
172
- }
173
- }
174
-
175
- async function addFile(output, path, metadata) {
176
- const file = await existingRegular(path);
177
- if (file) output.push({ path: file, ...metadata });
178
- }
179
-
180
- function profileKey(host, hostHome) { return `${host}:${digest(hostHome).slice(0, 24)}`; }
181
-
182
- function activeBinding(registry, host, hostHome, projectRoot, scope) {
183
- const targetRoot = scope === "state-user" ? "*" : projectRoot;
184
- return registry.bindings.find((item) => item.active && (item.host === host || item.host === "all")
185
- && (item.host === "all" || item.profileKey === profileKey(host, hostHome))
186
- && item.projectRoot === targetRoot && item.scope === scope) || null;
187
- }
188
-
189
- async function rememberRuntimeBinding({ host, hostHome, projectRoot, sourceRoot, scope, provenance, env }) {
190
- const canonicalSource = await canonicalPath(sourceRoot);
191
- return mutateRegistry((registry) => {
192
- const key = host === "all" ? "all:local-user" : profileKey(host, hostHome);
193
- const targetRoot = scope === "state-user" ? "*" : projectRoot;
194
- const current = registry.bindings.find((item) => item.active && item.host === host
195
- && item.profileKey === key && item.projectRoot === targetRoot && item.scope === scope);
196
- if (current?.sourceRoot === canonicalSource) return { binding: current, unchanged: true };
197
- if (current && current.sourceRoot !== canonicalSource) throw new Error(`conflicting ${host} ${scope} source binding; inspect or roll back the registry`);
198
- const binding = {
199
- id: `binding:${randomUUID()}`, host, profileKey: key, projectRoot: targetRoot, sourceRoot: canonicalSource,
200
- scope, provenance, active: true, createdAt: new Date().toISOString(), authority: "context-only"
201
- };
202
- registry.bindings.push(binding);
203
- registry.history.push({ kind: "bound", bindingId: binding.id, at: binding.createdAt, provenance, authority: "context-only" });
204
- return { binding, unchanged: false };
205
- }, env);
206
- }
207
-
208
- export async function bindSourceRoot({ host, hostHome, projectRoot, sourceRoot, scope = "state-user", confirmation, env = process.env }) {
209
- if (confirmation !== "local-user-confirmed") throw new Error("source binding requires explicit local user confirmation");
210
- if (!["claude", "codex", "all"].includes(host) || !["project-memory", "state-user"].includes(scope)
211
- || (host === "all" && scope !== "state-user")) throw new Error("invalid source binding scope");
212
- return rememberRuntimeBinding({ host, hostHome: host === "all" ? "local-user" : await canonicalPath(hostHome), projectRoot: await canonicalPath(projectRoot),
213
- sourceRoot, scope, provenance: "local-user-confirmed", env });
214
- }
215
-
216
- export async function rollbackSourceBinding({ id, confirmation, env = process.env }) {
217
- if (confirmation !== "local-user-confirmed") throw new Error("source binding rollback requires explicit local user confirmation");
218
- const result = await mutateRegistry((registry) => {
219
- const binding = registry.bindings.find((item) => item.id === id && item.active);
220
- if (!binding) throw new Error(`active source binding not found: ${id}`);
221
- binding.active = false;
222
- binding.rolledBackAt = new Date().toISOString();
223
- registry.history.push({ kind: "rolled-back", bindingId: id, at: binding.rolledBackAt, authority: "context-only" });
224
- return { binding };
225
- }, env);
226
- if (result.binding.scope === "project-memory") await purgeIndexedMemoryCache(result.binding.sourceRoot, env);
227
- return result;
228
- }
229
-
230
- export async function purgeSourceBinding({ id, confirmation, env = process.env }) {
231
- if (confirmation !== "local-user-confirmed") throw new Error("source binding purge requires explicit local user confirmation");
232
- const result = await mutateRegistry((registry) => {
233
- const removed = registry.bindings.find((item) => item.id === id);
234
- const before = registry.bindings.length;
235
- registry.bindings = registry.bindings.filter((item) => item.id !== id);
236
- if (registry.bindings.length === before) throw new Error(`source binding not found: ${id}`);
237
- registry.history.push({ kind: "purged", bindingDigest: digest(id), at: new Date().toISOString(), authority: "context-only" });
238
- return { purged: true, removed };
239
- }, env);
240
- if (result.removed?.scope === "project-memory") await purgeIndexedMemoryCache(result.removed.sourceRoot, env);
241
- return { ...result, removed: undefined };
242
- }
243
-
244
- export async function inspectSourceRegistry(env = process.env) {
245
- const { registry, path } = await readRegistry(env);
246
- return { registry, registryPath: path };
247
- }
248
-
249
- async function claudeSources({ cwd, projectRoot, configDir, input, env, registry, deadline, memoryHooks }) {
250
- const sources = [];
251
- const skipped = [];
252
- await addFile(sources, join(configDir, "CLAUDE.md"), { id: "claude:user/CLAUDE.md", host: "claude", scope: "user", binding: "CLAUDE_CONFIG_DIR", precedence: 100 });
253
- sources.push(...await boundedMarkdownTree(join(configDir, "rules"), "claude:user/rules", "claude", "user", 110, deadline,
254
- { maxFiles: MAX_RULE_FILES, maxDirectoryEntries: MAX_DIRECTORY_ENTRIES, skipped, timeoutMs: SOURCE_RESOLUTION_MS }));
255
- let precedence = 1000;
256
- for (const directory of ancestorsBetween(projectRoot, cwd)) {
257
- for (const name of ["CLAUDE.md", "CLAUDE.local.md"]) {
258
- await addFile(sources, join(directory, name), { id: `claude:project/${relative(projectRoot, join(directory, name)).replaceAll("\\", "/")}`,
259
- host: "claude", scope: "project", binding: "native-project-chain", precedence: precedence++ });
260
- }
261
- await addFile(sources, join(directory, ".claude", "CLAUDE.md"), { id: `claude:project/${relative(projectRoot, join(directory, ".claude", "CLAUDE.md")).replaceAll("\\", "/")}`,
262
- host: "claude", scope: "project", binding: "native-project-chain", precedence: precedence++ });
263
- }
264
- sources.push(...await boundedMarkdownTree(join(projectRoot, ".claude", "rules"), "claude:project/.claude/rules", "claude", "project", precedence, deadline,
265
- { maxFiles: MAX_RULE_FILES, maxDirectoryEntries: MAX_DIRECTORY_ENTRIES, skipped, timeoutMs: SOURCE_RESOLUTION_MS }));
266
-
267
- let memoryRoot = null;
268
- let memoryProvenance = null;
269
- for (const path of [join(configDir, "settings.json"), join(projectRoot, ".claude", "settings.json"), join(projectRoot, ".claude", "settings.local.json")]) {
270
- const value = await readJsonObject(path);
271
- if (typeof value?.autoMemoryDirectory === "string") {
272
- const expanded = expandHome(value.autoMemoryDirectory, homedir());
273
- if (!isAbsolute(expanded)) throw new Error("autoMemoryDirectory must be absolute or home-relative");
274
- memoryRoot = await existingDirectory(expanded);
275
- memoryProvenance = "autoMemoryDirectory";
276
- }
277
- }
278
- if (!memoryRoot && typeof env.CLAUDE_CODE_PROJECT_DIR_NAME === "string" && SAFE_NAME.test(env.CLAUDE_CODE_PROJECT_DIR_NAME)) {
279
- memoryRoot = await existingDirectory(join(configDir, "projects", env.CLAUDE_CODE_PROJECT_DIR_NAME, "memory"));
280
- memoryProvenance = "CLAUDE_CODE_PROJECT_DIR_NAME";
281
- }
282
- const transcript = input.transcript_path || input.transcriptPath;
283
- if (!memoryRoot && typeof transcript === "string" && isAbsolute(transcript)) {
284
- const transcriptFile = await existingRegular(transcript);
285
- const projectsRoot = await existingDirectory(join(configDir, "projects"));
286
- if (transcriptFile && projectsRoot && isInside(projectsRoot, transcriptFile)) {
287
- memoryRoot = await existingDirectory(join(dirname(transcriptFile), "memory"));
288
- memoryProvenance = "host-hook-transcript";
289
- }
290
- }
291
- if (memoryRoot) {
292
- await rememberRuntimeBinding({ host: "claude", hostHome: configDir, projectRoot, sourceRoot: memoryRoot,
293
- scope: "project-memory", provenance: memoryProvenance, env });
294
- } else {
295
- memoryRoot = activeBinding(registry, "claude", configDir, projectRoot, "project-memory")?.sourceRoot || null;
296
- memoryProvenance = memoryRoot ? "source-root-registry" : null;
297
- }
298
- let memoryDiagnostics = null;
299
- if (memoryRoot) {
300
- const supplied = input.agent_spine_scope && typeof input.agent_spine_scope === "object"
301
- ? input.agent_spine_scope : input;
302
- let recall = { status: "empty", paths: [], authority: "context-only" };
303
- try {
304
- recall = await loadLessonRecallSelection({ root: projectRoot, input, now: input.timestamp || new Date() });
305
- } catch (error) {
306
- recall = { status: "degraded", paths: [], reason: error.message, authority: "context-only" };
307
- }
308
- const resolved = await resolveIndexedMemory({
309
- root: memoryRoot, env, hooks: memoryHooks, deadline,
310
- scope: {
311
- entityId: supplied.entity_id ?? supplied.entityId ?? null,
312
- groupId: supplied.group_id ?? supplied.groupId ?? null,
313
- projectId: supplied.project_id ?? supplied.projectId ?? null,
314
- currentTaskId: supplied.task_id ?? supplied.currentTaskId ?? null,
315
- prompt: hookMemoryQuery(input),
316
- pinnedPaths: recall.paths
317
- }
318
- });
319
- let recorded = { status: "not-recorded", paths: [], authority: "context-only" };
320
- try {
321
- recorded = await rememberLessonRecallSelection({ root: projectRoot, input,
322
- sources: resolved.sources, now: input.timestamp || new Date() });
323
- } catch (error) {
324
- recorded = { status: "degraded", paths: [], reason: error.message, authority: "context-only" };
325
- }
326
- memoryDiagnostics = { ...resolved.diagnostics, recall: {
327
- restored: recall.paths.length, loadStatus: recall.status, recordStatus: recorded.status,
328
- recorded: recorded.paths.length, authority: "context-only"
329
- } };
330
- for (const item of resolved.sources) {
331
- sources.push({
332
- path: item.path, id: `claude:memory/${item.relativePath}`, host: "claude", scope: "project-memory",
333
- binding: "host-native-memory-index", precedence: 2000 + sources.length,
334
- snapshot: item.snapshot, relevance: item.relevance
335
- });
336
- }
337
- }
338
- return { sources, memoryRoot, memoryProvenance, memoryDiagnostics, skipped };
339
- }
340
-
341
- async function codexSources({ cwd, projectRoot, codexHome, config }) {
342
- const sources = [];
343
- for (const name of ["AGENTS.override.md", "AGENTS.md"]) {
344
- const file = await existingRegular(join(codexHome, name));
345
- if (file && (await stat(file)).size > 0) {
346
- sources.push({ path: file, id: `codex:user/${name}`, host: "codex", scope: "user", binding: "CODEX_HOME", precedence: 100, maxBytes: config.maxBytes });
347
- break;
348
- }
349
- }
350
- let precedence = 1000;
351
- for (const directory of ancestorsBetween(projectRoot, cwd)) {
352
- for (const name of ["AGENTS.override.md", "AGENTS.md", ...config.fallbackNames]) {
353
- const file = await existingRegular(join(directory, name));
354
- if (file && (await stat(file)).size > 0) {
355
- sources.push({ path: file, id: `codex:project/${relative(projectRoot, file).replaceAll("\\", "/")}`,
356
- host: "codex", scope: "project", binding: "native-project-chain", precedence: precedence++, maxBytes: config.maxBytes });
357
- break;
358
- }
359
- }
360
- }
361
- return sources;
362
- }
363
-
364
- export async function resolveHostSourceCatalog({ host, cwd = process.cwd(), input = {}, env = process.env, memoryHooks = {} } = {}) {
365
- if (!["claude", "codex", "generic"].includes(host)) throw new Error(`unsupported source host: ${host}`);
366
- const canonicalCwd = await canonicalPath(cwd);
367
- const deadline = Date.now() + SOURCE_RESOLUTION_MS;
368
- const { registry } = await readRegistry(env);
369
- let hostHome;
370
- let projectRoot;
371
- let sources, unverified;
372
- let skipped = [];
373
- let hostDetails = {};
374
- let rootResolution = "explicit-root";
375
- if (host === "codex") {
376
- const codexHome = isKingHost(env) ? env.BLUN_HOME : env.CODEX_HOME || env.BLUN_HOME || join(homedir(), ".codex");
377
- hostHome = await existingDirectory(resolve(codexHome)) || resolve(codexHome);
378
- const config = await codexConfig(hostHome);
379
- if (isKingHost(env)) config.maxBytes = KING_SOURCE_BYTES;
380
- if (env.AGENTSPINE_ROOT) projectRoot = await canonicalPath(env.AGENTSPINE_ROOT);
381
- else ({ root: projectRoot, resolution: rootResolution } = await findRoot(canonicalCwd, config.rootMarkers));
382
- sources = await codexSources({ cwd: canonicalCwd, projectRoot, codexHome: hostHome, config });
383
- hostDetails = { rootMarkers: config.rootMarkers, fallbackNames: config.fallbackNames };
384
- } else if (host === "claude") {
385
- hostHome = await existingDirectory(resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude")))
386
- || resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"));
387
- if (env.AGENTSPINE_ROOT) projectRoot = await canonicalPath(env.AGENTSPINE_ROOT);
388
- else ({ root: projectRoot, resolution: rootResolution } = await findRoot(canonicalCwd, [".git"]));
389
- const result = await claudeSources({ cwd: canonicalCwd, projectRoot, configDir: hostHome, input, env, registry, deadline, memoryHooks });
390
- sources = result.sources;
391
- skipped = result.skipped;
392
- hostDetails = { memoryRoot: result.memoryRoot, memoryProvenance: result.memoryProvenance,
393
- memoryDiagnostics: result.memoryDiagnostics };
394
- } else {
395
- hostHome = await canonicalPath(homedir());
396
- if (env.AGENTSPINE_ROOT) projectRoot = await canonicalPath(env.AGENTSPINE_ROOT);
397
- else ({ root: projectRoot, resolution: rootResolution } = await findRoot(canonicalCwd, [".git"]));
398
- sources = [];
399
- for (const directory of ancestorsBetween(projectRoot, canonicalCwd)) {
400
- for (const name of ["AGENTS.md", "SOUL.md", "MEMORY.md"]) {
401
- await addFile(sources, join(directory, name), {
402
- id: `generic:project/${relative(projectRoot, join(directory, name)).replaceAll("\\", "/")}`,
403
- host, scope: "project", binding: "native-project-chain", precedence: 1000 + sources.length
404
- });
405
- }
406
- }
407
- }
408
- sources = [...new Map(sources.map((item) => [item.path, item])).values()];
409
- if (sources.length > MAX_SOURCES) throw new Error(`host-native required source set exceeds ${MAX_SOURCES} files`);
410
- ({ sources, unverified } = await partitionSources(sources, env));
411
- const nativeNames = new Set(host === "codex"
412
- ? ["AGENTS.override.md", "AGENTS.md", ...(hostDetails.fallbackNames || [])]
413
- : host === "claude" ? ["CLAUDE.md", "CLAUDE.local.md"] : ["AGENTS.md", "SOUL.md", "MEMORY.md"]);
414
- const knownHomeRoots = await homeRoots(env);
415
- const skippedHomeTree = knownHomeRoots.some((root) => samePath(root, projectRoot));
416
- const skippedProfileTree = samePath(hostHome, projectRoot);
417
- const skippedFallbackHomeTree = skippedHomeTree && rootResolution === "cwd-fallback";
418
- if (!skippedHomeTree && !skippedProfileTree) {
419
- const optionalBudget = Math.min(MAX_PROJECT_FILES, MAX_SOURCES - sources.length);
420
- sources.push(...await boundedMarkdownTree(projectRoot, "agentspine:project", host, "project", 3000, deadline,
421
- { projectBoundary: true, maxFiles: optionalBudget, maxDirectoryEntries: MAX_PROJECT_DIRECTORY_ENTRIES,
422
- skipped, truncateOnLimit: true, excludedNames: nativeNames, label: "project Markdown",
423
- timeoutMs: SOURCE_RESOLUTION_MS }));
424
- }
425
- sources = [...new Map(sources.map((item) => [item.path, item])).values()];
426
- if (sources.length > MAX_SOURCES) throw new Error(`host-native source set exceeds ${MAX_SOURCES} files`);
427
- let documents;
428
- try {
429
- documents = await indexExplicitDocuments(sources);
430
- } catch (error) {
431
- if (typeof error?.code === "string" && (error.path || error.syscall)) throw sourceScanError(error);
432
- throw error;
433
- }
434
- const totalBytes = documents.reduce((sum, document) => sum + document.bytes, 0);
435
- if (totalBytes > MAX_TOTAL_SOURCE_BYTES) throw new Error("host-native source set exceeds 8 MiB");
436
- const activeUserState = activeBinding(registry, host, hostHome, projectRoot, "state-user");
437
- const orderedSkipped = skipped.sort((a, b) => a.path.localeCompare(b.path) || a.operation.localeCompare(b.operation));
438
- const warnings = orderedSkipped.filter((item) => item.code === SOURCE_SCAN_INCOMPLETE);
439
- const unverifiedWarning = unverified.length > 1
440
- ? `${unverified.length} King rules exceed AgentSpine reader budgets; none were loaded or verified. Native rules apply. Continue; no retry.`
441
- : unverified[0]?.message;
442
- const diagnostics = {
443
- schema: SOURCE_REGISTRY_SCHEMA, host, status: unverified.length ? "incomplete" : documents.length ? "loaded" : "empty", projectRoot,
444
- hostHomeDigest: digest(hostHome).slice(0, 16), checked: ["host-profile", "project-chain", ...(host === "claude" ? ["project-memory"] : [])],
445
- scopes: Object.fromEntries(["user", "project", "project-memory"].map((scope) => [scope, documents.filter((item) => item.sourceScope === scope).length])),
446
- reason: unverifiedWarning || (documents.length ? null : "No regular, non-symlink host-native Markdown source exists in the checked scope."),
447
- personalContinuityLoaded: documents.some((item) => item.sourceScope === "user") || Boolean(activeUserState),
448
- broadHomeScan: false, projectTreeScan: skippedFallbackHomeTree ? "skipped-unmarked-home"
449
- : skippedHomeTree ? "skipped-home-root" : skippedProfileTree ? "skipped-profile-root"
450
- : warnings.length ? "bounded-truncated" : "bounded",
451
- incomplete: Boolean(unverified.length || warnings.length),
452
- warning: unverifiedWarning || warnings[0]?.message || null,
453
- warnings,
454
- skipped: orderedSkipped,
455
- rootResolution, registryRevision: registry.revision,
456
- ...(host === "claude" ? {
457
- memoryBound: Boolean(hostDetails.memoryRoot),
458
- memoryRootDigest: hostDetails.memoryRoot ? digest(hostDetails.memoryRoot).slice(0, 16) : null,
459
- memoryProvenance: hostDetails.memoryProvenance,
460
- memory: hostDetails.memoryDiagnostics || {
461
- indexed: 0, relevant: 0, selected: 0, omittedRelevant: 0, loaded: 0, cacheHits: 0, cacheMisses: 0, missing: 0,
462
- rejected: { scope: 0, path: 0, symlink: 0, race: 0, size: 0 }, directoryEnumeration: 0
463
- }
464
- } : hostDetails)
465
- };
466
- const catalog = {
467
- schema: "agentspine.catalog/v1", generatedAt: new Date().toISOString(), root: projectRoot,
468
- scanPolicy: catalogScanPolicy(projectRoot, env),
469
- preservation: "source-files-are-read-only", documents, conflicts: [], sourceRegistry: diagnostics,
470
- summary: { total: documents.length, protected: documents.filter((item) => item.protected).length, conflicts: 0,
471
- byLayer: Object.fromEntries([...new Set(documents.map((item) => item.layer))].sort().map((layer) => [layer, documents.filter((item) => item.layer === layer).length])) }
472
- };
473
- return { host, hostHome, projectRoot, cwd: canonicalCwd, catalog, diagnostics, unverified,
474
- userStateRoot: activeUserState?.sourceRoot || null, memoryRoot: hostDetails.memoryRoot || null };
475
- }
@@ -1,178 +0,0 @@
1
- import { lstat, opendir, realpath } from "node:fs/promises";
2
- import { join, relative } from "node:path";
3
-
4
- export const SOURCE_SCAN_INCOMPLETE = "AGENTSPINE_SCAN_INCOMPLETE";
5
-
6
- const SKIP_EXTRA_DIRS = new Set([
7
- ".git", ".hg", ".svn", ".claude", ".codex", "node_modules", "vendor", "dist", "build", "coverage"
8
- ]);
9
-
10
- export function sourceScanError(error) {
11
- error.agentSpineScan = true;
12
- return error;
13
- }
14
-
15
- export async function existingRegular(path) {
16
- try {
17
- const metadata = await lstat(path);
18
- if (metadata.isSymbolicLink() || !metadata.isFile()) return null;
19
- return realpath(path);
20
- } catch (error) {
21
- if (error.code === "ENOENT") return null;
22
- throw sourceScanError(error);
23
- }
24
- }
25
-
26
- export async function existingDirectory(path) {
27
- try {
28
- const metadata = await lstat(path);
29
- if (metadata.isSymbolicLink() || !metadata.isDirectory()) return null;
30
- return realpath(path);
31
- } catch (error) {
32
- if (error.code === "ENOENT") return null;
33
- throw sourceScanError(error);
34
- }
35
- }
36
-
37
- function skippedExtraDirectory(name) {
38
- const lower = name.toLowerCase();
39
- return SKIP_EXTRA_DIRS.has(name) || SKIP_EXTRA_DIRS.has(lower)
40
- || lower.includes("dropbox") || lower === "onedrive" || lower.startsWith("onedrive - ");
41
- }
42
-
43
- export function skippableTraversalError(error) {
44
- return ["EPERM", "EACCES", "ENOENT", "ENOTDIR"].includes(error?.code);
45
- }
46
-
47
- function recordSkippedPath(skipped, path, error, operation) {
48
- skipped.push({ path, code: error.code, operation });
49
- }
50
-
51
- function recordIncomplete(skipped, { path, operation, message, limit, retained }) {
52
- skipped.push({
53
- path, code: SOURCE_SCAN_INCOMPLETE, operation, message, limit, retained,
54
- authority: "diagnostic-only"
55
- });
56
- }
57
-
58
- async function containsProjectMarker(directory) {
59
- try {
60
- await lstat(join(directory, ".git"));
61
- return true;
62
- } catch (error) {
63
- if (error.code === "ENOENT") return false;
64
- throw error;
65
- }
66
- }
67
-
68
- async function containsEmbeddedHostProfile(directory) {
69
- return Boolean(
70
- await existingDirectory(join(directory, ".runtime-private"))
71
- && await existingRegular(join(directory, "config.toml"))
72
- );
73
- }
74
-
75
- function limitMessage(label, detail) {
76
- return `Host-native ${label} context is incomplete: ${detail}; remaining files were skipped.`;
77
- }
78
-
79
- export async function boundedMarkdownTree(directory, prefix, host, scope, precedenceStart, deadline, {
80
- projectBoundary = false,
81
- maxFiles,
82
- maxDirectoryEntries,
83
- skipped = [],
84
- truncateOnLimit = false,
85
- excludedNames = new Set(),
86
- label = "rule-tree",
87
- timeoutMs
88
- } = {}) {
89
- let root;
90
- try {
91
- root = await existingDirectory(directory);
92
- } catch (error) {
93
- if (!skippableTraversalError(error)) throw sourceScanError(error);
94
- recordSkippedPath(skipped, directory, error, "inspect-directory");
95
- return [];
96
- }
97
- if (!root) return [];
98
- const output = [];
99
- let visitedEntries = 0;
100
-
101
- function stopForLimit(path, operation, message, limit) {
102
- if (!truncateOnLimit) throw new Error(message);
103
- recordIncomplete(skipped, { path, operation,
104
- message: limitMessage(label, message), limit, retained: output.length });
105
- return false;
106
- }
107
-
108
- function checkDeadline(path) {
109
- if (Date.now() <= deadline) return true;
110
- const message = `source resolution exceeded ${timeoutMs} ms`;
111
- if (!truncateOnLimit) throw new Error(`host-native ${message}`);
112
- recordIncomplete(skipped, { path, operation: "deadline",
113
- message: limitMessage(label, message), limit: timeoutMs, retained: output.length });
114
- return false;
115
- }
116
-
117
- async function walk(current) {
118
- if (!checkDeadline(current)) return false;
119
- try {
120
- if (projectBoundary && current !== root
121
- && (await containsProjectMarker(current) || await containsEmbeddedHostProfile(current))) return true;
122
- } catch (error) {
123
- if (!skippableTraversalError(error)) throw sourceScanError(error);
124
- recordSkippedPath(skipped, current, error, "inspect-directory-boundary");
125
- return true;
126
- }
127
- const entries = [];
128
- let stream;
129
- try {
130
- stream = await opendir(current);
131
- } catch (error) {
132
- if (!skippableTraversalError(error)) throw sourceScanError(error);
133
- recordSkippedPath(skipped, error.path || current, error, "opendir");
134
- return true;
135
- }
136
- let stopAfterDirectory = false;
137
- try {
138
- for await (const entry of stream) {
139
- if (truncateOnLimit && !checkDeadline(current)) return false;
140
- visitedEntries += 1;
141
- if (visitedEntries > maxDirectoryEntries) {
142
- const message = `source tree exceeds ${maxDirectoryEntries} directory entries`;
143
- if (!truncateOnLimit) throw new Error(`host-native ${message}`);
144
- recordIncomplete(skipped, { path: current, operation: "directory-entry-limit",
145
- message: limitMessage(label, message), limit: maxDirectoryEntries, retained: output.length });
146
- stopAfterDirectory = true;
147
- break;
148
- }
149
- entries.push(entry);
150
- }
151
- } catch (error) {
152
- if (!skippableTraversalError(error)) throw sourceScanError(error);
153
- recordSkippedPath(skipped, current, error, "readdir");
154
- return true;
155
- }
156
- entries.sort((a, b) => a.name.localeCompare(b.name));
157
- for (const entry of entries) {
158
- if (truncateOnLimit && !checkDeadline(current)) return false;
159
- if (entry.isSymbolicLink()) continue;
160
- const path = join(current, entry.name);
161
- if (entry.isDirectory() && !stopAfterDirectory && !entry.name.startsWith(".")
162
- && !skippedExtraDirectory(entry.name)) {
163
- if (!await walk(path)) return false;
164
- } else if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")
165
- && !excludedNames.has(entry.name)) {
166
- if (output.length >= maxFiles) {
167
- return stopForLimit(root, "file-limit", `rule tree exceeds ${maxFiles} files`, maxFiles);
168
- }
169
- output.push({ path, id: `${prefix}/${relative(root, path).replaceAll("\\", "/")}`, host, scope,
170
- binding: "host-native-rule-tree", precedence: precedenceStart + output.length });
171
- }
172
- }
173
- return !stopAfterDirectory;
174
- }
175
-
176
- await walk(root);
177
- return output;
178
- }