open-second-brain 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1852) hide show
  1. package/.claude-plugin/marketplace.json +20 -0
  2. package/.claude-plugin/plugin.json +23 -0
  3. package/.codex-plugin/plugin.json +15 -0
  4. package/LICENSE +21 -0
  5. package/README.md +76 -2
  6. package/__init__.py +35 -0
  7. package/bin/_launch.js +141 -0
  8. package/bin/o2b-hook.js +3 -0
  9. package/bin/o2b-mcp.js +3 -0
  10. package/bin/o2b.js +3 -0
  11. package/hooks/README.md +347 -0
  12. package/hooks/active-inject.ts +992 -0
  13. package/hooks/answer-quote-check.ts +1319 -0
  14. package/hooks/backlog-nudge.ts +116 -0
  15. package/hooks/counterparty-brief.ts +209 -0
  16. package/hooks/gap-agenda.ts +65 -0
  17. package/hooks/gap-promote.ts +159 -0
  18. package/hooks/hooks.json +256 -0
  19. package/hooks/hygiene-digest.ts +194 -0
  20. package/hooks/lib/active-context.ts +558 -0
  21. package/hooks/lib/agent-context-blocks.ts +200 -0
  22. package/hooks/lib/backlog-nudge-state.ts +95 -0
  23. package/hooks/lib/context-events.ts +32 -0
  24. package/hooks/lib/detect.ts +295 -0
  25. package/hooks/lib/hook-vault.ts +132 -0
  26. package/hooks/lib/host-context-ceiling.ts +172 -0
  27. package/hooks/lib/hygiene-digest-state.ts +126 -0
  28. package/hooks/lib/hygiene-digest-text.ts +144 -0
  29. package/hooks/lib/injection-ledger.ts +580 -0
  30. package/hooks/lib/log-cursor-state.ts +371 -0
  31. package/hooks/lib/messages.ts +161 -0
  32. package/hooks/lib/process-ceiling.ts +158 -0
  33. package/hooks/lib/session-state.ts +437 -0
  34. package/hooks/lib/standing-block.ts +152 -0
  35. package/hooks/lib/stdin.ts +129 -0
  36. package/hooks/lib/stop-advisory-handover.ts +218 -0
  37. package/hooks/lib/transcript.ts +265 -0
  38. package/hooks/log-catchup.ts +566 -0
  39. package/hooks/nav-inject.ts +134 -0
  40. package/hooks/neighbour-updates.ts +528 -0
  41. package/hooks/post-write-reminder.ts +146 -0
  42. package/hooks/pretool-host-backup.ts +502 -0
  43. package/hooks/pretool-orient.ts +142 -0
  44. package/hooks/recall-inject.ts +443 -0
  45. package/hooks/reground-deliver.ts +216 -0
  46. package/hooks/session-capture.ts +260 -0
  47. package/hooks/stop-advisory-deliver.ts +71 -0
  48. package/hooks/stop-log-guardrail.ts +94 -0
  49. package/hooks/subagent-inject.ts +431 -0
  50. package/hooks/view-render.ts +83 -0
  51. package/openclaw/index.js +12703 -0
  52. package/openclaw.plugin.json +66 -0
  53. package/package.json +111 -4
  54. package/plugin.yaml +13 -0
  55. package/plugins/codex/.codex-plugin/plugin.json +25 -0
  56. package/plugins/codex/.codexignore +25 -0
  57. package/plugins/codex/LICENSE +21 -0
  58. package/plugins/codex/README.md +77 -0
  59. package/plugins/codex/SECURITY.md +51 -0
  60. package/plugins/codex/hooks/hooks.json +277 -0
  61. package/plugins/codex/skills/brain-memory/SKILL.md +197 -0
  62. package/plugins/codex/skills/codegraph-partner/SKILL.md +130 -0
  63. package/plugins/codex/skills/decision-model-setup/SKILL.md +215 -0
  64. package/plugins/codex/skills/embeddings-setup/SKILL.md +270 -0
  65. package/plugins/codex/skills/open-second-brain/SKILL.md +56 -0
  66. package/plugins/codex/skills/schema-author/SKILL.md +23 -0
  67. package/plugins/hermes/__init__.py +134 -0
  68. package/plugins/hermes/_base.py +85 -0
  69. package/plugins/hermes/_schemas.py +1501 -0
  70. package/plugins/hermes/bridge.py +740 -0
  71. package/plugins/hermes/cli.py +100 -0
  72. package/plugins/hermes/config.py +755 -0
  73. package/plugins/hermes/plugin.yaml +13 -0
  74. package/plugins/hermes/provider.py +1138 -0
  75. package/plugins/opencode/open-second-brain.ts +1164 -0
  76. package/pyproject.toml +28 -0
  77. package/schemas/brain/complexity-report.schema.json +39 -0
  78. package/schemas/brain/intent-review.schema.json +36 -0
  79. package/schemas/brain/monthly-review.schema.json +34 -0
  80. package/schemas/brain/retention-review.schema.json +44 -0
  81. package/schemas/brain/search-query.schema.json +231 -0
  82. package/scripts/_bun-precheck.sh +103 -0
  83. package/scripts/_macos-sqlite.sh +68 -0
  84. package/scripts/o2b +16 -0
  85. package/scripts/o2b-aider +22 -0
  86. package/scripts/o2b-aider.cmd +44 -0
  87. package/scripts/o2b-hook +94 -0
  88. package/scripts/o2b-hook.cmd +47 -0
  89. package/scripts/o2b-mcp +16 -0
  90. package/scripts/o2b-mcp.cmd +46 -0
  91. package/scripts/o2b.cmd +46 -0
  92. package/scripts/vault-log +17 -0
  93. package/scripts/vault-log.cmd +44 -0
  94. package/skills/brain-memory/SKILL.md +197 -0
  95. package/skills/codegraph-partner/SKILL.md +130 -0
  96. package/skills/decision-model-setup/SKILL.md +215 -0
  97. package/skills/embeddings-setup/SKILL.md +270 -0
  98. package/skills/open-second-brain/SKILL.md +56 -0
  99. package/skills/schema-author/SKILL.md +23 -0
  100. package/src/cli/advisory-rail.ts +175 -0
  101. package/src/cli/aider.ts +167 -0
  102. package/src/cli/argparse.ts +96 -0
  103. package/src/cli/bootstrap/index.ts +24 -0
  104. package/src/cli/bootstrap/receipt.ts +178 -0
  105. package/src/cli/bootstrap/run.ts +728 -0
  106. package/src/cli/bootstrap/targets.ts +56 -0
  107. package/src/cli/bootstrap/token-cli.ts +285 -0
  108. package/src/cli/brain/help-text.ts +1658 -0
  109. package/src/cli/brain/helpers.ts +263 -0
  110. package/src/cli/brain/query-render.ts +57 -0
  111. package/src/cli/brain/rollback-prompt.ts +72 -0
  112. package/src/cli/brain/snapshot-render.ts +176 -0
  113. package/src/cli/brain/upgrade-render.ts +76 -0
  114. package/src/cli/brain/verbs/actions.ts +70 -0
  115. package/src/cli/brain/verbs/activation.ts +115 -0
  116. package/src/cli/brain/verbs/agenda.ts +131 -0
  117. package/src/cli/brain/verbs/agent-diff.ts +97 -0
  118. package/src/cli/brain/verbs/agent-query.ts +80 -0
  119. package/src/cli/brain/verbs/anticipate.ts +86 -0
  120. package/src/cli/brain/verbs/apply-evidence.ts +69 -0
  121. package/src/cli/brain/verbs/apply-markers.ts +133 -0
  122. package/src/cli/brain/verbs/architect.ts +127 -0
  123. package/src/cli/brain/verbs/attention-flows.ts +90 -0
  124. package/src/cli/brain/verbs/attest.ts +458 -0
  125. package/src/cli/brain/verbs/attr.ts +98 -0
  126. package/src/cli/brain/verbs/audit.ts +39 -0
  127. package/src/cli/brain/verbs/authored-at-backfill.ts +73 -0
  128. package/src/cli/brain/verbs/backlinks.ts +80 -0
  129. package/src/cli/brain/verbs/bank-export.ts +200 -0
  130. package/src/cli/brain/verbs/bank-import.ts +146 -0
  131. package/src/cli/brain/verbs/batch-plan.ts +159 -0
  132. package/src/cli/brain/verbs/bench.ts +545 -0
  133. package/src/cli/brain/verbs/benchmark.ts +125 -0
  134. package/src/cli/brain/verbs/bridges.ts +237 -0
  135. package/src/cli/brain/verbs/capture.ts +154 -0
  136. package/src/cli/brain/verbs/changes.ts +88 -0
  137. package/src/cli/brain/verbs/claims.ts +148 -0
  138. package/src/cli/brain/verbs/clusters.ts +374 -0
  139. package/src/cli/brain/verbs/co-occurrence.ts +94 -0
  140. package/src/cli/brain/verbs/codec.ts +36 -0
  141. package/src/cli/brain/verbs/context-pack.ts +212 -0
  142. package/src/cli/brain/verbs/context-presets.ts +108 -0
  143. package/src/cli/brain/verbs/context-receipts.ts +225 -0
  144. package/src/cli/brain/verbs/continuity.ts +471 -0
  145. package/src/cli/brain/verbs/dead-end.ts +92 -0
  146. package/src/cli/brain/verbs/dead-letters.ts +504 -0
  147. package/src/cli/brain/verbs/decision.ts +538 -0
  148. package/src/cli/brain/verbs/deep-synthesis.ts +115 -0
  149. package/src/cli/brain/verbs/design-note.ts +167 -0
  150. package/src/cli/brain/verbs/diarize.ts +86 -0
  151. package/src/cli/brain/verbs/digest.ts +92 -0
  152. package/src/cli/brain/verbs/distill.ts +247 -0
  153. package/src/cli/brain/verbs/doctor.ts +543 -0
  154. package/src/cli/brain/verbs/dream.ts +720 -0
  155. package/src/cli/brain/verbs/entity.ts +629 -0
  156. package/src/cli/brain/verbs/event-trace.ts +113 -0
  157. package/src/cli/brain/verbs/expire.ts +118 -0
  158. package/src/cli/brain/verbs/explorer.ts +149 -0
  159. package/src/cli/brain/verbs/export.ts +531 -0
  160. package/src/cli/brain/verbs/extract-signals.ts +279 -0
  161. package/src/cli/brain/verbs/extract.ts +254 -0
  162. package/src/cli/brain/verbs/facts.ts +118 -0
  163. package/src/cli/brain/verbs/feedback.ts +325 -0
  164. package/src/cli/brain/verbs/file-context.ts +87 -0
  165. package/src/cli/brain/verbs/foresight.ts +107 -0
  166. package/src/cli/brain/verbs/forget-source.ts +198 -0
  167. package/src/cli/brain/verbs/freeze.ts +104 -0
  168. package/src/cli/brain/verbs/generation-reports.ts +271 -0
  169. package/src/cli/brain/verbs/git.ts +267 -0
  170. package/src/cli/brain/verbs/graph-export.ts +114 -0
  171. package/src/cli/brain/verbs/graph-import.ts +53 -0
  172. package/src/cli/brain/verbs/hallways.ts +370 -0
  173. package/src/cli/brain/verbs/handoff.ts +65 -0
  174. package/src/cli/brain/verbs/health-baseline.ts +107 -0
  175. package/src/cli/brain/verbs/health.ts +79 -0
  176. package/src/cli/brain/verbs/history.ts +33 -0
  177. package/src/cli/brain/verbs/hygiene.ts +192 -0
  178. package/src/cli/brain/verbs/idea-lineage.ts +62 -0
  179. package/src/cli/brain/verbs/ideas.ts +68 -0
  180. package/src/cli/brain/verbs/import-claude-memory.ts +173 -0
  181. package/src/cli/brain/verbs/import-session.ts +910 -0
  182. package/src/cli/brain/verbs/inbox-drain.ts +91 -0
  183. package/src/cli/brain/verbs/index.ts +165 -0
  184. package/src/cli/brain/verbs/init.ts +189 -0
  185. package/src/cli/brain/verbs/intent-review.ts +61 -0
  186. package/src/cli/brain/verbs/intention.ts +110 -0
  187. package/src/cli/brain/verbs/knowledge-gaps.ts +86 -0
  188. package/src/cli/brain/verbs/knowledge-pack.ts +295 -0
  189. package/src/cli/brain/verbs/label.ts +141 -0
  190. package/src/cli/brain/verbs/lessons.ts +1064 -0
  191. package/src/cli/brain/verbs/lifecycle.ts +278 -0
  192. package/src/cli/brain/verbs/links.ts +131 -0
  193. package/src/cli/brain/verbs/lint.ts +68 -0
  194. package/src/cli/brain/verbs/log.ts +159 -0
  195. package/src/cli/brain/verbs/maintenance.ts +608 -0
  196. package/src/cli/brain/verbs/mcp-landscape.ts +29 -0
  197. package/src/cli/brain/verbs/merge.ts +98 -0
  198. package/src/cli/brain/verbs/migrate-store-forms.ts +230 -0
  199. package/src/cli/brain/verbs/migrate-store.ts +482 -0
  200. package/src/cli/brain/verbs/moc-audit.ts +68 -0
  201. package/src/cli/brain/verbs/monthly.ts +51 -0
  202. package/src/cli/brain/verbs/morning-brief.ts +150 -0
  203. package/src/cli/brain/verbs/note-history.ts +70 -0
  204. package/src/cli/brain/verbs/note-lifecycle.ts +356 -0
  205. package/src/cli/brain/verbs/note.ts +89 -0
  206. package/src/cli/brain/verbs/obligation.ts +159 -0
  207. package/src/cli/brain/verbs/okf-export.ts +210 -0
  208. package/src/cli/brain/verbs/okf-import.ts +41 -0
  209. package/src/cli/brain/verbs/orphan-repair.ts +85 -0
  210. package/src/cli/brain/verbs/page-dedup.ts +171 -0
  211. package/src/cli/brain/verbs/panel.ts +202 -0
  212. package/src/cli/brain/verbs/payload.ts +196 -0
  213. package/src/cli/brain/verbs/pending.ts +190 -0
  214. package/src/cli/brain/verbs/permissions.ts +243 -0
  215. package/src/cli/brain/verbs/pin.ts +50 -0
  216. package/src/cli/brain/verbs/post-compact-audit.ts +118 -0
  217. package/src/cli/brain/verbs/pre-compact-extract.ts +64 -0
  218. package/src/cli/brain/verbs/pre-extract.ts +58 -0
  219. package/src/cli/brain/verbs/privacy-marker-restamp.ts +73 -0
  220. package/src/cli/brain/verbs/procedural-graph.ts +95 -0
  221. package/src/cli/brain/verbs/procedural-memory.ts +93 -0
  222. package/src/cli/brain/verbs/profile.ts +53 -0
  223. package/src/cli/brain/verbs/project.ts +145 -0
  224. package/src/cli/brain/verbs/protect.ts +319 -0
  225. package/src/cli/brain/verbs/query.ts +145 -0
  226. package/src/cli/brain/verbs/recall-telemetry.ts +359 -0
  227. package/src/cli/brain/verbs/receipts.ts +195 -0
  228. package/src/cli/brain/verbs/recurrence.ts +121 -0
  229. package/src/cli/brain/verbs/refresh.ts +66 -0
  230. package/src/cli/brain/verbs/reject.ts +155 -0
  231. package/src/cli/brain/verbs/repair-lane.ts +252 -0
  232. package/src/cli/brain/verbs/retention.ts +46 -0
  233. package/src/cli/brain/verbs/rollback.ts +258 -0
  234. package/src/cli/brain/verbs/scaffold-stub.ts +151 -0
  235. package/src/cli/brain/verbs/scan-citations.ts +61 -0
  236. package/src/cli/brain/verbs/scan-inline.ts +94 -0
  237. package/src/cli/brain/verbs/schema.ts +241 -0
  238. package/src/cli/brain/verbs/secret.ts +469 -0
  239. package/src/cli/brain/verbs/semantics-backfill.ts +33 -0
  240. package/src/cli/brain/verbs/session-hook.ts +37 -0
  241. package/src/cli/brain/verbs/session-recall.ts +226 -0
  242. package/src/cli/brain/verbs/session-summary.ts +223 -0
  243. package/src/cli/brain/verbs/session.ts +205 -0
  244. package/src/cli/brain/verbs/set-primary.ts +118 -0
  245. package/src/cli/brain/verbs/settings.ts +128 -0
  246. package/src/cli/brain/verbs/sgrep.ts +78 -0
  247. package/src/cli/brain/verbs/signal.ts +100 -0
  248. package/src/cli/brain/verbs/skill-proposals.ts +886 -0
  249. package/src/cli/brain/verbs/snapshot.ts +294 -0
  250. package/src/cli/brain/verbs/source.ts +75 -0
  251. package/src/cli/brain/verbs/sources.ts +42 -0
  252. package/src/cli/brain/verbs/standing-rules.ts +119 -0
  253. package/src/cli/brain/verbs/state.ts +120 -0
  254. package/src/cli/brain/verbs/status.ts +36 -0
  255. package/src/cli/brain/verbs/storage.ts +113 -0
  256. package/src/cli/brain/verbs/summary.ts +81 -0
  257. package/src/cli/brain/verbs/synthesise.ts +63 -0
  258. package/src/cli/brain/verbs/telegram-capture.ts +80 -0
  259. package/src/cli/brain/verbs/temporal-daily.ts +87 -0
  260. package/src/cli/brain/verbs/temporal-evolution.ts +79 -0
  261. package/src/cli/brain/verbs/temporal-stale.ts +50 -0
  262. package/src/cli/brain/verbs/temporal-timeline.ts +92 -0
  263. package/src/cli/brain/verbs/temporal-weekly.ts +87 -0
  264. package/src/cli/brain/verbs/tension.ts +222 -0
  265. package/src/cli/brain/verbs/tiers.ts +170 -0
  266. package/src/cli/brain/verbs/today.ts +71 -0
  267. package/src/cli/brain/verbs/token-footprint.ts +62 -0
  268. package/src/cli/brain/verbs/trigger.ts +188 -0
  269. package/src/cli/brain/verbs/truth.ts +417 -0
  270. package/src/cli/brain/verbs/tune.ts +154 -0
  271. package/src/cli/brain/verbs/unlinked.ts +67 -0
  272. package/src/cli/brain/verbs/upgrade.ts +286 -0
  273. package/src/cli/brain/verbs/validate.ts +198 -0
  274. package/src/cli/brain/verbs/vitals.ts +95 -0
  275. package/src/cli/brain/verbs/watchdog.ts +51 -0
  276. package/src/cli/brain/verbs/writes.ts +507 -0
  277. package/src/cli/brain.ts +591 -0
  278. package/src/cli/coerce.ts +85 -0
  279. package/src/cli/command-manifest.ts +1757 -0
  280. package/src/cli/completions.ts +103 -0
  281. package/src/cli/cron-recipe.ts +512 -0
  282. package/src/cli/decision-model.ts +590 -0
  283. package/src/cli/deps-bootstrap.ts +24 -0
  284. package/src/cli/discipline.ts +67 -0
  285. package/src/cli/dream/agent.ts +193 -0
  286. package/src/cli/dream/owner.ts +268 -0
  287. package/src/cli/dream/queue.ts +181 -0
  288. package/src/cli/dream/run.ts +249 -0
  289. package/src/cli/dream/status.ts +69 -0
  290. package/src/cli/help-render.ts +129 -0
  291. package/src/cli/helpers.ts +157 -0
  292. package/src/cli/install/init-interactive.ts +340 -0
  293. package/src/cli/install/install.ts +707 -0
  294. package/src/cli/install/render.ts +354 -0
  295. package/src/cli/install/uninstall-target.ts +167 -0
  296. package/src/cli/install-cli-windows.ts +232 -0
  297. package/src/cli/install-cli.ts +307 -0
  298. package/src/cli/interrupt.ts +286 -0
  299. package/src/cli/json-helpers.ts +155 -0
  300. package/src/cli/main.ts +1758 -0
  301. package/src/cli/maintenance-cron.ts +234 -0
  302. package/src/cli/mcp-drain.ts +132 -0
  303. package/src/cli/mcp-fault-guard.ts +248 -0
  304. package/src/cli/onboarding.ts +384 -0
  305. package/src/cli/output.ts +93 -0
  306. package/src/cli/partner-codegraph-cron.ts +233 -0
  307. package/src/cli/partner.ts +228 -0
  308. package/src/cli/progress-rail.ts +250 -0
  309. package/src/cli/search/helpers.ts +177 -0
  310. package/src/cli/search/outcome-render.ts +343 -0
  311. package/src/cli/search/verbs/check.ts +665 -0
  312. package/src/cli/search/verbs/event-anchor-backfill.ts +132 -0
  313. package/src/cli/search/verbs/expand.ts +120 -0
  314. package/src/cli/search/verbs/focus.ts +93 -0
  315. package/src/cli/search/verbs/indexing.ts +688 -0
  316. package/src/cli/search/verbs/learned-weights.ts +121 -0
  317. package/src/cli/search/verbs/plan.ts +74 -0
  318. package/src/cli/search/verbs/provider-registry.ts +233 -0
  319. package/src/cli/search/verbs/query.ts +288 -0
  320. package/src/cli/search/verbs/rerank-eval.ts +309 -0
  321. package/src/cli/search/verbs/rerank-fit.ts +65 -0
  322. package/src/cli/search/verbs/restamp.ts +201 -0
  323. package/src/cli/search/verbs/schema-export.ts +226 -0
  324. package/src/cli/search/verbs/set-aside.ts +47 -0
  325. package/src/cli/search/verbs/status.ts +203 -0
  326. package/src/cli/search/verbs/vector-backfill.ts +345 -0
  327. package/src/cli/search/verbs/watch.ts +121 -0
  328. package/src/cli/search-cron-template.ts +95 -0
  329. package/src/cli/search.ts +134 -0
  330. package/src/cli/setup.ts +543 -0
  331. package/src/cli/state.ts +312 -0
  332. package/src/cli/stdin.ts +29 -0
  333. package/src/cli/stdout-guard.ts +68 -0
  334. package/src/cli/store-device.ts +259 -0
  335. package/src/cli/store-partition.ts +161 -0
  336. package/src/cli/store-path.ts +130 -0
  337. package/src/cli/store-shard.ts +535 -0
  338. package/src/cli/store.ts +298 -0
  339. package/src/cli/topic.ts +317 -0
  340. package/src/cli/transport-reach.ts +17 -0
  341. package/src/cli/uninstall.ts +210 -0
  342. package/src/cli/update.ts +183 -0
  343. package/src/cli/vault/help-text.ts +51 -0
  344. package/src/cli/vault/verbs/inspect.ts +141 -0
  345. package/src/cli/vault/verbs/map.ts +37 -0
  346. package/src/cli/vault/verbs/profile.ts +69 -0
  347. package/src/cli/vault/verbs/status.ts +100 -0
  348. package/src/cli/vault.ts +58 -0
  349. package/src/cli/version.ts +53 -0
  350. package/src/cli/view.ts +275 -0
  351. package/src/cli/windows-path-hint.ts +39 -0
  352. package/src/core/agent-context/budget-line.ts +19 -0
  353. package/src/core/agent-context/config.ts +35 -0
  354. package/src/core/agent-context/digest-cut-note.ts +138 -0
  355. package/src/core/agent-context/head-select.ts +209 -0
  356. package/src/core/agent-context/heads.ts +128 -0
  357. package/src/core/agent-context/neighbour-relevant.ts +175 -0
  358. package/src/core/agent-context/neighbours.ts +282 -0
  359. package/src/core/agent-context/pinned-block.ts +68 -0
  360. package/src/core/agent-context/session-identity.ts +124 -0
  361. package/src/core/agent-context/topic-tail.ts +262 -0
  362. package/src/core/agent-identity.ts +151 -0
  363. package/src/core/bench/embedding-cache.ts +358 -0
  364. package/src/core/bench/failure-modes.ts +257 -0
  365. package/src/core/bench/fixture.ts +315 -0
  366. package/src/core/bench/guards.ts +596 -0
  367. package/src/core/bench/judge.ts +75 -0
  368. package/src/core/bench/locomo.ts +199 -0
  369. package/src/core/bench/longmemeval-sample.ts +273 -0
  370. package/src/core/bench/longmemeval.ts +736 -0
  371. package/src/core/bench/phases.ts +1054 -0
  372. package/src/core/bench/replay-fixture.ts +290 -0
  373. package/src/core/bench/replay.ts +78 -0
  374. package/src/core/bench/run-store.ts +389 -0
  375. package/src/core/bench/types.ts +497 -0
  376. package/src/core/brain/active-budget-pressure.ts +215 -0
  377. package/src/core/brain/active-budget.ts +486 -0
  378. package/src/core/brain/active.ts +687 -0
  379. package/src/core/brain/agenda.ts +296 -0
  380. package/src/core/brain/agent-backend/claude.ts +42 -0
  381. package/src/core/brain/agent-backend/generic.ts +33 -0
  382. package/src/core/brain/agent-backend/json-source.ts +169 -0
  383. package/src/core/brain/agent-backend/mem0.ts +29 -0
  384. package/src/core/brain/agent-backend/registry.ts +49 -0
  385. package/src/core/brain/agent-backend/types.ts +89 -0
  386. package/src/core/brain/agent-source/diff.ts +160 -0
  387. package/src/core/brain/agent-source/freeze.ts +12 -0
  388. package/src/core/brain/agent-source/query.ts +187 -0
  389. package/src/core/brain/agent-source/registry.ts +101 -0
  390. package/src/core/brain/agent-source/summary.ts +28 -0
  391. package/src/core/brain/agent-source/types.ts +99 -0
  392. package/src/core/brain/agent-source/vault-provider.ts +276 -0
  393. package/src/core/brain/answer-quotes/check.ts +190 -0
  394. package/src/core/brain/anticipatory-cache.ts +591 -0
  395. package/src/core/brain/anticipatory-prune.ts +156 -0
  396. package/src/core/brain/applier-capability.ts +369 -0
  397. package/src/core/brain/apply-evidence.ts +524 -0
  398. package/src/core/brain/architect/decisions.ts +92 -0
  399. package/src/core/brain/architect/generate.ts +1121 -0
  400. package/src/core/brain/architect/manifests.ts +611 -0
  401. package/src/core/brain/architect/scan.ts +541 -0
  402. package/src/core/brain/artifact-ref-resolve.ts +217 -0
  403. package/src/core/brain/artifact-ref-view.ts +174 -0
  404. package/src/core/brain/atomic-facts.ts +339 -0
  405. package/src/core/brain/attention-flows.ts +411 -0
  406. package/src/core/brain/attestation/digest.ts +357 -0
  407. package/src/core/brain/attestation/record.ts +537 -0
  408. package/src/core/brain/attestation/signing.ts +405 -0
  409. package/src/core/brain/attestation/verify.ts +523 -0
  410. package/src/core/brain/attributes.ts +221 -0
  411. package/src/core/brain/audit-dirs.ts +39 -0
  412. package/src/core/brain/authored-at-backfill.ts +211 -0
  413. package/src/core/brain/backlinks.ts +438 -0
  414. package/src/core/brain/belief-semantic.ts +338 -0
  415. package/src/core/brain/capture/capture-note.ts +563 -0
  416. package/src/core/brain/capture/inbox-drain.ts +473 -0
  417. package/src/core/brain/capture/telegram-capture.ts +501 -0
  418. package/src/core/brain/capture-boundary.ts +166 -0
  419. package/src/core/brain/checkpoint-store.ts +153 -0
  420. package/src/core/brain/claim-graph.ts +342 -0
  421. package/src/core/brain/claude-memory-manifest.ts +62 -0
  422. package/src/core/brain/claude-memory-parser.ts +138 -0
  423. package/src/core/brain/claude-memory-paths.ts +64 -0
  424. package/src/core/brain/claude-memory-plan.ts +26 -0
  425. package/src/core/brain/claude-memory-render.ts +140 -0
  426. package/src/core/brain/commitment.ts +62 -0
  427. package/src/core/brain/compiled-digest-path.ts +125 -0
  428. package/src/core/brain/confidence.ts +91 -0
  429. package/src/core/brain/config-template.ts +904 -0
  430. package/src/core/brain/content-hash.ts +81 -0
  431. package/src/core/brain/context-density.ts +86 -0
  432. package/src/core/brain/context-lanes.ts +83 -0
  433. package/src/core/brain/context-pack-evidence.ts +423 -0
  434. package/src/core/brain/context-pack-outcome.ts +447 -0
  435. package/src/core/brain/context-pack.ts +1915 -0
  436. package/src/core/brain/context-presets.ts +333 -0
  437. package/src/core/brain/context-receipt-trigger.ts +34 -0
  438. package/src/core/brain/context-receipts-verify.ts +565 -0
  439. package/src/core/brain/context-receipts.ts +856 -0
  440. package/src/core/brain/context-transforms.ts +82 -0
  441. package/src/core/brain/continuity/emit.ts +37 -0
  442. package/src/core/brain/continuity/export-atif.ts +110 -0
  443. package/src/core/brain/continuity/export-atof.ts +131 -0
  444. package/src/core/brain/continuity/promote-host-memory.ts +673 -0
  445. package/src/core/brain/continuity/read-model.ts +131 -0
  446. package/src/core/brain/continuity/redaction.ts +42 -0
  447. package/src/core/brain/continuity/store.ts +575 -0
  448. package/src/core/brain/continuity/types.ts +263 -0
  449. package/src/core/brain/continuity/usage-signal.ts +223 -0
  450. package/src/core/brain/count-guard.ts +82 -0
  451. package/src/core/brain/counterparty-brief.ts +686 -0
  452. package/src/core/brain/dead-ends.ts +254 -0
  453. package/src/core/brain/dead-letter-recovery.ts +739 -0
  454. package/src/core/brain/dead-letter.ts +453 -0
  455. package/src/core/brain/dead-weight.ts +267 -0
  456. package/src/core/brain/decisions/brief.ts +63 -0
  457. package/src/core/brain/decisions/open-store.ts +1043 -0
  458. package/src/core/brain/decisions/recall.ts +121 -0
  459. package/src/core/brain/decisions/receipts.ts +677 -0
  460. package/src/core/brain/decisions/record.ts +814 -0
  461. package/src/core/brain/dedup-hash.ts +404 -0
  462. package/src/core/brain/dedup-index-cache.ts +144 -0
  463. package/src/core/brain/dedup-telemetry.ts +294 -0
  464. package/src/core/brain/deep-synthesis.ts +736 -0
  465. package/src/core/brain/delivery-shaping.ts +113 -0
  466. package/src/core/brain/derived-artifact.ts +107 -0
  467. package/src/core/brain/derived-fact.ts +168 -0
  468. package/src/core/brain/design-note.ts +634 -0
  469. package/src/core/brain/destructive-sites.ts +505 -0
  470. package/src/core/brain/diagnostics.ts +2200 -0
  471. package/src/core/brain/diarization.ts +355 -0
  472. package/src/core/brain/digest-agent-summary.ts +228 -0
  473. package/src/core/brain/digest-analysis.ts +160 -0
  474. package/src/core/brain/digest-brief.ts +152 -0
  475. package/src/core/brain/digest-collect.ts +532 -0
  476. package/src/core/brain/digest-types.ts +324 -0
  477. package/src/core/brain/digest.ts +379 -0
  478. package/src/core/brain/distill/backlog-proposals.ts +158 -0
  479. package/src/core/brain/distill/block-resolve.ts +205 -0
  480. package/src/core/brain/distill/claim.ts +23 -0
  481. package/src/core/brain/distill/distill-source.ts +506 -0
  482. package/src/core/brain/distill/quote-check.ts +190 -0
  483. package/src/core/brain/distill/quote-spans.ts +509 -0
  484. package/src/core/brain/distill/quote-verdict.ts +120 -0
  485. package/src/core/brain/doctor/active-budget-check.ts +84 -0
  486. package/src/core/brain/doctor/adopt-conflicts-check.ts +40 -0
  487. package/src/core/brain/doctor/attestation-check.ts +268 -0
  488. package/src/core/brain/doctor/check.ts +133 -0
  489. package/src/core/brain/doctor/chunk-holds-check.ts +131 -0
  490. package/src/core/brain/doctor/config-checks.ts +223 -0
  491. package/src/core/brain/doctor/delivery-provenance-check.ts +99 -0
  492. package/src/core/brain/doctor/device-retire-check.ts +45 -0
  493. package/src/core/brain/doctor/device-state-check.ts +67 -0
  494. package/src/core/brain/doctor/discipline-check.ts +111 -0
  495. package/src/core/brain/doctor/dream-owner-check.ts +87 -0
  496. package/src/core/brain/doctor/dream-queue-check.ts +182 -0
  497. package/src/core/brain/doctor/dream-replay-check.ts +129 -0
  498. package/src/core/brain/doctor/dream-trigger-check.ts +87 -0
  499. package/src/core/brain/doctor/embedding-sunset-check.ts +261 -0
  500. package/src/core/brain/doctor/embeddings-health-check.ts +304 -0
  501. package/src/core/brain/doctor/entity-alias-verdicts.ts +131 -0
  502. package/src/core/brain/doctor/entity-checks.ts +366 -0
  503. package/src/core/brain/doctor/frozen-check.ts +52 -0
  504. package/src/core/brain/doctor/git-tracked-state-check.ts +206 -0
  505. package/src/core/brain/doctor/inbox-archive-check.ts +77 -0
  506. package/src/core/brain/doctor/lane-id-check.ts +148 -0
  507. package/src/core/brain/doctor/lessons-block-check.ts +343 -0
  508. package/src/core/brain/doctor/link-checks.ts +95 -0
  509. package/src/core/brain/doctor/log-chain-check.ts +59 -0
  510. package/src/core/brain/doctor/log-checks.ts +192 -0
  511. package/src/core/brain/doctor/merge-chain-check.ts +183 -0
  512. package/src/core/brain/doctor/migration-check.ts +575 -0
  513. package/src/core/brain/doctor/orphan-session-check.ts +465 -0
  514. package/src/core/brain/doctor/payload-checks.ts +117 -0
  515. package/src/core/brain/doctor/permissions-check.ts +245 -0
  516. package/src/core/brain/doctor/planted-rows-check.ts +134 -0
  517. package/src/core/brain/doctor/preference-hygiene.ts +229 -0
  518. package/src/core/brain/doctor/privacy-marker-check.ts +61 -0
  519. package/src/core/brain/doctor/recall-channel-coverage.ts +248 -0
  520. package/src/core/brain/doctor/receipt-content-drift-check.ts +178 -0
  521. package/src/core/brain/doctor/receipt-ledger.ts +100 -0
  522. package/src/core/brain/doctor/record-checks.ts +404 -0
  523. package/src/core/brain/doctor/records.ts +307 -0
  524. package/src/core/brain/doctor/recovery-point-liveness.ts +234 -0
  525. package/src/core/brain/doctor/removed-tool-checks.ts +178 -0
  526. package/src/core/brain/doctor/report.ts +136 -0
  527. package/src/core/brain/doctor/rerank-health-check.ts +324 -0
  528. package/src/core/brain/doctor/secrets-sync-check.ts +71 -0
  529. package/src/core/brain/doctor/semantic-health-check.ts +212 -0
  530. package/src/core/brain/doctor/session-identity-check.ts +147 -0
  531. package/src/core/brain/doctor/stale-dependency-check.ts +522 -0
  532. package/src/core/brain/doctor/storage-capacity.ts +141 -0
  533. package/src/core/brain/doctor/store-check.ts +655 -0
  534. package/src/core/brain/doctor/store-gap-check.ts +222 -0
  535. package/src/core/brain/doctor/store-integrity.ts +457 -0
  536. package/src/core/brain/doctor/store-side-pass.ts +94 -0
  537. package/src/core/brain/doctor/store-trust-check.ts +197 -0
  538. package/src/core/brain/doctor/topic-plan-check.ts +42 -0
  539. package/src/core/brain/doctor/uncertain-stream.ts +117 -0
  540. package/src/core/brain/doctor/uncertainty-probes.ts +204 -0
  541. package/src/core/brain/doctor/unreadable-path.ts +211 -0
  542. package/src/core/brain/doctor/view-writer-check.ts +105 -0
  543. package/src/core/brain/doctor-exits.ts +806 -0
  544. package/src/core/brain/doctor.ts +911 -0
  545. package/src/core/brain/document-retire.ts +461 -0
  546. package/src/core/brain/dream-apply.ts +904 -0
  547. package/src/core/brain/dream-gates.ts +155 -0
  548. package/src/core/brain/dream-outcome.ts +125 -0
  549. package/src/core/brain/dream-owner/constants.ts +38 -0
  550. package/src/core/brain/dream-owner/create.ts +62 -0
  551. package/src/core/brain/dream-owner/fold.ts +179 -0
  552. package/src/core/brain/dream-owner/gate.ts +305 -0
  553. package/src/core/brain/dream-owner/owner.ts +409 -0
  554. package/src/core/brain/dream-owner/pass-record.ts +42 -0
  555. package/src/core/brain/dream-owner/status.ts +205 -0
  556. package/src/core/brain/dream-phases.ts +49 -0
  557. package/src/core/brain/dream-plan-cross-topic.ts +638 -0
  558. package/src/core/brain/dream-plan-retires.ts +136 -0
  559. package/src/core/brain/dream-plan-topics.ts +643 -0
  560. package/src/core/brain/dream-plan.ts +437 -0
  561. package/src/core/brain/dream-queue/agent-check.ts +187 -0
  562. package/src/core/brain/dream-queue/agent-config.ts +179 -0
  563. package/src/core/brain/dream-queue/agent-executor.ts +331 -0
  564. package/src/core/brain/dream-queue/agent-presets.ts +58 -0
  565. package/src/core/brain/dream-queue/agent-verified.ts +104 -0
  566. package/src/core/brain/dream-queue/constants.ts +90 -0
  567. package/src/core/brain/dream-queue/decision-executor.ts +439 -0
  568. package/src/core/brain/dream-queue/dream-session.ts +71 -0
  569. package/src/core/brain/dream-queue/fold.ts +516 -0
  570. package/src/core/brain/dream-queue/operations.ts +107 -0
  571. package/src/core/brain/dream-queue/pass.ts +134 -0
  572. package/src/core/brain/dream-queue/queue.ts +1370 -0
  573. package/src/core/brain/dream-queue/records.ts +293 -0
  574. package/src/core/brain/dream-queue/rollup-work.ts +313 -0
  575. package/src/core/brain/dream-queue/run-record.ts +361 -0
  576. package/src/core/brain/dream-queue/status-view.ts +415 -0
  577. package/src/core/brain/dream-refresh.ts +502 -0
  578. package/src/core/brain/dream-replay/admission.ts +247 -0
  579. package/src/core/brain/dream-replay/behind.ts +89 -0
  580. package/src/core/brain/dream-replay/bootstrap.ts +220 -0
  581. package/src/core/brain/dream-replay/fold.ts +208 -0
  582. package/src/core/brain/dream-replay/ledgers.ts +237 -0
  583. package/src/core/brain/dream-replay/loop.ts +511 -0
  584. package/src/core/brain/dream-replay/pass.ts +128 -0
  585. package/src/core/brain/dream-replay/plan.ts +157 -0
  586. package/src/core/brain/dream-replay/privacy.ts +62 -0
  587. package/src/core/brain/dream-replay/reconcile.ts +69 -0
  588. package/src/core/brain/dream-replay/records.ts +184 -0
  589. package/src/core/brain/dream-replay/status-view.ts +127 -0
  590. package/src/core/brain/dream-replay/transfer.ts +137 -0
  591. package/src/core/brain/dream-replay/window.ts +160 -0
  592. package/src/core/brain/dream-report.ts +398 -0
  593. package/src/core/brain/dream-rollup.ts +71 -0
  594. package/src/core/brain/dream-scan.ts +400 -0
  595. package/src/core/brain/dream-stage.ts +914 -0
  596. package/src/core/brain/dream-step.ts +246 -0
  597. package/src/core/brain/dream-summary.ts +240 -0
  598. package/src/core/brain/dream-tail.ts +150 -0
  599. package/src/core/brain/dream-trigger/auto.ts +31 -0
  600. package/src/core/brain/dream-trigger/check.ts +170 -0
  601. package/src/core/brain/dream-trigger/claim.ts +206 -0
  602. package/src/core/brain/dream-trigger/constants.ts +53 -0
  603. package/src/core/brain/dream-trigger/due.ts +335 -0
  604. package/src/core/brain/dream-trigger/forget.ts +33 -0
  605. package/src/core/brain/dream-trigger/line.ts +67 -0
  606. package/src/core/brain/dream-trigger/outcome.ts +518 -0
  607. package/src/core/brain/dream-trigger/record.ts +366 -0
  608. package/src/core/brain/dream-trigger/status.ts +166 -0
  609. package/src/core/brain/dream-types.ts +412 -0
  610. package/src/core/brain/dream-workrun.ts +194 -0
  611. package/src/core/brain/dream.ts +1097 -0
  612. package/src/core/brain/entities/canonical.ts +802 -0
  613. package/src/core/brain/entities/index-builder.ts +308 -0
  614. package/src/core/brain/entities/label-hygiene.ts +319 -0
  615. package/src/core/brain/entities/lexicon.ts +444 -0
  616. package/src/core/brain/entities/page-merge.ts +683 -0
  617. package/src/core/brain/entities/page-privacy.ts +35 -0
  618. package/src/core/brain/entities/page-scope.ts +45 -0
  619. package/src/core/brain/entities/person-nicknames.ts +157 -0
  620. package/src/core/brain/entities/person-variants.ts +259 -0
  621. package/src/core/brain/entities/registry.ts +1070 -0
  622. package/src/core/brain/entities/semantic-dedup.ts +353 -0
  623. package/src/core/brain/entities/status-scope.ts +78 -0
  624. package/src/core/brain/entities/types.ts +86 -0
  625. package/src/core/brain/event-trace.ts +391 -0
  626. package/src/core/brain/evidence-read.ts +65 -0
  627. package/src/core/brain/evidence.ts +96 -0
  628. package/src/core/brain/exact-state.ts +363 -0
  629. package/src/core/brain/expiration-set.ts +449 -0
  630. package/src/core/brain/expiration.ts +115 -0
  631. package/src/core/brain/explorer-console.ts +269 -0
  632. package/src/core/brain/explorer.ts +615 -0
  633. package/src/core/brain/export-transcripts.ts +358 -0
  634. package/src/core/brain/export.ts +590 -0
  635. package/src/core/brain/extract-signals-prefilter.ts +541 -0
  636. package/src/core/brain/extract-signals.ts +990 -0
  637. package/src/core/brain/fact-extract.ts +610 -0
  638. package/src/core/brain/file-recall.ts +164 -0
  639. package/src/core/brain/freeze-marker.ts +331 -0
  640. package/src/core/brain/freeze.ts +171 -0
  641. package/src/core/brain/freshness.ts +222 -0
  642. package/src/core/brain/frontmatter-tiers.ts +247 -0
  643. package/src/core/brain/gaps/gap-loop.ts +572 -0
  644. package/src/core/brain/gaps/gap-recall.ts +153 -0
  645. package/src/core/brain/gate-telemetry.ts +231 -0
  646. package/src/core/brain/gates/durability.ts +338 -0
  647. package/src/core/brain/gates/recoverability.ts +277 -0
  648. package/src/core/brain/generation-reports.ts +245 -0
  649. package/src/core/brain/git/decisions.ts +199 -0
  650. package/src/core/brain/git/digest.ts +116 -0
  651. package/src/core/brain/git/identity.ts +29 -0
  652. package/src/core/brain/git/ingest.ts +222 -0
  653. package/src/core/brain/git/reader.ts +456 -0
  654. package/src/core/brain/git/store.ts +655 -0
  655. package/src/core/brain/gitignore-guard.ts +296 -0
  656. package/src/core/brain/governance/forget-plan.ts +213 -0
  657. package/src/core/brain/governance/store-unreachable.ts +44 -0
  658. package/src/core/brain/handoff.ts +176 -0
  659. package/src/core/brain/heal-enrich.ts +188 -0
  660. package/src/core/brain/heal-run.ts +211 -0
  661. package/src/core/brain/health/batch-inflation.ts +102 -0
  662. package/src/core/brain/health/concept-gap.ts +96 -0
  663. package/src/core/brain/health/contradiction.ts +379 -0
  664. package/src/core/brain/health/edit-history.ts +207 -0
  665. package/src/core/brain/health/iso-time.ts +32 -0
  666. package/src/core/brain/health/reconcile.ts +248 -0
  667. package/src/core/brain/health/remediation.ts +424 -0
  668. package/src/core/brain/health/stale-claim.ts +53 -0
  669. package/src/core/brain/health/thesis.ts +649 -0
  670. package/src/core/brain/health-baseline.ts +185 -0
  671. package/src/core/brain/host-memory-promotions.ts +101 -0
  672. package/src/core/brain/host-memory-write.ts +140 -0
  673. package/src/core/brain/host-path-free.ts +46 -0
  674. package/src/core/brain/hygiene/apply.ts +275 -0
  675. package/src/core/brain/hygiene/dedup-verdicts.ts +147 -0
  676. package/src/core/brain/hygiene/detectors/capture-scope.ts +327 -0
  677. package/src/core/brain/hygiene/detectors/conflicts.ts +47 -0
  678. package/src/core/brain/hygiene/detectors/dedup.ts +238 -0
  679. package/src/core/brain/hygiene/detectors/document-dedup.ts +595 -0
  680. package/src/core/brain/hygiene/detectors/freshness.ts +59 -0
  681. package/src/core/brain/hygiene/detectors/frontmatter-tags.ts +99 -0
  682. package/src/core/brain/hygiene/detectors/id.ts +17 -0
  683. package/src/core/brain/hygiene/detectors/slug-collisions.ts +176 -0
  684. package/src/core/brain/hygiene/detectors/tags.ts +252 -0
  685. package/src/core/brain/hygiene/detectors/usefulness.ts +89 -0
  686. package/src/core/brain/hygiene/plan.ts +81 -0
  687. package/src/core/brain/hygiene/resolve-conflicts.ts +133 -0
  688. package/src/core/brain/hygiene/scan.ts +93 -0
  689. package/src/core/brain/hygiene/types.ts +125 -0
  690. package/src/core/brain/idea-discovery.ts +382 -0
  691. package/src/core/brain/idea-lineage.ts +329 -0
  692. package/src/core/brain/idempotency-ledger.ts +426 -0
  693. package/src/core/brain/import-census.ts +152 -0
  694. package/src/core/brain/import-claude-memory.ts +536 -0
  695. package/src/core/brain/index.ts +168 -0
  696. package/src/core/brain/ingest/batch-plan.ts +749 -0
  697. package/src/core/brain/ingest/checkpoint.ts +202 -0
  698. package/src/core/brain/ingest/content-manifest.ts +693 -0
  699. package/src/core/brain/ingest/contract.ts +70 -0
  700. package/src/core/brain/ingest/extract-html.ts +815 -0
  701. package/src/core/brain/ingest/extract-source.ts +290 -0
  702. package/src/core/brain/ingest/extractable-gate.ts +147 -0
  703. package/src/core/brain/ingest/ingest.ts +1137 -0
  704. package/src/core/brain/ingest/pre-extract-hcl.ts +389 -0
  705. package/src/core/brain/ingest/pre-extract-seeds.ts +76 -0
  706. package/src/core/brain/ingest/pre-extract.ts +455 -0
  707. package/src/core/brain/ingest/reconcile.ts +106 -0
  708. package/src/core/brain/ingest/source-formats.ts +210 -0
  709. package/src/core/brain/ingest/source-read.ts +84 -0
  710. package/src/core/brain/ingest/sources-registry.ts +151 -0
  711. package/src/core/brain/ingest/table-note.ts +519 -0
  712. package/src/core/brain/ingest/tail-read.ts +188 -0
  713. package/src/core/brain/init-store.ts +150 -0
  714. package/src/core/brain/init.ts +673 -0
  715. package/src/core/brain/inject-failopen.ts +123 -0
  716. package/src/core/brain/inject-governor.ts +250 -0
  717. package/src/core/brain/inline-rewrite.ts +110 -0
  718. package/src/core/brain/inline-scan.ts +338 -0
  719. package/src/core/brain/inline.ts +924 -0
  720. package/src/core/brain/intake/extract-intake.ts +587 -0
  721. package/src/core/brain/intake/page-entity-links.ts +198 -0
  722. package/src/core/brain/intake/source-trust.ts +508 -0
  723. package/src/core/brain/intent-review.ts +256 -0
  724. package/src/core/brain/intentions.ts +223 -0
  725. package/src/core/brain/label-suggest.ts +292 -0
  726. package/src/core/brain/labels.ts +247 -0
  727. package/src/core/brain/ledger-shards.ts +447 -0
  728. package/src/core/brain/lessons-promotion.ts +966 -0
  729. package/src/core/brain/lessons.ts +714 -0
  730. package/src/core/brain/lifecycle/correction.ts +727 -0
  731. package/src/core/brain/lifecycle/curator.ts +75 -0
  732. package/src/core/brain/lifecycle/memory-target.ts +845 -0
  733. package/src/core/brain/lifecycle/temporal-replace.ts +212 -0
  734. package/src/core/brain/lifecycle/tombstone-read.ts +323 -0
  735. package/src/core/brain/lifecycle/tombstone.ts +329 -0
  736. package/src/core/brain/lifecycle/validity.ts +109 -0
  737. package/src/core/brain/lineage/crutch.ts +515 -0
  738. package/src/core/brain/lineage/identity.ts +459 -0
  739. package/src/core/brain/lineage/ledger.ts +1203 -0
  740. package/src/core/brain/lineage/resolve.ts +182 -0
  741. package/src/core/brain/lineage/types.ts +82 -0
  742. package/src/core/brain/lineage/verify.ts +364 -0
  743. package/src/core/brain/link-graph/alias-index.ts +166 -0
  744. package/src/core/brain/link-graph/bridge-discovery.ts +431 -0
  745. package/src/core/brain/link-graph/co-occurrence.ts +295 -0
  746. package/src/core/brain/link-graph/communities.ts +430 -0
  747. package/src/core/brain/link-graph/concept-cluster.ts +152 -0
  748. package/src/core/brain/link-graph/format-wikilink.ts +211 -0
  749. package/src/core/brain/link-graph/graph-holdout.ts +200 -0
  750. package/src/core/brain/link-graph/graph-index.ts +185 -0
  751. package/src/core/brain/link-graph/hallways.ts +581 -0
  752. package/src/core/brain/link-graph/hub-candidates.ts +441 -0
  753. package/src/core/brain/link-graph/minimal-spelling.ts +110 -0
  754. package/src/core/brain/link-graph/moc-audit.ts +371 -0
  755. package/src/core/brain/link-graph/orphan-repair.ts +259 -0
  756. package/src/core/brain/link-graph/parse-wikilink.ts +202 -0
  757. package/src/core/brain/link-graph/repair-lane.ts +726 -0
  758. package/src/core/brain/link-graph/session-mining.ts +666 -0
  759. package/src/core/brain/link-graph/unlinked-mentions.ts +273 -0
  760. package/src/core/brain/lint-consolidate.ts +426 -0
  761. package/src/core/brain/llm-step.ts +110 -0
  762. package/src/core/brain/log-append-io.ts +272 -0
  763. package/src/core/brain/log-chain.ts +414 -0
  764. package/src/core/brain/log-days.ts +340 -0
  765. package/src/core/brain/log-events-at-reach.ts +198 -0
  766. package/src/core/brain/log-jsonl.ts +447 -0
  767. package/src/core/brain/log.ts +1034 -0
  768. package/src/core/brain/maintenance/action-scorer.ts +144 -0
  769. package/src/core/brain/maintenance/collect.ts +163 -0
  770. package/src/core/brain/maintenance/custom-task-id.ts +25 -0
  771. package/src/core/brain/maintenance/custom-tasks.ts +551 -0
  772. package/src/core/brain/maintenance/host-pressure.ts +501 -0
  773. package/src/core/brain/maintenance/journal.ts +413 -0
  774. package/src/core/brain/maintenance/lane-tasks.ts +284 -0
  775. package/src/core/brain/maintenance/lane.ts +774 -0
  776. package/src/core/brain/maintenance/lease.ts +143 -0
  777. package/src/core/brain/maintenance/reindex-task.ts +168 -0
  778. package/src/core/brain/maintenance/relink-anchors-task.ts +768 -0
  779. package/src/core/brain/manifest.ts +610 -0
  780. package/src/core/brain/marginal-value-stop.ts +83 -0
  781. package/src/core/brain/marker-routing.ts +225 -0
  782. package/src/core/brain/marker-writeback.ts +607 -0
  783. package/src/core/brain/mcp-route-metrics.ts +330 -0
  784. package/src/core/brain/memory-cost-meter.ts +240 -0
  785. package/src/core/brain/memory-page-records.ts +84 -0
  786. package/src/core/brain/memory-pages.ts +698 -0
  787. package/src/core/brain/merge-candidates.ts +134 -0
  788. package/src/core/brain/merge.ts +453 -0
  789. package/src/core/brain/metrics.ts +291 -0
  790. package/src/core/brain/model-window.ts +278 -0
  791. package/src/core/brain/monthly-review.ts +120 -0
  792. package/src/core/brain/morning-brief.ts +279 -0
  793. package/src/core/brain/most-applied.ts +124 -0
  794. package/src/core/brain/nav-inject.ts +49 -0
  795. package/src/core/brain/navmap.ts +109 -0
  796. package/src/core/brain/near-duplicate-vectors.ts +178 -0
  797. package/src/core/brain/near-duplicate.ts +141 -0
  798. package/src/core/brain/negative-recall.ts +755 -0
  799. package/src/core/brain/next-step.ts +99 -0
  800. package/src/core/brain/no-vault.ts +49 -0
  801. package/src/core/brain/note-history.ts +178 -0
  802. package/src/core/brain/note-path.ts +57 -0
  803. package/src/core/brain/note.ts +198 -0
  804. package/src/core/brain/notes/blank-overwrite-guard.ts +88 -0
  805. package/src/core/brain/notes/create-note-privacy.ts +46 -0
  806. package/src/core/brain/notes/create-note.ts +919 -0
  807. package/src/core/brain/notes/folder-lifecycle.ts +1428 -0
  808. package/src/core/brain/notes/index-refresh.ts +346 -0
  809. package/src/core/brain/notes/lifecycle.ts +1414 -0
  810. package/src/core/brain/notes/link-candidates.ts +227 -0
  811. package/src/core/brain/notes/log-window.ts +147 -0
  812. package/src/core/brain/notes/note-template.ts +299 -0
  813. package/src/core/brain/notes/note-title-resolver.ts +169 -0
  814. package/src/core/brain/notes/note-walk.ts +194 -0
  815. package/src/core/brain/notes/revert.ts +774 -0
  816. package/src/core/brain/notes/scaffold-stub.ts +541 -0
  817. package/src/core/brain/notes/write-destinations.ts +330 -0
  818. package/src/core/brain/notes/write-log.ts +228 -0
  819. package/src/core/brain/notes/write-record.ts +408 -0
  820. package/src/core/brain/obligations.ts +749 -0
  821. package/src/core/brain/observed-use.ts +209 -0
  822. package/src/core/brain/offset-cursor.ts +76 -0
  823. package/src/core/brain/open-loops.ts +248 -0
  824. package/src/core/brain/operator-snapshot.ts +577 -0
  825. package/src/core/brain/owner-scope-view.ts +131 -0
  826. package/src/core/brain/owner-scoped-facts.ts +43 -0
  827. package/src/core/brain/pack-stamp.ts +274 -0
  828. package/src/core/brain/page-dedup.ts +752 -0
  829. package/src/core/brain/page-lint-widening.ts +210 -0
  830. package/src/core/brain/page-lint.ts +969 -0
  831. package/src/core/brain/page-meta/confidence.ts +33 -0
  832. package/src/core/brain/page-meta/lifecycle.ts +85 -0
  833. package/src/core/brain/page-meta/page-id.ts +534 -0
  834. package/src/core/brain/page-meta/tier.ts +53 -0
  835. package/src/core/brain/parse-error.ts +84 -0
  836. package/src/core/brain/path-constants.ts +425 -0
  837. package/src/core/brain/paths.ts +1264 -0
  838. package/src/core/brain/payload-inventory.ts +539 -0
  839. package/src/core/brain/payload-json.ts +133 -0
  840. package/src/core/brain/payload-registry.ts +305 -0
  841. package/src/core/brain/pending/pending-lanes.ts +905 -0
  842. package/src/core/brain/pending.ts +160 -0
  843. package/src/core/brain/permissions/document-source.ts +100 -0
  844. package/src/core/brain/permissions/document.ts +638 -0
  845. package/src/core/brain/permissions/ledger.ts +302 -0
  846. package/src/core/brain/permissions/resolve.ts +130 -0
  847. package/src/core/brain/pin.ts +205 -0
  848. package/src/core/brain/pinned.ts +410 -0
  849. package/src/core/brain/planted-rows.ts +573 -0
  850. package/src/core/brain/pledge-intake.ts +632 -0
  851. package/src/core/brain/pledges.ts +971 -0
  852. package/src/core/brain/policy/blocks/active.ts +251 -0
  853. package/src/core/brain/policy/blocks/context.ts +87 -0
  854. package/src/core/brain/policy/blocks/continuity-hygiene.ts +96 -0
  855. package/src/core/brain/policy/blocks/decision-model.ts +60 -0
  856. package/src/core/brain/policy/blocks/discipline-report.ts +105 -0
  857. package/src/core/brain/policy/blocks/embeddings.ts +127 -0
  858. package/src/core/brain/policy/blocks/feedback.ts +53 -0
  859. package/src/core/brain/policy/blocks/guardrails.ts +215 -0
  860. package/src/core/brain/policy/blocks/health.ts +134 -0
  861. package/src/core/brain/policy/blocks/install.ts +131 -0
  862. package/src/core/brain/policy/blocks/integrity.ts +162 -0
  863. package/src/core/brain/policy/blocks/lessons.ts +146 -0
  864. package/src/core/brain/policy/blocks/lifecycle.ts +200 -0
  865. package/src/core/brain/policy/blocks/link-graph.ts +125 -0
  866. package/src/core/brain/policy/blocks/maintenance.ts +129 -0
  867. package/src/core/brain/policy/blocks/notes.ts +83 -0
  868. package/src/core/brain/policy/blocks/quote-check.ts +45 -0
  869. package/src/core/brain/policy/blocks/recall-inject.ts +192 -0
  870. package/src/core/brain/policy/blocks/rollup.ts +31 -0
  871. package/src/core/brain/policy/blocks/schema.ts +118 -0
  872. package/src/core/brain/policy/blocks/sessions.ts +124 -0
  873. package/src/core/brain/policy/blocks/storage.ts +282 -0
  874. package/src/core/brain/policy/blocks/temporal.ts +110 -0
  875. package/src/core/brain/policy/blocks/vault-scope.ts +169 -0
  876. package/src/core/brain/policy/blocks/write-binding.ts +113 -0
  877. package/src/core/brain/policy/defaults.ts +71 -0
  878. package/src/core/brain/policy/errors.ts +50 -0
  879. package/src/core/brain/policy/field-checks.ts +153 -0
  880. package/src/core/brain/policy/key-index.ts +143 -0
  881. package/src/core/brain/policy/load.ts +468 -0
  882. package/src/core/brain/policy/primary-agent.ts +59 -0
  883. package/src/core/brain/policy/settings-entry-authority.ts +105 -0
  884. package/src/core/brain/policy/settings-keys.ts +163 -0
  885. package/src/core/brain/policy/settings-names.ts +252 -0
  886. package/src/core/brain/policy/settings-source.ts +366 -0
  887. package/src/core/brain/policy/settings-store-commit.ts +115 -0
  888. package/src/core/brain/policy/settings-write.ts +777 -0
  889. package/src/core/brain/policy/settings-yaml-edit.ts +152 -0
  890. package/src/core/brain/policy/validate.ts +254 -0
  891. package/src/core/brain/policy.ts +177 -0
  892. package/src/core/brain/portability/bundle.ts +251 -0
  893. package/src/core/brain/portability/codec.ts +80 -0
  894. package/src/core/brain/portability/graph.ts +353 -0
  895. package/src/core/brain/portability/knowledge-pack.ts +1446 -0
  896. package/src/core/brain/portability/okf.ts +1755 -0
  897. package/src/core/brain/portability/origin-reach.ts +123 -0
  898. package/src/core/brain/portability/origins.ts +104 -0
  899. package/src/core/brain/portability/pack-stamp.ts +63 -0
  900. package/src/core/brain/portability/page-contract.ts +139 -0
  901. package/src/core/brain/portability/pointer.ts +262 -0
  902. package/src/core/brain/portability/preference-restore.ts +830 -0
  903. package/src/core/brain/portability/profiles.ts +219 -0
  904. package/src/core/brain/portability/recall-sources.ts +172 -0
  905. package/src/core/brain/portability/role-tokens.ts +165 -0
  906. package/src/core/brain/portability/sources.ts +123 -0
  907. package/src/core/brain/portability/vault-map-document.ts +34 -0
  908. package/src/core/brain/post-compact-audit.ts +448 -0
  909. package/src/core/brain/pre-compact-extract.ts +239 -0
  910. package/src/core/brain/pre-compress-pack.ts +388 -0
  911. package/src/core/brain/pref-audit.ts +397 -0
  912. package/src/core/brain/preference-body.ts +372 -0
  913. package/src/core/brain/preference-page-meta.ts +66 -0
  914. package/src/core/brain/preference-page-write.ts +249 -0
  915. package/src/core/brain/preference-provenance.ts +194 -0
  916. package/src/core/brain/preference-store.ts +135 -0
  917. package/src/core/brain/preference-txn.ts +446 -0
  918. package/src/core/brain/preference.ts +2398 -0
  919. package/src/core/brain/preferences-collect.ts +371 -0
  920. package/src/core/brain/present-time.ts +71 -0
  921. package/src/core/brain/pretool-host-backup.ts +353 -0
  922. package/src/core/brain/pretool-orient.ts +147 -0
  923. package/src/core/brain/privacy-marker-restamp.ts +429 -0
  924. package/src/core/brain/procedural-graph.ts +369 -0
  925. package/src/core/brain/procedural-hints.ts +85 -0
  926. package/src/core/brain/procedural-memory.ts +510 -0
  927. package/src/core/brain/profile-doc.ts +205 -0
  928. package/src/core/brain/progress.ts +386 -0
  929. package/src/core/brain/prompt-prefix.ts +149 -0
  930. package/src/core/brain/protect.ts +1014 -0
  931. package/src/core/brain/provenance/capture-scope.ts +249 -0
  932. package/src/core/brain/provenance/content-class.ts +342 -0
  933. package/src/core/brain/provenance/epistemic.ts +120 -0
  934. package/src/core/brain/provenance/page-origin.ts +169 -0
  935. package/src/core/brain/provenance/provenance.ts +117 -0
  936. package/src/core/brain/provenance/source-archive.ts +430 -0
  937. package/src/core/brain/provenance/trust-order.ts +34 -0
  938. package/src/core/brain/query-demand.ts +607 -0
  939. package/src/core/brain/query.ts +487 -0
  940. package/src/core/brain/quote-check-modes.ts +47 -0
  941. package/src/core/brain/reach-view.ts +68 -0
  942. package/src/core/brain/recall-adequacy.ts +246 -0
  943. package/src/core/brain/recall-budget.ts +356 -0
  944. package/src/core/brain/recall-inject-decision.ts +243 -0
  945. package/src/core/brain/recall-inject.ts +1420 -0
  946. package/src/core/brain/recall-telemetry.ts +568 -0
  947. package/src/core/brain/receipts/compact.ts +832 -0
  948. package/src/core/brain/receipts/scan.ts +409 -0
  949. package/src/core/brain/receipts/types.ts +292 -0
  950. package/src/core/brain/receipts/views.ts +96 -0
  951. package/src/core/brain/recent-turns.ts +156 -0
  952. package/src/core/brain/recompile.ts +320 -0
  953. package/src/core/brain/reconcile-domains.ts +143 -0
  954. package/src/core/brain/reconcile-outcomes.ts +109 -0
  955. package/src/core/brain/record-name.ts +74 -0
  956. package/src/core/brain/record-origin.ts +102 -0
  957. package/src/core/brain/recurrence.ts +332 -0
  958. package/src/core/brain/regions.ts +149 -0
  959. package/src/core/brain/reground-parts.ts +235 -0
  960. package/src/core/brain/render/activity-line.ts +81 -0
  961. package/src/core/brain/report-snapshot.ts +259 -0
  962. package/src/core/brain/research/external-fetch.ts +328 -0
  963. package/src/core/brain/research/extract.ts +61 -0
  964. package/src/core/brain/research/providers/brave.ts +51 -0
  965. package/src/core/brain/research/providers/provider.ts +27 -0
  966. package/src/core/brain/research/providers/tavily.ts +47 -0
  967. package/src/core/brain/research/research.ts +501 -0
  968. package/src/core/brain/response-checks.ts +178 -0
  969. package/src/core/brain/response-shape.ts +462 -0
  970. package/src/core/brain/retention.ts +197 -0
  971. package/src/core/brain/retire-siblings.ts +110 -0
  972. package/src/core/brain/retrieval-plan.ts +255 -0
  973. package/src/core/brain/review-candidates.ts +360 -0
  974. package/src/core/brain/rollup-ladder.ts +246 -0
  975. package/src/core/brain/runtime-notices.ts +505 -0
  976. package/src/core/brain/safeguard.ts +255 -0
  977. package/src/core/brain/safety/context-guard.ts +235 -0
  978. package/src/core/brain/salience-gate.ts +363 -0
  979. package/src/core/brain/schema-admin.ts +510 -0
  980. package/src/core/brain/schema-integrity.ts +502 -0
  981. package/src/core/brain/schema-mutate-store.ts +257 -0
  982. package/src/core/brain/schema-mutate.ts +798 -0
  983. package/src/core/brain/schema-pack-store.ts +313 -0
  984. package/src/core/brain/schema-pack.ts +588 -0
  985. package/src/core/brain/schema-report.ts +473 -0
  986. package/src/core/brain/schema-vocab.ts +141 -0
  987. package/src/core/brain/scope-identity.ts +93 -0
  988. package/src/core/brain/scoped-rule-axis.ts +31 -0
  989. package/src/core/brain/scoped-rule-key.ts +42 -0
  990. package/src/core/brain/scoped-rules.ts +323 -0
  991. package/src/core/brain/sdk.ts +142 -0
  992. package/src/core/brain/secrets/bundle.ts +539 -0
  993. package/src/core/brain/secrets/crypto.ts +156 -0
  994. package/src/core/brain/secrets/device-token-path.ts +18 -0
  995. package/src/core/brain/secrets/envelope.ts +726 -0
  996. package/src/core/brain/secrets/exec.ts +194 -0
  997. package/src/core/brain/secrets/owner-acl.ts +165 -0
  998. package/src/core/brain/secrets/store.ts +610 -0
  999. package/src/core/brain/secrets/sync-exposure.ts +263 -0
  1000. package/src/core/brain/secrets/token-store.ts +542 -0
  1001. package/src/core/brain/secrets/value-cipher.ts +58 -0
  1002. package/src/core/brain/semantics-backfill.ts +99 -0
  1003. package/src/core/brain/session-checkpoint.ts +360 -0
  1004. package/src/core/brain/session-lifecycle.ts +926 -0
  1005. package/src/core/brain/session-mining-ledger.ts +350 -0
  1006. package/src/core/brain/session-mining-surveys.ts +240 -0
  1007. package/src/core/brain/session-recall.ts +1667 -0
  1008. package/src/core/brain/session-scope.ts +41 -0
  1009. package/src/core/brain/session-summary.ts +465 -0
  1010. package/src/core/brain/sessions/checkpoint.ts +362 -0
  1011. package/src/core/brain/sessions/claude.ts +140 -0
  1012. package/src/core/brain/sessions/codex.ts +153 -0
  1013. package/src/core/brain/sessions/discover.ts +468 -0
  1014. package/src/core/brain/sessions/dream-transcript.ts +38 -0
  1015. package/src/core/brain/sessions/grok.ts +188 -0
  1016. package/src/core/brain/sessions/hermes.ts +132 -0
  1017. package/src/core/brain/sessions/import.ts +984 -0
  1018. package/src/core/brain/sessions/mining-census.ts +234 -0
  1019. package/src/core/brain/sessions/opencode.ts +137 -0
  1020. package/src/core/brain/sessions/read-lines.ts +147 -0
  1021. package/src/core/brain/sessions/registry.ts +114 -0
  1022. package/src/core/brain/sessions/session-files.ts +124 -0
  1023. package/src/core/brain/sessions/types.ts +184 -0
  1024. package/src/core/brain/sessions/validate-feedback.ts +130 -0
  1025. package/src/core/brain/set-primary.ts +122 -0
  1026. package/src/core/brain/shared-namespace.ts +297 -0
  1027. package/src/core/brain/sign.ts +65 -0
  1028. package/src/core/brain/signal-archive.ts +180 -0
  1029. package/src/core/brain/signal-retire.ts +301 -0
  1030. package/src/core/brain/signal-state.ts +339 -0
  1031. package/src/core/brain/signal.ts +1270 -0
  1032. package/src/core/brain/similarity.ts +84 -0
  1033. package/src/core/brain/skill-accept-journal.ts +413 -0
  1034. package/src/core/brain/skill-page-drafts.ts +443 -0
  1035. package/src/core/brain/skill-proposal-verifier.ts +100 -0
  1036. package/src/core/brain/skill-proposals.ts +2852 -0
  1037. package/src/core/brain/skill-rewrite-spec.ts +323 -0
  1038. package/src/core/brain/skill-rewrite-tasks.ts +362 -0
  1039. package/src/core/brain/skill-rewrite.ts +793 -0
  1040. package/src/core/brain/skill-usage.ts +350 -0
  1041. package/src/core/brain/snapshot-diff-render.ts +134 -0
  1042. package/src/core/brain/snapshot-diff.ts +421 -0
  1043. package/src/core/brain/snapshot-gate.ts +531 -0
  1044. package/src/core/brain/snapshot-transient.ts +116 -0
  1045. package/src/core/brain/snapshot.ts +4059 -0
  1046. package/src/core/brain/source-cleanup.ts +1091 -0
  1047. package/src/core/brain/source-links.ts +133 -0
  1048. package/src/core/brain/stale-dependency.ts +552 -0
  1049. package/src/core/brain/staleness.ts +316 -0
  1050. package/src/core/brain/standing-rules-write.ts +93 -0
  1051. package/src/core/brain/standing-rules.ts +451 -0
  1052. package/src/core/brain/status.ts +650 -0
  1053. package/src/core/brain/storage/capacity-error.ts +45 -0
  1054. package/src/core/brain/storage/forecast.ts +450 -0
  1055. package/src/core/brain/storage/gate-config.ts +135 -0
  1056. package/src/core/brain/storage/gate.ts +241 -0
  1057. package/src/core/brain/storage/usage.ts +388 -0
  1058. package/src/core/brain/store-record-visibility.ts +176 -0
  1059. package/src/core/brain/surprisal.ts +104 -0
  1060. package/src/core/brain/sync-lockfile.ts +854 -0
  1061. package/src/core/brain/tag-syntax.ts +119 -0
  1062. package/src/core/brain/tar-extract.ts +197 -0
  1063. package/src/core/brain/tar-names.ts +251 -0
  1064. package/src/core/brain/tar-writer.ts +206 -0
  1065. package/src/core/brain/templates/_BRAIN.md.tpl +175 -0
  1066. package/src/core/brain/templates/bases/daily.base +21 -0
  1067. package/src/core/brain/templates/bases/people.base +47 -0
  1068. package/src/core/brain/templates/bases/projects.base +59 -0
  1069. package/src/core/brain/templates/bases/tasks.base +42 -0
  1070. package/src/core/brain/templates.ts +238 -0
  1071. package/src/core/brain/temporal/activity-timeline.ts +176 -0
  1072. package/src/core/brain/temporal/belief-evolution.ts +348 -0
  1073. package/src/core/brain/temporal/build-index.ts +413 -0
  1074. package/src/core/brain/temporal/citations.ts +381 -0
  1075. package/src/core/brain/temporal/daily-brief.ts +102 -0
  1076. package/src/core/brain/temporal/foresight.ts +150 -0
  1077. package/src/core/brain/temporal/freshness-trend.ts +151 -0
  1078. package/src/core/brain/temporal/period-common.ts +129 -0
  1079. package/src/core/brain/temporal/select-events.ts +69 -0
  1080. package/src/core/brain/temporal/stale-watch.ts +217 -0
  1081. package/src/core/brain/temporal/types.ts +126 -0
  1082. package/src/core/brain/temporal/weekly-brief.ts +334 -0
  1083. package/src/core/brain/temporal-extract.ts +109 -0
  1084. package/src/core/brain/tension-verdicts.ts +204 -0
  1085. package/src/core/brain/tensions.ts +794 -0
  1086. package/src/core/brain/text/neutralize-markdown.ts +710 -0
  1087. package/src/core/brain/text/normalize.ts +28 -0
  1088. package/src/core/brain/text/sanitize-principle.ts +68 -0
  1089. package/src/core/brain/text/text-budget.ts +446 -0
  1090. package/src/core/brain/text/tokenizer.ts +38 -0
  1091. package/src/core/brain/thread-topics.ts +157 -0
  1092. package/src/core/brain/time.ts +173 -0
  1093. package/src/core/brain/today-dashboard.ts +463 -0
  1094. package/src/core/brain/token-footprint.ts +199 -0
  1095. package/src/core/brain/token-impact.ts +568 -0
  1096. package/src/core/brain/tool-outcome.ts +25 -0
  1097. package/src/core/brain/triggers/adapters.ts +93 -0
  1098. package/src/core/brain/triggers/brief.ts +53 -0
  1099. package/src/core/brain/triggers/scan.ts +83 -0
  1100. package/src/core/brain/triggers/store.ts +1766 -0
  1101. package/src/core/brain/triggers/types.ts +209 -0
  1102. package/src/core/brain/trust/assess-rule-quality.ts +129 -0
  1103. package/src/core/brain/trust/check-role-permission.ts +91 -0
  1104. package/src/core/brain/trust/compute-trust-verdict.ts +58 -0
  1105. package/src/core/brain/trust/compute-verification-delta.ts +295 -0
  1106. package/src/core/brain/trust/instruction-file-ceiling.ts +97 -0
  1107. package/src/core/brain/trust/operator-summary.ts +420 -0
  1108. package/src/core/brain/trust/owner-write-gate.ts +171 -0
  1109. package/src/core/brain/trust/retrieval-gate.ts +259 -0
  1110. package/src/core/brain/trust/retrieval-receipts.ts +263 -0
  1111. package/src/core/brain/trust/role.ts +65 -0
  1112. package/src/core/brain/trust/self-approval-guardrail.ts +61 -0
  1113. package/src/core/brain/trust/untrusted-provenance.ts +101 -0
  1114. package/src/core/brain/truth/aggregate.ts +101 -0
  1115. package/src/core/brain/truth/claim-provenance.ts +346 -0
  1116. package/src/core/brain/truth/collision.ts +119 -0
  1117. package/src/core/brain/truth/conflicts.ts +130 -0
  1118. package/src/core/brain/truth/contamination.ts +132 -0
  1119. package/src/core/brain/truth/correction-policy.ts +60 -0
  1120. package/src/core/brain/truth/events-window.ts +160 -0
  1121. package/src/core/brain/truth/fold.ts +127 -0
  1122. package/src/core/brain/truth/grounding.ts +205 -0
  1123. package/src/core/brain/truth/ingest.ts +92 -0
  1124. package/src/core/brain/truth/merge-guard.ts +127 -0
  1125. package/src/core/brain/truth/stated-claims.ts +256 -0
  1126. package/src/core/brain/truth/store.ts +852 -0
  1127. package/src/core/brain/truth/succession.ts +117 -0
  1128. package/src/core/brain/truth/types.ts +187 -0
  1129. package/src/core/brain/truth/validity.ts +203 -0
  1130. package/src/core/brain/types.ts +2642 -0
  1131. package/src/core/brain/undated-quantity.ts +513 -0
  1132. package/src/core/brain/untrusted-source.ts +242 -0
  1133. package/src/core/brain/upgrade.ts +732 -0
  1134. package/src/core/brain/vault-dirty.ts +201 -0
  1135. package/src/core/brain/vault-identity.ts +424 -0
  1136. package/src/core/brain/vault-instruction-file.ts +121 -0
  1137. package/src/core/brain/vitals.ts +167 -0
  1138. package/src/core/brain/watchdog.ts +303 -0
  1139. package/src/core/brain/wikilink.ts +607 -0
  1140. package/src/core/brain/write-advisory.ts +441 -0
  1141. package/src/core/brain/write-batch-privacy.ts +145 -0
  1142. package/src/core/brain/write-batch.ts +1461 -0
  1143. package/src/core/brain/write-disposition.ts +392 -0
  1144. package/src/core/brain/write-gate.ts +122 -0
  1145. package/src/core/brain/write-path-advisory.ts +101 -0
  1146. package/src/core/brain/write-refusal-exit.ts +16 -0
  1147. package/src/core/brain/write-session/engine.ts +530 -0
  1148. package/src/core/brain/write-session/panel-target.ts +110 -0
  1149. package/src/core/brain/write-session/panel.ts +391 -0
  1150. package/src/core/brain/write-session/personas.ts +240 -0
  1151. package/src/core/brain/write-session/store.ts +382 -0
  1152. package/src/core/brain/write-session/types.ts +149 -0
  1153. package/src/core/brain/write-session/validate.ts +244 -0
  1154. package/src/core/brain/writeback-contract.ts +614 -0
  1155. package/src/core/brain/yaml-parse.ts +290 -0
  1156. package/src/core/config.ts +2362 -0
  1157. package/src/core/decision-model/advisory.ts +96 -0
  1158. package/src/core/decision-model/answerable.ts +103 -0
  1159. package/src/core/decision-model/answers.ts +162 -0
  1160. package/src/core/decision-model/config-types.ts +159 -0
  1161. package/src/core/decision-model/config.ts +892 -0
  1162. package/src/core/decision-model/contract.ts +225 -0
  1163. package/src/core/decision-model/converse.ts +363 -0
  1164. package/src/core/decision-model/diagnostics.ts +1004 -0
  1165. package/src/core/decision-model/egress-guard.ts +135 -0
  1166. package/src/core/decision-model/eval/grade.ts +536 -0
  1167. package/src/core/decision-model/eval/mark.ts +277 -0
  1168. package/src/core/decision-model/eval/take.ts +278 -0
  1169. package/src/core/decision-model/eval-spec.ts +316 -0
  1170. package/src/core/decision-model/latency.ts +24 -0
  1171. package/src/core/decision-model/llm-emulation.ts +436 -0
  1172. package/src/core/decision-model/pair-verdict.ts +386 -0
  1173. package/src/core/decision-model/presets.ts +360 -0
  1174. package/src/core/decision-model/provider-entries.ts +43 -0
  1175. package/src/core/decision-model/provider.ts +134 -0
  1176. package/src/core/decision-model/questions-skills.ts +78 -0
  1177. package/src/core/decision-model/questions-topics.ts +372 -0
  1178. package/src/core/decision-model/questions.ts +420 -0
  1179. package/src/core/decision-model/record.ts +473 -0
  1180. package/src/core/decision-model/reports/answerable.ts +198 -0
  1181. package/src/core/decision-model/reports/extract-prefilter.ts +295 -0
  1182. package/src/core/decision-model/reports/index.ts +76 -0
  1183. package/src/core/decision-model/reports/labels.ts +218 -0
  1184. package/src/core/decision-model/reports/pair-verdict.ts +232 -0
  1185. package/src/core/decision-model/reports/recall-inject.ts +175 -0
  1186. package/src/core/decision-model/reports/skills.ts +136 -0
  1187. package/src/core/decision-model/request-floor.ts +42 -0
  1188. package/src/core/decision-model/run.ts +408 -0
  1189. package/src/core/decision-model/state.ts +209 -0
  1190. package/src/core/decision-model/systemone.ts +257 -0
  1191. package/src/core/decision-model/thresholds-fit.ts +292 -0
  1192. package/src/core/decision-model/thresholds.ts +323 -0
  1193. package/src/core/decision-model/transport.ts +206 -0
  1194. package/src/core/decision-model/use-thresholds.ts +41 -0
  1195. package/src/core/decision-model/vercel-evaluate.ts +90 -0
  1196. package/src/core/derived-store-guard.ts +87 -0
  1197. package/src/core/diff.ts +37 -0
  1198. package/src/core/discipline/activity-git.ts +71 -0
  1199. package/src/core/discipline/activity-mtime.ts +76 -0
  1200. package/src/core/discipline/complexity.ts +204 -0
  1201. package/src/core/discipline/decision.ts +75 -0
  1202. package/src/core/discipline/legacy-jobs.ts +37 -0
  1203. package/src/core/discipline/log-counts.ts +59 -0
  1204. package/src/core/discipline/render.ts +109 -0
  1205. package/src/core/discipline/report.ts +139 -0
  1206. package/src/core/discipline/transcripts/claude-code.ts +78 -0
  1207. package/src/core/discipline/transcripts/codex.ts +77 -0
  1208. package/src/core/discipline/transcripts/cursor.ts +180 -0
  1209. package/src/core/discipline/transcripts/index.ts +86 -0
  1210. package/src/core/discipline/transcripts/types.ts +138 -0
  1211. package/src/core/discipline/vault-delta.ts +65 -0
  1212. package/src/core/discipline/window.ts +85 -0
  1213. package/src/core/doctor-hermes-parity.ts +300 -0
  1214. package/src/core/doctor-readiness.ts +1984 -0
  1215. package/src/core/doctor-selftest.ts +880 -0
  1216. package/src/core/doctor.ts +478 -0
  1217. package/src/core/egress/consent-stamp.ts +241 -0
  1218. package/src/core/egress/guard.ts +384 -0
  1219. package/src/core/egress/registry.ts +409 -0
  1220. package/src/core/fs/git-discovery.ts +262 -0
  1221. package/src/core/fs/ignore.ts +246 -0
  1222. package/src/core/fs-atomic.ts +640 -0
  1223. package/src/core/fs-identity.ts +80 -0
  1224. package/src/core/fs-lock.ts +580 -0
  1225. package/src/core/fs-stamp.ts +120 -0
  1226. package/src/core/fs-utils.ts +84 -0
  1227. package/src/core/graph/agent-scope.ts +147 -0
  1228. package/src/core/graph/frontmatter-relations.ts +55 -0
  1229. package/src/core/graph/mcp-config.ts +181 -0
  1230. package/src/core/graph/privacy-markers.ts +146 -0
  1231. package/src/core/graph/relation-vocab.ts +79 -0
  1232. package/src/core/graph/transport-reach.ts +97 -0
  1233. package/src/core/graph/unique-match.ts +43 -0
  1234. package/src/core/graph/visibility.ts +153 -0
  1235. package/src/core/hygiene/hardcoded-paths.ts +168 -0
  1236. package/src/core/hygiene/scan-repo.ts +214 -0
  1237. package/src/core/identity-reminder.ts +165 -0
  1238. package/src/core/install/adapters/_json-mcp.ts +591 -0
  1239. package/src/core/install/adapters/aider-wrapper.ts +181 -0
  1240. package/src/core/install/adapters/aider.ts +330 -0
  1241. package/src/core/install/adapters/all.ts +37 -0
  1242. package/src/core/install/adapters/codex.ts +595 -0
  1243. package/src/core/install/adapters/copilot-cli.ts +584 -0
  1244. package/src/core/install/adapters/cursor.ts +30 -0
  1245. package/src/core/install/adapters/gemini-cli.ts +23 -0
  1246. package/src/core/install/adapters/generic.ts +182 -0
  1247. package/src/core/install/adapters/grok.ts +261 -0
  1248. package/src/core/install/adapters/kiro.ts +27 -0
  1249. package/src/core/install/adapters/opencode.ts +863 -0
  1250. package/src/core/install/adapters/pi.ts +268 -0
  1251. package/src/core/install/command-probe.ts +287 -0
  1252. package/src/core/install/env.ts +69 -0
  1253. package/src/core/install/friction.ts +391 -0
  1254. package/src/core/install/grok-asset.ts +223 -0
  1255. package/src/core/install/grok-config.ts +100 -0
  1256. package/src/core/install/host-kinds.ts +34 -0
  1257. package/src/core/install/host-probe.ts +385 -0
  1258. package/src/core/install/identity.ts +52 -0
  1259. package/src/core/install/instruction-block.ts +537 -0
  1260. package/src/core/install/integrations.ts +25 -0
  1261. package/src/core/install/json-merge.ts +126 -0
  1262. package/src/core/install/jsonc.ts +789 -0
  1263. package/src/core/install/managed-block.ts +190 -0
  1264. package/src/core/install/manifest.ts +110 -0
  1265. package/src/core/install/opencode-plugin-asset.ts +43 -0
  1266. package/src/core/install/origin.ts +76 -0
  1267. package/src/core/install/ownership-measure.ts +291 -0
  1268. package/src/core/install/ownership.ts +1161 -0
  1269. package/src/core/install/payload-equals.ts +91 -0
  1270. package/src/core/install/payload-host.ts +160 -0
  1271. package/src/core/install/payload.ts +191 -0
  1272. package/src/core/install/registry.ts +46 -0
  1273. package/src/core/install/rules-block.ts +659 -0
  1274. package/src/core/install/session-paths.ts +41 -0
  1275. package/src/core/install/settings.ts +231 -0
  1276. package/src/core/install/types.ts +223 -0
  1277. package/src/core/install/update.ts +177 -0
  1278. package/src/core/integrity/degradation.ts +243 -0
  1279. package/src/core/integrity/digest.ts +183 -0
  1280. package/src/core/integrity/stamp.ts +208 -0
  1281. package/src/core/maintenance/dependency-tree.ts +89 -0
  1282. package/src/core/maintenance/ensure-current.ts +916 -0
  1283. package/src/core/maintenance/o2b-command.ts +223 -0
  1284. package/src/core/maintenance/self-heal-reindex.ts +265 -0
  1285. package/src/core/maintenance/self-heal-upgrade-state.ts +611 -0
  1286. package/src/core/maintenance/self-heal-upgrade.ts +275 -0
  1287. package/src/core/markdown-fence.ts +24 -0
  1288. package/src/core/math.ts +12 -0
  1289. package/src/core/migration-gate.ts +731 -0
  1290. package/src/core/origin-channel.ts +207 -0
  1291. package/src/core/partner/codegraph-health.ts +192 -0
  1292. package/src/core/partner/codegraph-report.ts +319 -0
  1293. package/src/core/partner/codegraph.ts +631 -0
  1294. package/src/core/path-safety.ts +381 -0
  1295. package/src/core/platform-dirs.ts +178 -0
  1296. package/src/core/process/run-program.ts +235 -0
  1297. package/src/core/project-manifests.ts +85 -0
  1298. package/src/core/reconciliation-report.ts +206 -0
  1299. package/src/core/record-path.ts +93 -0
  1300. package/src/core/redactor.ts +1362 -0
  1301. package/src/core/reliability/audit.ts +230 -0
  1302. package/src/core/reliability/command-bridge.ts +79 -0
  1303. package/src/core/reliability/lock.ts +49 -0
  1304. package/src/core/reliability/probe.ts +32 -0
  1305. package/src/core/removed-surfaces.ts +65 -0
  1306. package/src/core/route-scope.ts +106 -0
  1307. package/src/core/runtime/collect-garbage.ts +25 -0
  1308. package/src/core/runtime/host-facts.ts +721 -0
  1309. package/src/core/scope-key.ts +136 -0
  1310. package/src/core/search/activation/decay.ts +91 -0
  1311. package/src/core/search/activation/store.ts +311 -0
  1312. package/src/core/search/activation/types.ts +54 -0
  1313. package/src/core/search/authored-at.ts +60 -0
  1314. package/src/core/search/benchmark.ts +456 -0
  1315. package/src/core/search/brain-store/catch-up.ts +1155 -0
  1316. package/src/core/search/brain-store/changes.ts +164 -0
  1317. package/src/core/search/brain-store/constants.ts +112 -0
  1318. package/src/core/search/brain-store/entity-filter.ts +176 -0
  1319. package/src/core/search/brain-store/forgotten.ts +318 -0
  1320. package/src/core/search/brain-store/index-summary.ts +72 -0
  1321. package/src/core/search/brain-store/ingest.ts +204 -0
  1322. package/src/core/search/brain-store/location.ts +246 -0
  1323. package/src/core/search/brain-store/orphans.ts +113 -0
  1324. package/src/core/search/brain-store/prefix-hash.ts +49 -0
  1325. package/src/core/search/brain-store/record-text.ts +168 -0
  1326. package/src/core/search/brain-store/shard-scan.ts +169 -0
  1327. package/src/core/search/build-progress.ts +566 -0
  1328. package/src/core/search/capability-tier.ts +190 -0
  1329. package/src/core/search/cards.ts +291 -0
  1330. package/src/core/search/chunker.ts +880 -0
  1331. package/src/core/search/cjk-tokenizer.ts +165 -0
  1332. package/src/core/search/corpus-generation.ts +33 -0
  1333. package/src/core/search/correction-coupling.ts +93 -0
  1334. package/src/core/search/coverage.ts +358 -0
  1335. package/src/core/search/cross-vault.ts +418 -0
  1336. package/src/core/search/decider-step.ts +463 -0
  1337. package/src/core/search/disclosure-mode.ts +30 -0
  1338. package/src/core/search/embedding-spend.ts +261 -0
  1339. package/src/core/search/embeddings/configured-provider.ts +44 -0
  1340. package/src/core/search/embeddings/contract.ts +102 -0
  1341. package/src/core/search/embeddings/credential-report.ts +102 -0
  1342. package/src/core/search/embeddings/http-util.ts +435 -0
  1343. package/src/core/search/embeddings/local-provider.ts +83 -0
  1344. package/src/core/search/embeddings/null-provider.ts +37 -0
  1345. package/src/core/search/embeddings/openai-compat.ts +573 -0
  1346. package/src/core/search/embeddings/presets.ts +299 -0
  1347. package/src/core/search/embeddings/pricing.ts +100 -0
  1348. package/src/core/search/embeddings/provider-resolve.ts +99 -0
  1349. package/src/core/search/embeddings/provider-semaphore.ts +152 -0
  1350. package/src/core/search/embeddings/provider.ts +89 -0
  1351. package/src/core/search/embeddings/query-embed.ts +257 -0
  1352. package/src/core/search/embeddings/registry.ts +227 -0
  1353. package/src/core/search/embeddings/signature.ts +310 -0
  1354. package/src/core/search/embeddings/sunset.ts +544 -0
  1355. package/src/core/search/embeddings/zeroentropy.ts +318 -0
  1356. package/src/core/search/enrich.ts +161 -0
  1357. package/src/core/search/entities.ts +100 -0
  1358. package/src/core/search/entity-alias.ts +212 -0
  1359. package/src/core/search/entity-refresh.ts +122 -0
  1360. package/src/core/search/event-anchor-backfill.ts +130 -0
  1361. package/src/core/search/event-anchor.ts +232 -0
  1362. package/src/core/search/event-time-status.ts +81 -0
  1363. package/src/core/search/evidence-pack.ts +221 -0
  1364. package/src/core/search/evidence-verification.ts +170 -0
  1365. package/src/core/search/explain-envelope.ts +183 -0
  1366. package/src/core/search/feedback.ts +554 -0
  1367. package/src/core/search/freshen.ts +794 -0
  1368. package/src/core/search/fts-match-mode.ts +31 -0
  1369. package/src/core/search/fts-safety.ts +64 -0
  1370. package/src/core/search/fts.ts +130 -0
  1371. package/src/core/search/fusion.ts +139 -0
  1372. package/src/core/search/graph-phases.ts +119 -0
  1373. package/src/core/search/graph-prepass.ts +278 -0
  1374. package/src/core/search/index-estimate.ts +141 -0
  1375. package/src/core/search/index-watch.ts +88 -0
  1376. package/src/core/search/index.ts +1618 -0
  1377. package/src/core/search/indexer.ts +3405 -0
  1378. package/src/core/search/line-numbering.ts +114 -0
  1379. package/src/core/search/link-constraints.ts +110 -0
  1380. package/src/core/search/link-ratchet.ts +446 -0
  1381. package/src/core/search/links.ts +187 -0
  1382. package/src/core/search/mmr.ts +106 -0
  1383. package/src/core/search/parked-index.ts +635 -0
  1384. package/src/core/search/parked-set-aside.ts +256 -0
  1385. package/src/core/search/paths.ts +116 -0
  1386. package/src/core/search/pipeline/assemble.ts +629 -0
  1387. package/src/core/search/pipeline/attribution.ts +116 -0
  1388. package/src/core/search/pipeline/cache-slot.ts +481 -0
  1389. package/src/core/search/pipeline/candidate-signals.ts +376 -0
  1390. package/src/core/search/pipeline/event-time.ts +225 -0
  1391. package/src/core/search/pipeline/iterative-recall.ts +561 -0
  1392. package/src/core/search/pipeline/keyword-lane.ts +177 -0
  1393. package/src/core/search/pipeline/outcome.ts +531 -0
  1394. package/src/core/search/pipeline/pool-filters.ts +506 -0
  1395. package/src/core/search/pipeline/post-rank.ts +696 -0
  1396. package/src/core/search/pipeline/query-shape.ts +128 -0
  1397. package/src/core/search/pipeline/relational-arm.ts +755 -0
  1398. package/src/core/search/pipeline/request.ts +240 -0
  1399. package/src/core/search/pipeline/second-pass.ts +227 -0
  1400. package/src/core/search/pipeline/semantic-lane.ts +138 -0
  1401. package/src/core/search/pipeline/session-pool-cap.ts +164 -0
  1402. package/src/core/search/pipeline/store-open.ts +484 -0
  1403. package/src/core/search/pipeline/weights.ts +39 -0
  1404. package/src/core/search/price-recommendations.ts +75 -0
  1405. package/src/core/search/profiles.ts +75 -0
  1406. package/src/core/search/property-filter.ts +166 -0
  1407. package/src/core/search/property-pushdown.ts +447 -0
  1408. package/src/core/search/provider-consent.ts +377 -0
  1409. package/src/core/search/provider-probe.ts +167 -0
  1410. package/src/core/search/query-cache.ts +224 -0
  1411. package/src/core/search/query-expansion.ts +130 -0
  1412. package/src/core/search/query-plan.ts +211 -0
  1413. package/src/core/search/rank-adjust.ts +154 -0
  1414. package/src/core/search/ranker.ts +956 -0
  1415. package/src/core/search/recall-hint.ts +63 -0
  1416. package/src/core/search/recency.ts +67 -0
  1417. package/src/core/search/reinforce.ts +261 -0
  1418. package/src/core/search/relation-polarity.ts +255 -0
  1419. package/src/core/search/relational-fanout.ts +431 -0
  1420. package/src/core/search/relational-query.ts +76 -0
  1421. package/src/core/search/rerank/contract.ts +32 -0
  1422. package/src/core/search/rerank/cross-encoder.ts +207 -0
  1423. package/src/core/search/rerank/decision-model.ts +457 -0
  1424. package/src/core/search/rerank/failure.ts +129 -0
  1425. package/src/core/search/rerank/index.ts +298 -0
  1426. package/src/core/search/rerank/local.ts +83 -0
  1427. package/src/core/search/rerank/provider.ts +37 -0
  1428. package/src/core/search/rerank/registry.ts +170 -0
  1429. package/src/core/search/rerank/sunset.ts +135 -0
  1430. package/src/core/search/rerank-eval-gate.ts +222 -0
  1431. package/src/core/search/rerank-fit-check.ts +347 -0
  1432. package/src/core/search/result-filters.ts +601 -0
  1433. package/src/core/search/retrieval-trail.ts +585 -0
  1434. package/src/core/search/schema.ts +1693 -0
  1435. package/src/core/search/search-error.ts +94 -0
  1436. package/src/core/search/search-options-descriptor.ts +718 -0
  1437. package/src/core/search/search-result.ts +202 -0
  1438. package/src/core/search/search.ts +1309 -0
  1439. package/src/core/search/self-heal.ts +373 -0
  1440. package/src/core/search/semantic-phase.ts +336 -0
  1441. package/src/core/search/serialize.ts +216 -0
  1442. package/src/core/search/session-focus.ts +212 -0
  1443. package/src/core/search/snippet-window.ts +225 -0
  1444. package/src/core/search/store/aliases.ts +116 -0
  1445. package/src/core/search/store/atomic.ts +50 -0
  1446. package/src/core/search/store/brain-records.ts +362 -0
  1447. package/src/core/search/store/chunk-entities.ts +73 -0
  1448. package/src/core/search/store/chunks.ts +832 -0
  1449. package/src/core/search/store/counts.ts +367 -0
  1450. package/src/core/search/store/documents.ts +596 -0
  1451. package/src/core/search/store/embedder-audit.ts +199 -0
  1452. package/src/core/search/store/embedding-abi.ts +136 -0
  1453. package/src/core/search/store/entity-bridges.ts +54 -0
  1454. package/src/core/search/store/keyword.ts +222 -0
  1455. package/src/core/search/store/lifecycle.ts +769 -0
  1456. package/src/core/search/store/links.ts +315 -0
  1457. package/src/core/search/store/path-prefix.ts +93 -0
  1458. package/src/core/search/store/query-cache-table.ts +82 -0
  1459. package/src/core/search/store/relations.ts +251 -0
  1460. package/src/core/search/store/signal-exit.d.ts +11 -0
  1461. package/src/core/search/store/sql.ts +15 -0
  1462. package/src/core/search/store/state.ts +271 -0
  1463. package/src/core/search/store/tiers.ts +118 -0
  1464. package/src/core/search/store/trigram.ts +207 -0
  1465. package/src/core/search/store/vector-carry-over.ts +167 -0
  1466. package/src/core/search/store/vectors.ts +792 -0
  1467. package/src/core/search/store/visibility-tag.ts +123 -0
  1468. package/src/core/search/store/writer-lock.ts +1025 -0
  1469. package/src/core/search/store-exit.ts +67 -0
  1470. package/src/core/search/store-family.ts +111 -0
  1471. package/src/core/search/store.ts +1179 -0
  1472. package/src/core/search/structured-lanes.ts +64 -0
  1473. package/src/core/search/structured-query.ts +140 -0
  1474. package/src/core/search/surfacing-gate.ts +192 -0
  1475. package/src/core/search/surfacing-key.ts +196 -0
  1476. package/src/core/search/synonyms.ts +91 -0
  1477. package/src/core/search/temporal-bridge.ts +101 -0
  1478. package/src/core/search/temporal-intent.ts +226 -0
  1479. package/src/core/search/time-range.ts +147 -0
  1480. package/src/core/search/traversal.ts +156 -0
  1481. package/src/core/search/trigram-prefilter.ts +85 -0
  1482. package/src/core/search/tuning-store.ts +90 -0
  1483. package/src/core/search/tuning.ts +260 -0
  1484. package/src/core/search/types.ts +2078 -0
  1485. package/src/core/search/validity.ts +106 -0
  1486. package/src/core/search/vector-backfill.ts +226 -0
  1487. package/src/core/search/vector-guard.ts +44 -0
  1488. package/src/core/search/visibility-surface-registry.ts +1580 -0
  1489. package/src/core/search/walker.ts +201 -0
  1490. package/src/core/search/watch-runner.ts +103 -0
  1491. package/src/core/search/with-timeout.ts +35 -0
  1492. package/src/core/secret-ref.ts +165 -0
  1493. package/src/core/secret-resolver.ts +317 -0
  1494. package/src/core/shell-quote.ts +97 -0
  1495. package/src/core/sqlite-close.ts +31 -0
  1496. package/src/core/sqlite-file-set.ts +190 -0
  1497. package/src/core/state/machine-state.ts +385 -0
  1498. package/src/core/state/migrate.ts +1286 -0
  1499. package/src/core/state/state-moves.ts +260 -0
  1500. package/src/core/state/surfaces.ts +1872 -0
  1501. package/src/core/store/FORMAT.md +417 -0
  1502. package/src/core/store/appender.ts +277 -0
  1503. package/src/core/store/blobs.ts +323 -0
  1504. package/src/core/store/caller-reach.ts +45 -0
  1505. package/src/core/store/clock-floor.ts +34 -0
  1506. package/src/core/store/clock-store.ts +131 -0
  1507. package/src/core/store/compare.ts +11 -0
  1508. package/src/core/store/constants.ts +322 -0
  1509. package/src/core/store/content-write-gates.ts +23 -0
  1510. package/src/core/store/device-retirement.ts +67 -0
  1511. package/src/core/store/device-roster.ts +253 -0
  1512. package/src/core/store/device-state-scan.ts +102 -0
  1513. package/src/core/store/dual-write-records.ts +339 -0
  1514. package/src/core/store/dual-write.ts +461 -0
  1515. package/src/core/store/envelope.ts +249 -0
  1516. package/src/core/store/fold-pinned.ts +86 -0
  1517. package/src/core/store/fold-preferences.ts +263 -0
  1518. package/src/core/store/fold-setting-lists.ts +307 -0
  1519. package/src/core/store/fold-settings.ts +200 -0
  1520. package/src/core/store/fold-signals.ts +296 -0
  1521. package/src/core/store/fold.ts +184 -0
  1522. package/src/core/store/format-doc.ts +63 -0
  1523. package/src/core/store/fresh-switch.ts +98 -0
  1524. package/src/core/store/gc-hint.ts +28 -0
  1525. package/src/core/store/held-ledger.ts +112 -0
  1526. package/src/core/store/hlc.ts +91 -0
  1527. package/src/core/store/lane-dual-moves.ts +374 -0
  1528. package/src/core/store/lane-entry-store.ts +345 -0
  1529. package/src/core/store/lane-fold-cache.ts +285 -0
  1530. package/src/core/store/lane-pages.ts +739 -0
  1531. package/src/core/store/lane-paths.ts +172 -0
  1532. package/src/core/store/lane-raw.ts +105 -0
  1533. package/src/core/store/lane-records.ts +222 -0
  1534. package/src/core/store/legacy-tree.ts +84 -0
  1535. package/src/core/store/local-lock.ts +120 -0
  1536. package/src/core/store/migration-availability.ts +170 -0
  1537. package/src/core/store/newest-records.ts +294 -0
  1538. package/src/core/store/operation-privacy.ts +172 -0
  1539. package/src/core/store/operation-scope.ts +75 -0
  1540. package/src/core/store/own-appends.ts +76 -0
  1541. package/src/core/store/partition-leave.ts +157 -0
  1542. package/src/core/store/partition-view.ts +149 -0
  1543. package/src/core/store/private-page.ts +40 -0
  1544. package/src/core/store/private-region.ts +72 -0
  1545. package/src/core/store/process-lock.ts +209 -0
  1546. package/src/core/store/read/ledger-rows.ts +110 -0
  1547. package/src/core/store/read/log-events.ts +271 -0
  1548. package/src/core/store/read/memory-ids.ts +135 -0
  1549. package/src/core/store/read/pinned.ts +44 -0
  1550. package/src/core/store/read/preferences.ts +182 -0
  1551. package/src/core/store/read/protection-store.ts +152 -0
  1552. package/src/core/store/read/read-context.ts +44 -0
  1553. package/src/core/store/read/read-view.ts +131 -0
  1554. package/src/core/store/read/shards-from.ts +302 -0
  1555. package/src/core/store/read/signals.ts +197 -0
  1556. package/src/core/store/read/store-entities.ts +650 -0
  1557. package/src/core/store/read/stream-read.ts +552 -0
  1558. package/src/core/store/read/viewed-read.ts +106 -0
  1559. package/src/core/store/reader.ts +586 -0
  1560. package/src/core/store/reference-privacy.ts +491 -0
  1561. package/src/core/store/removal-backlog.ts +118 -0
  1562. package/src/core/store/safe-fs.ts +237 -0
  1563. package/src/core/store/seen-shards.ts +480 -0
  1564. package/src/core/store/shard-list.ts +85 -0
  1565. package/src/core/store/shard-quarantine-write.ts +175 -0
  1566. package/src/core/store/shard-quarantine.ts +397 -0
  1567. package/src/core/store/state-digest-check.ts +74 -0
  1568. package/src/core/store/state-digest-compare.ts +225 -0
  1569. package/src/core/store/state-digest.ts +572 -0
  1570. package/src/core/store/store-identity.ts +220 -0
  1571. package/src/core/store/store-init.ts +271 -0
  1572. package/src/core/store/store-location.ts +181 -0
  1573. package/src/core/store/store-only.ts +507 -0
  1574. package/src/core/store/store-open.ts +224 -0
  1575. package/src/core/store/store-paths.ts +360 -0
  1576. package/src/core/store/store-privacy.ts +82 -0
  1577. package/src/core/store/store-status.ts +154 -0
  1578. package/src/core/store/store-write.ts +309 -0
  1579. package/src/core/store/torn-line.ts +151 -0
  1580. package/src/core/store/ulid.ts +81 -0
  1581. package/src/core/store-migration/auto-claimed-writes.ts +120 -0
  1582. package/src/core/store-migration/auto-probe.ts +356 -0
  1583. package/src/core/store-migration/auto-report.ts +808 -0
  1584. package/src/core/store-migration/auto-state.ts +1858 -0
  1585. package/src/core/store-migration/auto-transition.ts +155 -0
  1586. package/src/core/store-migration/auto-worker.ts +1193 -0
  1587. package/src/core/store-migration/backup.ts +511 -0
  1588. package/src/core/store-migration/brain-settings.ts +288 -0
  1589. package/src/core/store-migration/catalogue.ts +124 -0
  1590. package/src/core/store-migration/cohort-here.ts +48 -0
  1591. package/src/core/store-migration/cohort-status.ts +195 -0
  1592. package/src/core/store-migration/convert.ts +588 -0
  1593. package/src/core/store-migration/destinations.ts +258 -0
  1594. package/src/core/store-migration/device-config.ts +165 -0
  1595. package/src/core/store-migration/device-evidence.ts +303 -0
  1596. package/src/core/store-migration/device-silence.ts +91 -0
  1597. package/src/core/store-migration/device-state-layout.ts +31 -0
  1598. package/src/core/store-migration/dry-run.ts +442 -0
  1599. package/src/core/store-migration/exporters.ts +597 -0
  1600. package/src/core/store-migration/gate-decision.ts +460 -0
  1601. package/src/core/store-migration/gate-state.ts +254 -0
  1602. package/src/core/store-migration/holder-liveness.ts +72 -0
  1603. package/src/core/store-migration/import-batch.ts +159 -0
  1604. package/src/core/store-migration/incremental-reads.ts +157 -0
  1605. package/src/core/store-migration/journal-scope.ts +167 -0
  1606. package/src/core/store-migration/journal.ts +652 -0
  1607. package/src/core/store-migration/lane-entry-records.ts +92 -0
  1608. package/src/core/store-migration/lane-id-repair.ts +421 -0
  1609. package/src/core/store-migration/lane-map.ts +394 -0
  1610. package/src/core/store-migration/later.ts +218 -0
  1611. package/src/core/store-migration/legacy-claims.ts +283 -0
  1612. package/src/core/store-migration/legacy-kept.ts +31 -0
  1613. package/src/core/store-migration/legacy-scan.ts +581 -0
  1614. package/src/core/store-migration/local-state.ts +161 -0
  1615. package/src/core/store-migration/migrate.ts +1030 -0
  1616. package/src/core/store-migration/migration-records.ts +395 -0
  1617. package/src/core/store-migration/outcome.ts +256 -0
  1618. package/src/core/store-migration/owner-only-copy.ts +51 -0
  1619. package/src/core/store-migration/process-identity.ts +91 -0
  1620. package/src/core/store-migration/quiesce.ts +359 -0
  1621. package/src/core/store-migration/removal-marker.ts +82 -0
  1622. package/src/core/store-migration/removal.ts +695 -0
  1623. package/src/core/store-migration/retire-adopted.ts +96 -0
  1624. package/src/core/store-migration/rollback.ts +764 -0
  1625. package/src/core/store-migration/row-records.ts +334 -0
  1626. package/src/core/store-migration/sizes.ts +38 -0
  1627. package/src/core/store-migration/spill-map.ts +328 -0
  1628. package/src/core/store-migration/surface-map.ts +446 -0
  1629. package/src/core/store-migration/sync-leftovers.ts +383 -0
  1630. package/src/core/store-migration/transition-watermark.ts +144 -0
  1631. package/src/core/store-migration/transition.ts +198 -0
  1632. package/src/core/store-migration/update-step.ts +153 -0
  1633. package/src/core/store-migration/worker-log.ts +139 -0
  1634. package/src/core/strings.ts +16 -0
  1635. package/src/core/surface/descriptor.ts +100 -0
  1636. package/src/core/surface/lexical-score.ts +164 -0
  1637. package/src/core/surface/skill-attach-decision.ts +495 -0
  1638. package/src/core/surface/skill-attach.ts +241 -0
  1639. package/src/core/surface/skill-offer.ts +84 -0
  1640. package/src/core/surface/skills-dir.ts +40 -0
  1641. package/src/core/surface/skills.ts +234 -0
  1642. package/src/core/tags.ts +114 -0
  1643. package/src/core/text/nearest-name.ts +146 -0
  1644. package/src/core/topics/actions.ts +672 -0
  1645. package/src/core/topics/candidates.ts +314 -0
  1646. package/src/core/topics/constants.ts +122 -0
  1647. package/src/core/topics/decide-auto.ts +138 -0
  1648. package/src/core/topics/decide-operations.ts +792 -0
  1649. package/src/core/topics/decide-produce.ts +125 -0
  1650. package/src/core/topics/decision-titles.ts +210 -0
  1651. package/src/core/topics/fold.ts +719 -0
  1652. package/src/core/topics/held-decisions.ts +278 -0
  1653. package/src/core/topics/held-records.ts +464 -0
  1654. package/src/core/topics/plan-outcome.ts +138 -0
  1655. package/src/core/topics/plan.ts +685 -0
  1656. package/src/core/topics/planning.ts +1192 -0
  1657. package/src/core/topics/read.ts +124 -0
  1658. package/src/core/topics/records.ts +204 -0
  1659. package/src/core/topics/review.ts +68 -0
  1660. package/src/core/topics/settings.ts +22 -0
  1661. package/src/core/topics/undo-fold.ts +43 -0
  1662. package/src/core/topics/verdict-writes.ts +257 -0
  1663. package/src/core/topics/verdicts.ts +181 -0
  1664. package/src/core/topics/wording-operation.ts +99 -0
  1665. package/src/core/topics/write.ts +230 -0
  1666. package/src/core/trust.ts +164 -0
  1667. package/src/core/types.ts +85 -0
  1668. package/src/core/validate.ts +196 -0
  1669. package/src/core/vault-adapter/bases.ts +104 -0
  1670. package/src/core/vault-adapter/codes.ts +8 -0
  1671. package/src/core/vault-adapter/index.ts +121 -0
  1672. package/src/core/vault-adapter/vault-binding.ts +398 -0
  1673. package/src/core/vault-adapter/wikilink-audits.ts +18 -0
  1674. package/src/core/vault-backing.ts +435 -0
  1675. package/src/core/vault-presence.ts +57 -0
  1676. package/src/core/vault-scope/defaults.ts +162 -0
  1677. package/src/core/vault-scope/index-admission.ts +79 -0
  1678. package/src/core/vault-scope/index.ts +559 -0
  1679. package/src/core/vault-unexaminable.ts +148 -0
  1680. package/src/core/vault.ts +1522 -0
  1681. package/src/core/version.ts +21 -0
  1682. package/src/core/view/auto-render.ts +222 -0
  1683. package/src/core/view/catch-up.ts +182 -0
  1684. package/src/core/view/constants.ts +139 -0
  1685. package/src/core/view/corrections.ts +309 -0
  1686. package/src/core/view/edit-record.ts +16 -0
  1687. package/src/core/view/i18n.ts +228 -0
  1688. package/src/core/view/lane-view-pages.ts +143 -0
  1689. package/src/core/view/line-diff.ts +171 -0
  1690. package/src/core/view/page-io.ts +522 -0
  1691. package/src/core/view/page-path.ts +103 -0
  1692. package/src/core/view/page-stats.ts +107 -0
  1693. package/src/core/view/pages.ts +451 -0
  1694. package/src/core/view/recover.ts +57 -0
  1695. package/src/core/view/render.ts +476 -0
  1696. package/src/core/view/retire.ts +346 -0
  1697. package/src/core/view/target.ts +170 -0
  1698. package/src/core/view/topic-edits.ts +299 -0
  1699. package/src/core/view/topic-pages.ts +437 -0
  1700. package/src/core/view/vault-guard.ts +222 -0
  1701. package/src/core/view/view-records.ts +326 -0
  1702. package/src/core/view/writer-fold.ts +124 -0
  1703. package/src/core/view/writer.ts +244 -0
  1704. package/src/core/write-binding/index.ts +431 -0
  1705. package/src/core/write-binding/prefix.ts +49 -0
  1706. package/src/mcp/argument-guard.ts +132 -0
  1707. package/src/mcp/artifact-store.ts +143 -0
  1708. package/src/mcp/brain/admin-policy-tools.ts +319 -0
  1709. package/src/mcp/brain/admin-tools.ts +417 -0
  1710. package/src/mcp/brain/agent-claim.ts +43 -0
  1711. package/src/mcp/brain/analytics-tools.ts +396 -0
  1712. package/src/mcp/brain/attest-tools.ts +145 -0
  1713. package/src/mcp/brain/brief-tools.ts +186 -0
  1714. package/src/mcp/brain/brief-view-tools.ts +655 -0
  1715. package/src/mcp/brain/calendar-tools.ts +303 -0
  1716. package/src/mcp/brain/changes-tools.ts +124 -0
  1717. package/src/mcp/brain/context-active-tools.ts +533 -0
  1718. package/src/mcp/brain/context-pinned-tools.ts +167 -0
  1719. package/src/mcp/brain/context-session-tools.ts +173 -0
  1720. package/src/mcp/brain/context-tools.ts +264 -0
  1721. package/src/mcp/brain/decisions-tools.ts +601 -0
  1722. package/src/mcp/brain/derive-tools.ts +89 -0
  1723. package/src/mcp/brain/design-note-tools.ts +140 -0
  1724. package/src/mcp/brain/device-path.ts +320 -0
  1725. package/src/mcp/brain/distill-tools.ts +207 -0
  1726. package/src/mcp/brain/dream-owner-tool.ts +171 -0
  1727. package/src/mcp/brain/dream-tools.ts +539 -0
  1728. package/src/mcp/brain/entity-tools.ts +179 -0
  1729. package/src/mcp/brain/evidence-tools.ts +222 -0
  1730. package/src/mcp/brain/expire-tools.ts +89 -0
  1731. package/src/mcp/brain/extract-tools.ts +237 -0
  1732. package/src/mcp/brain/feedback-tool.ts +724 -0
  1733. package/src/mcp/brain/feedback-tools.ts +293 -0
  1734. package/src/mcp/brain/generation-tools.ts +330 -0
  1735. package/src/mcp/brain/health-tools.ts +529 -0
  1736. package/src/mcp/brain/hygiene-tools.ts +494 -0
  1737. package/src/mcp/brain/ingest-batch-tools.ts +156 -0
  1738. package/src/mcp/brain/ingest-source-tools.ts +636 -0
  1739. package/src/mcp/brain/ingest-tools.ts +223 -0
  1740. package/src/mcp/brain/intake-args.ts +192 -0
  1741. package/src/mcp/brain/knowledge-claim-tools.ts +325 -0
  1742. package/src/mcp/brain/knowledge-lane-tools.ts +678 -0
  1743. package/src/mcp/brain/knowledge-tools.ts +354 -0
  1744. package/src/mcp/brain/knowledge-truth-tools.ts +416 -0
  1745. package/src/mcp/brain/landscape-tools.ts +61 -0
  1746. package/src/mcp/brain/lane-vault.ts +47 -0
  1747. package/src/mcp/brain/lifecycle-file-tools.ts +580 -0
  1748. package/src/mcp/brain/lifecycle-tools.ts +294 -0
  1749. package/src/mcp/brain/memory-bridge-tools.ts +160 -0
  1750. package/src/mcp/brain/ner-tools.ts +133 -0
  1751. package/src/mcp/brain/notes-shared.ts +212 -0
  1752. package/src/mcp/brain/notes-tools.ts +145 -0
  1753. package/src/mcp/brain/notes-write-tools.ts +488 -0
  1754. package/src/mcp/brain/pack-context-tools.ts +472 -0
  1755. package/src/mcp/brain/pack-preset-tools.ts +310 -0
  1756. package/src/mcp/brain/pack-receipt-tools.ts +512 -0
  1757. package/src/mcp/brain/pack-shared.ts +181 -0
  1758. package/src/mcp/brain/pack-tools.ts +463 -0
  1759. package/src/mcp/brain/pagination.ts +35 -0
  1760. package/src/mcp/brain/pledge-tools.ts +505 -0
  1761. package/src/mcp/brain/procedure-tools.ts +580 -0
  1762. package/src/mcp/brain/query-agent-tools.ts +220 -0
  1763. package/src/mcp/brain/query-serialize.ts +198 -0
  1764. package/src/mcp/brain/query-tools.ts +709 -0
  1765. package/src/mcp/brain/query-unlinked-tools.ts +135 -0
  1766. package/src/mcp/brain/query-writes-tools.ts +304 -0
  1767. package/src/mcp/brain/reach-events.ts +201 -0
  1768. package/src/mcp/brain/reach-readable.ts +145 -0
  1769. package/src/mcp/brain/recall-bench-tools.ts +388 -0
  1770. package/src/mcp/brain/recall-coerce-tools.ts +404 -0
  1771. package/src/mcp/brain/recall-outcome-tools.ts +268 -0
  1772. package/src/mcp/brain/recall-session-tools.ts +321 -0
  1773. package/src/mcp/brain/recall-tools.ts +569 -0
  1774. package/src/mcp/brain/receipt-tools.ts +236 -0
  1775. package/src/mcp/brain/research-tools.ts +98 -0
  1776. package/src/mcp/brain/review-tools.ts +320 -0
  1777. package/src/mcp/brain/settings-tools.ts +120 -0
  1778. package/src/mcp/brain/shared.ts +372 -0
  1779. package/src/mcp/brain/storage-tools.ts +176 -0
  1780. package/src/mcp/brain/synthesis-tools.ts +529 -0
  1781. package/src/mcp/brain/tension-tools.ts +243 -0
  1782. package/src/mcp/brain/time-bounds.ts +64 -0
  1783. package/src/mcp/brain/topic-tools.ts +240 -0
  1784. package/src/mcp/brain/workspace-tools.ts +370 -0
  1785. package/src/mcp/brain/write-batch-tools.ts +385 -0
  1786. package/src/mcp/brain-tools.ts +107 -0
  1787. package/src/mcp/capabilities.ts +162 -0
  1788. package/src/mcp/coerce.ts +372 -0
  1789. package/src/mcp/decision-answerable.ts +45 -0
  1790. package/src/mcp/drain.ts +204 -0
  1791. package/src/mcp/dream-executor.ts +493 -0
  1792. package/src/mcp/error-redaction.ts +91 -0
  1793. package/src/mcp/frozen-refusal.ts +206 -0
  1794. package/src/mcp/http.ts +715 -0
  1795. package/src/mcp/hydrate-tool.ts +82 -0
  1796. package/src/mcp/index.ts +26 -0
  1797. package/src/mcp/instruction-segments.ts +510 -0
  1798. package/src/mcp/instructions.ts +96 -0
  1799. package/src/mcp/output-contract.ts +62 -0
  1800. package/src/mcp/owner-scope-refusal.ts +144 -0
  1801. package/src/mcp/preview-budget.ts +142 -0
  1802. package/src/mcp/profiles.ts +153 -0
  1803. package/src/mcp/progress.ts +187 -0
  1804. package/src/mcp/protocol.ts +84 -0
  1805. package/src/mcp/reach-refusal.ts +108 -0
  1806. package/src/mcp/registry-guard.ts +465 -0
  1807. package/src/mcp/resources-backlink-readers.ts +95 -0
  1808. package/src/mcp/resources-digest-readers.ts +225 -0
  1809. package/src/mcp/resources-record-readers.ts +379 -0
  1810. package/src/mcp/resources-shared.ts +190 -0
  1811. package/src/mcp/resources-topic-readers.ts +40 -0
  1812. package/src/mcp/resources.ts +206 -0
  1813. package/src/mcp/schema-tools.ts +199 -0
  1814. package/src/mcp/search-tools.ts +2172 -0
  1815. package/src/mcp/server.ts +1082 -0
  1816. package/src/mcp/skill-tools.ts +284 -0
  1817. package/src/mcp/stdio.ts +467 -0
  1818. package/src/mcp/token-source.ts +65 -0
  1819. package/src/mcp/tool-contract.ts +387 -0
  1820. package/src/mcp/tool-error-codes.ts +564 -0
  1821. package/src/mcp/tools.ts +645 -0
  1822. package/src/mcp/vault-path-field.ts +264 -0
  1823. package/src/mcp/vault-unreachable.ts +23 -0
  1824. package/src/mcp/watchdog-tools.ts +46 -0
  1825. package/src/mcp/wiring-tools.ts +308 -0
  1826. package/src/openclaw/index.ts +215 -0
  1827. package/src/openclaw/openclaw-sdk.d.ts +65 -0
  1828. package/templates/brain-explorer.html +1375 -0
  1829. package/templates/brain-starter/inbox/sig-2026-05-10-strict-types.md +16 -0
  1830. package/templates/brain-starter/log/2026-05-12.md +19 -0
  1831. package/templates/brain-starter/log/2026-05-13.md +37 -0
  1832. package/templates/brain-starter/log/2026-05-14.md +43 -0
  1833. package/templates/brain-starter/log/2026-05-15.md +43 -0
  1834. package/templates/brain-starter/log/2026-05-16.md +31 -0
  1835. package/templates/brain-starter/log/2026-05-17.md +10 -0
  1836. package/templates/brain-starter/preferences/pref-changelog-every-release.md +25 -0
  1837. package/templates/brain-starter/preferences/pref-explicit-imports-only.md +25 -0
  1838. package/templates/brain-starter/preferences/pref-imperative-commit-messages.md +26 -0
  1839. package/templates/brain-starter/preferences/pref-no-unexplained-abbreviations.md +26 -0
  1840. package/templates/brain-starter/preferences/pref-prefer-bun-over-npx.md +25 -0
  1841. package/templates/brain-starter/preferences/pref-prefer-typed-errors.md +25 -0
  1842. package/templates/brain-starter/preferences/pref-russian-in-chat.md +25 -0
  1843. package/templates/brain-starter/preferences/pref-test-before-refactor.md +19 -0
  1844. package/templates/brain-starter/retired/ret-no-emojis-in-code.md +30 -0
  1845. package/templates/brain-starter/retired/ret-prefer-curl-over-wget.md +30 -0
  1846. package/templates/brain-starter/retired/ret-tabs-over-spaces.md +32 -0
  1847. package/templates/identity-reminder.hermes.txt +1 -0
  1848. package/templates/identity-reminder.openclaw.txt +1 -0
  1849. package/templates/identity-reminder.txt +1 -0
  1850. package/templates/install/aider-context.md.tmpl +40 -0
  1851. package/tests/fixtures/decision-model/recall-inject-take.json +760 -0
  1852. package/tests/fixtures/decision-model/rerank-take.json +1124 -0
@@ -0,0 +1,1858 @@
1
+ /**
2
+ * The automatic store migration's device-local state (change
3
+ * auto-store-migration, design D2). The worker that
4
+ * `ensureVaultCurrent` starts (`auto-worker.ts`) and the reporting
5
+ * surfaces (`auto-report.ts`, the doctor, the store status block) read
6
+ * and write it; nothing else does.
7
+ *
8
+ * Three files, one folder per vault per machine:
9
+ * `<state base>/open-second-brain/stores/auto-migration/<vault key>/`, the
10
+ * device-local folder of all stores (`storesStateDir`), which exists
11
+ * before any store does, is never inside a vault and is never synced. The
12
+ * folder does not move when the machine switches or rolls back, so the
13
+ * attempt that claims the lock, records a failure or writes the notice
14
+ * releases and clears the same files whichever layout it ends on, and a
15
+ * rollback never brings an old record back.
16
+ *
17
+ * - the WORKER LOCK, `auto-store-migration.lock`, so N starts at once
18
+ * start one worker. The claim is an exclusive create holding a JSON
19
+ * record with the claim token, the holder's pid and start identity,
20
+ * and the claim time, so the report can say since when and which
21
+ * process. The parent claims before it spawns, hands the claim to the
22
+ * child's pid, and the worker stamps its own start identity on it;
23
+ * the worker releases when it ends. Every claim, takeover, hand-over
24
+ * and release runs under a short device-local mutex beside the file,
25
+ * so a takeover can never leave two holders. A claim is stale when its
26
+ * holder is provably not running (the pid is gone, or now names
27
+ * another process: the rule of the migration gate, `quiesce.ts`); a
28
+ * provably running holder keeps it however long the run takes. When
29
+ * the holder cannot be told (no identity recorded or readable), the
30
+ * one-hour age rule of the other workers applies, and an mtime in the
31
+ * future counts as stale. That is the EXACT judgement, for the worker,
32
+ * the manual verb and the doctor. A session start and the runtime
33
+ * notices use the CHEAP one ({@link AUTO_MIGRATION_LOCK_JUDGE}): the pid
34
+ * alone, never an identity query, which can be a subprocess on Windows
35
+ * and macOS. The cheap judge never takes over a live pid's claim; past
36
+ * the age a holder is trusted for, the start leaves the claim to a
37
+ * worker that judges exactly ({@link autoMigrationClaimUndecided}).
38
+ * A claim file that cannot be read is never taken over. Every one of
39
+ * these answers is {@link decideClaim}'s, a pure function the callers
40
+ * gather the state for.
41
+ * - the STATE FILE, `auto-store-migration.json`: the last FAILED
42
+ * attempt (reason, consecutive count, manual command, and the
43
+ * cooldown's end, which doubles per consecutive failure) or the
44
+ * WAITING state of a later machine whose first machine's cut has not
45
+ * arrived. Waiting starts no cooldown: it is not a failure. Both are
46
+ * cleared by the attempt that succeeds.
47
+ * - the NOTICE, `store-migration-notice.json`: written once on success
48
+ * (the snapshot), shown once at a session start (with the rollback
49
+ * command), then cleared.
50
+ *
51
+ * A failure is a property of the device (a full disk, an unmapped file,
52
+ * a store root inside the vault), so the state is device-local and never
53
+ * synced; a peer migrates on its own answer.
54
+ *
55
+ * Leaf module on purpose: the doctor and the status block read the state
56
+ * without pulling the worker in.
57
+ */
58
+
59
+ import { latestWorkerLogAttempt } from "./worker-log.ts";
60
+ import { randomBytes } from "node:crypto";
61
+ import {
62
+ existsSync,
63
+ linkSync,
64
+ mkdirSync,
65
+ readdirSync,
66
+ readFileSync,
67
+ renameSync,
68
+ rmdirSync,
69
+ statSync,
70
+ unlinkSync,
71
+ writeFileSync,
72
+ type Stats,
73
+ } from "node:fs";
74
+ import { homedir } from "node:os";
75
+ import { dirname, join } from "node:path";
76
+
77
+ import { atomicWriteFileSync } from "../fs-atomic.ts";
78
+ import { canonicalVault } from "../migration-gate.ts";
79
+ // The cooldown math and the age rule are the self-heal upgrade's, reused:
80
+ // same base, same ceiling, same doubling rule, same one-hour takeover.
81
+ // Its module imports nothing from here.
82
+ import {
83
+ SELF_HEAL_UPGRADE_LOCK_STALE_MS,
84
+ SELF_HEAL_UPGRADE_MAX_COOLDOWN_MS,
85
+ selfHealUpgradeCooldownMs,
86
+ } from "../maintenance/self-heal-upgrade-state.ts";
87
+ import { processDirsEnv } from "../platform-dirs.ts";
88
+ import { vaultKey } from "../state/machine-state.ts";
89
+ import { isLockContention, withLocalLock } from "../store/local-lock.ts";
90
+ import { storesStateDir } from "../store/store-paths.ts";
91
+ import { holderLiveness, processAlive } from "./holder-liveness.ts";
92
+ import { processStartIdentity } from "./process-identity.ts";
93
+ import { tryCreateLockFile } from "../fs-lock.ts";
94
+
95
+ /**
96
+ * Suffix of the device-local file beside a vault's state folder that the
97
+ * worker's output goes to (a new attempt at every spawn, the last few kept). Beside the
98
+ * folder, not in it, so the folder still goes when its last record does.
99
+ */
100
+ export const AUTO_MIGRATION_WORKER_LOG_SUFFIX = ".worker.log";
101
+
102
+ /** At most this much of the worker's error output goes into a failure reason. */
103
+ const WORKER_LOG_TAIL_CHARS = 600;
104
+
105
+ /** Folder (in the folder of all stores) of the per-vault automatic migration state. */
106
+ export const AUTO_MIGRATION_STATE_DIR = "auto-migration";
107
+
108
+ /** Worker lock file name. */
109
+ export const AUTO_MIGRATION_LOCK_FILE = "auto-store-migration.lock";
110
+
111
+ /** Failure / waiting state file name. */
112
+ export const AUTO_MIGRATION_STATE_FILE = "auto-store-migration.json";
113
+
114
+ /** One-time success notice file name. */
115
+ export const AUTO_MIGRATION_NOTICE_FILE = "store-migration-notice.json";
116
+
117
+ /**
118
+ * The command the doctor, the status block and the notices name for a
119
+ * failed automatic migration.
120
+ */
121
+ export const AUTO_MIGRATION_MANUAL_COMMAND = "o2b brain migrate-store";
122
+
123
+ /** How the automatic migration rolls back, for the surfaces that say so. */
124
+ export const AUTO_MIGRATION_ROLLBACK_COMMAND = "o2b brain migrate-store --rollback";
125
+
126
+ /**
127
+ * How long a lock file that cannot be read (a claim being written right
128
+ * now, or a damaged file) holds before it is taken over.
129
+ */
130
+ export const AUTO_MIGRATION_UNREADABLE_LOCK_GRACE_MS = 10_000;
131
+
132
+ /**
133
+ * How far in the future a lock's mtime may be before it counts as stale:
134
+ * file times and the clock are read at different resolutions, so a claim
135
+ * written a moment ago can look a fraction of a second ahead.
136
+ */
137
+ const FUTURE_MTIME_TOLERANCE_MS = 60_000;
138
+
139
+ /**
140
+ * How a claim's holder is judged.
141
+ *
142
+ * - `exact`: the pid and, when one was recorded, its start identity
143
+ * (`holderLiveness`). Reading an identity can cost an external query
144
+ * (PowerShell on Windows, `ps` on macOS), up to a second or more: for
145
+ * the worker, the manual verb and the doctor, which can afford it.
146
+ * - `cheap`: the pid alone (one signal probe) and the claim's age, never
147
+ * an identity query, not even of this process: for a session start and
148
+ * the runtime notices, which must never wait on a subprocess. A live
149
+ * pid holds for {@link AUTO_MIGRATION_LIVE_PID_CEILING_MS} when an
150
+ * identity was recorded (a stamped worker), else by the one-hour age
151
+ * rule, as the exact judgement does for a holder it cannot tell apart.
152
+ */
153
+ export const AUTO_MIGRATION_LOCK_JUDGE = Object.freeze({
154
+ exact: "exact",
155
+ cheap: "cheap",
156
+ } as const);
157
+
158
+ export type AutoMigrationLockJudge =
159
+ (typeof AUTO_MIGRATION_LOCK_JUDGE)[keyof typeof AUTO_MIGRATION_LOCK_JUDGE];
160
+
161
+ export interface AutoMigrationLockOptions {
162
+ /**
163
+ * Told the worker a replaced claim was handed to when that worker never
164
+ * confirmed it ({@link LostAutoMigrationWorker}): the claimer records it.
165
+ */
166
+ readonly onLostWorker?: (worker: LostAutoMigrationWorker) => void;
167
+ /** How the holder of an existing claim is judged; `cheap` by default. */
168
+ readonly judge?: AutoMigrationLockJudge;
169
+ }
170
+
171
+ /**
172
+ * How long the cheap judgement lets a live pid with a recorded identity
173
+ * hold a claim without checking that identity: a day, the longest
174
+ * cooldown. Past it the claim is the worker's to judge exactly, so a pid
175
+ * reused by an unrelated long-lived process cannot hold the migration off
176
+ * for longer than that.
177
+ */
178
+ export const AUTO_MIGRATION_LIVE_PID_CEILING_MS = SELF_HEAL_UPGRADE_MAX_COOLDOWN_MS;
179
+
180
+ /** How long a claim, takeover or release waits for the lock's mutex. */
181
+ const LOCK_MUTEX_BUDGET_MS = 2000;
182
+
183
+ /**
184
+ * How long a claim of `judge` waits for the lock's mutex: the cheap one (a
185
+ * session start) never waits, because the holder may be an exact claimer
186
+ * querying a start identity (a subprocess on Windows and macOS); a busy
187
+ * mutex is a claim being made, so the start starts nothing. Everyone else
188
+ * waits the short budget.
189
+ */
190
+ export function claimMutexBudgetMs(judge: AutoMigrationLockJudge): number {
191
+ return judge === AUTO_MIGRATION_LOCK_JUDGE.cheap ? 0 : LOCK_MUTEX_BUDGET_MS;
192
+ }
193
+
194
+ export { selfHealUpgradeCooldownMs as selfHealMigrationCooldownMs };
195
+
196
+ /**
197
+ * The folder of the automatic migration state of `vault` on this machine.
198
+ * Independent of the layout: it is the same before the switch, after it,
199
+ * and after a rollback. Keyed by the vault's canonical path (links
200
+ * resolved, case folded on Windows: the form the migration gate compares
201
+ * by), so every spelling of one vault shares one worker lock. No release
202
+ * kept these folders under another spelling, so none is carried over.
203
+ */
204
+ export function autoMigrationStateDir(vault: string): string {
205
+ return join(
206
+ storesStateDir(processDirsEnv()),
207
+ AUTO_MIGRATION_STATE_DIR,
208
+ vaultKey(canonicalVault(vault)),
209
+ );
210
+ }
211
+
212
+ /** The worker's error output log for `vault` ({@link AUTO_MIGRATION_WORKER_LOG_SUFFIX}). */
213
+ export function autoMigrationWorkerLogPath(vault: string): string {
214
+ return `${autoMigrationStateDir(vault)}${AUTO_MIGRATION_WORKER_LOG_SUFFIX}`;
215
+ }
216
+
217
+ /**
218
+ * The last part of the worker's error output, reduced for the surfaces it
219
+ * reaches, or null when there is none (or it cannot be read).
220
+ */
221
+ export function readAutoMigrationWorkerLogTail(vault: string): string | null {
222
+ let text: string;
223
+ try {
224
+ text = readFileSync(autoMigrationWorkerLogPath(vault), "utf8");
225
+ } catch {
226
+ return null;
227
+ }
228
+ // Only what the latest attempt wrote: the log keeps the attempts before
229
+ // it too (`worker-log.ts`), and a lost worker is judged by its own output.
230
+ const trimmed = latestWorkerLogAttempt(text).trim();
231
+ if (trimmed.length === 0) return null;
232
+ const tail =
233
+ trimmed.length <= WORKER_LOG_TAIL_CHARS
234
+ ? trimmed
235
+ : `...${trimmed.slice(trimmed.length - WORKER_LOG_TAIL_CHARS + 3)}`;
236
+ return printable(tail).replace(/\s+/g, " ");
237
+ }
238
+
239
+ export function autoMigrationLockPath(vault: string): string {
240
+ return join(autoMigrationStateDir(vault), AUTO_MIGRATION_LOCK_FILE);
241
+ }
242
+
243
+ export function autoMigrationStatePath(vault: string): string {
244
+ return join(autoMigrationStateDir(vault), AUTO_MIGRATION_STATE_FILE);
245
+ }
246
+
247
+ export function autoMigrationNoticePath(vault: string): string {
248
+ return join(autoMigrationStateDir(vault), AUTO_MIGRATION_NOTICE_FILE);
249
+ }
250
+
251
+ /**
252
+ * Remove the vault's state folder once it is empty: the last of its files
253
+ * (the lock, the state record, the notice) was just dropped. A folder that
254
+ * still holds anything stays. Never throws.
255
+ */
256
+ function pruneAutoMigrationStateDir(vault: string): void {
257
+ try {
258
+ rmdirSync(autoMigrationStateDir(vault));
259
+ } catch {
260
+ // not empty, already gone, or held open for a moment: left as it is
261
+ }
262
+ }
263
+
264
+ function isMissing(err: unknown): boolean {
265
+ return (err as NodeJS.ErrnoException | null)?.code === "ENOENT";
266
+ }
267
+
268
+ /**
269
+ * Write one of the folder's files. The folder is removed when its last
270
+ * file goes ({@link pruneAutoMigrationStateDir}), so a write that loses
271
+ * that race makes the folder again once.
272
+ */
273
+ function writeStateFile(path: string, text: string): void {
274
+ mkdirSync(dirname(path), { recursive: true });
275
+ try {
276
+ atomicWriteFileSync(path, text);
277
+ } catch (err) {
278
+ if (!isMissing(err)) throw err;
279
+ mkdirSync(dirname(path), { recursive: true });
280
+ atomicWriteFileSync(path, text);
281
+ }
282
+ }
283
+
284
+ function messageOf(err: unknown): string {
285
+ return err instanceof Error ? err.message : String(err);
286
+ }
287
+
288
+ // ----- Worker lock ---------------------------------------------------------
289
+
290
+ /** What a live claim on the worker lock says. */
291
+ export interface AutoMigrationRunning {
292
+ /** The holder's pid; null when the claim cannot be read (being written, or a read error). */
293
+ readonly pid: number | null;
294
+ /** ISO-8601 instant the claim was made; null when the claim cannot be read. */
295
+ readonly since: string | null;
296
+ }
297
+
298
+ /**
299
+ * Whether a claim was handed to a spawned worker: `awaited` once the start
300
+ * that spawned it handed the claim to its pid, `confirmed` once the worker
301
+ * stamped the claim itself, null for a claim no start handed over (a
302
+ * start's own, a self-claiming worker's, the manual verb's).
303
+ */
304
+ export type ClaimWorker = "awaited" | "confirmed" | null;
305
+
306
+ interface LockRecord {
307
+ token: string;
308
+ pid: number;
309
+ /** The holder's start identity (`process-identity.ts`), or null when not known. */
310
+ started: string | null;
311
+ since: string;
312
+ worker: ClaimWorker;
313
+ }
314
+
315
+ function parseLockRecord(text: string): LockRecord | null {
316
+ try {
317
+ const raw: unknown = JSON.parse(text);
318
+ if (typeof raw !== "object" || raw === null) return null;
319
+ const r = raw as Record<string, unknown>;
320
+ if (typeof r["token"] !== "string") return null;
321
+ return {
322
+ token: r["token"],
323
+ pid: typeof r["pid"] === "number" ? r["pid"] : 0,
324
+ started: typeof r["started"] === "string" ? r["started"] : null,
325
+ since: typeof r["since"] === "string" ? r["since"] : new Date(0).toISOString(),
326
+ worker: r["worker"] === "awaited" || r["worker"] === "confirmed" ? r["worker"] : null,
327
+ };
328
+ } catch {
329
+ return null;
330
+ }
331
+ }
332
+
333
+ /**
334
+ * The claim file as one look at it found it. `ageMs` is the time since its
335
+ * mtime (negative when the mtime is in the future).
336
+ *
337
+ * - `absent`: no claim;
338
+ * - `unreadable`: it is there, and reading it failed for a reason other
339
+ * than its absence (a permission, an I/O error): nothing is known of
340
+ * its holder;
341
+ * - `torn`: it was read and holds no claim record (empty, a claim being
342
+ * written right now, or damaged);
343
+ * - `valid`: a claim record.
344
+ */
345
+ export type ClaimFile =
346
+ | { readonly kind: "absent" }
347
+ | { readonly kind: "unreadable"; readonly ageMs: number | null }
348
+ | { readonly kind: "torn"; readonly ageMs: number }
349
+ | {
350
+ readonly kind: "valid";
351
+ readonly ageMs: number;
352
+ readonly token: string;
353
+ readonly pid: number;
354
+ readonly started: string | null;
355
+ readonly since: string;
356
+ readonly worker: ClaimWorker;
357
+ };
358
+
359
+ /**
360
+ * What the asker can tell of a valid claim's holder: the cheap judgement
361
+ * sees only whether the pid is alive (`dead`, or `unknown` for a live
362
+ * pid); the exact one also compares the start identity (`dead` when the
363
+ * pid now names another process, `alive` when it is the recorded one,
364
+ * `unknown` when no identity was recorded or none can be read).
365
+ */
366
+ export type ClaimHolderSeen = "dead" | "alive" | "unknown";
367
+
368
+ /** Who asks about the claim, with what it brings. */
369
+ export type ClaimAsker =
370
+ /** A session start claiming before it spawns a worker (cheap). */
371
+ | { readonly who: "start" }
372
+ /** A worker, or the manual verb's own claim, claiming with the exact judgement. */
373
+ | { readonly who: "claim" }
374
+ /**
375
+ * A parent handing its claim to the worker's pid, or the worker stamping
376
+ * itself (`confirms`: the worker's own stamp, which confirms that it
377
+ * started).
378
+ */
379
+ | {
380
+ readonly who: "hand-over";
381
+ readonly token: string;
382
+ readonly pid: number;
383
+ readonly started: string | null;
384
+ readonly confirms: boolean;
385
+ }
386
+ /** The start that spawned worker `pid` on its claim `token` saw that process exit. */
387
+ | { readonly who: "exited"; readonly token: string; readonly pid: number }
388
+ /** The holder of `token` releasing it. */
389
+ | { readonly who: "release"; readonly token: string }
390
+ /**
391
+ * Reading whether a worker runs: the manual verb, the doctor and the
392
+ * report judge exactly, the runtime notices cheaply.
393
+ */
394
+ | { readonly who: "read"; readonly judge: AutoMigrationLockJudge };
395
+
396
+ /** The whole state one claim decision is taken on. */
397
+ export interface ClaimState {
398
+ readonly file: ClaimFile;
399
+ /** The holder as the asker's judgement sees it; asked only of a valid claim. */
400
+ readonly holder: ClaimHolderSeen;
401
+ /** Whether the claim's device-local mutex could be taken. */
402
+ readonly mutex: "free" | "busy";
403
+ readonly asker: ClaimAsker;
404
+ }
405
+
406
+ /**
407
+ * A worker a start spawned and handed its claim to, gone without ever
408
+ * confirming the claim: it could not run, or died before its first state
409
+ * record.
410
+ */
411
+ export interface LostAutoMigrationWorker {
412
+ readonly pid: number;
413
+ /** ISO-8601 instant the start claimed the lock for it. */
414
+ readonly since: string;
415
+ }
416
+
417
+ /** What one claim decision answers. */
418
+ export type ClaimDecision =
419
+ /**
420
+ * Make a new claim: remove the one there first (`replace`), then an
421
+ * exclusive create. `lost` names the worker the replaced claim was
422
+ * handed to when that worker never confirmed it: the claimer records it.
423
+ */
424
+ | {
425
+ readonly act: "claim";
426
+ readonly replace: boolean;
427
+ readonly lost: LostAutoMigrationWorker | null;
428
+ }
429
+ /**
430
+ * The claim was handed to a worker that is gone and never confirmed it:
431
+ * a reader reports it; the start that spawned it (`exited`) records it
432
+ * and removes the claim.
433
+ */
434
+ | { readonly act: "worker-lost"; readonly pid: number; readonly since: string }
435
+ /** The claim holds; nothing is changed. */
436
+ | { readonly act: "held" }
437
+ /**
438
+ * The cheap judgement cannot decide a live pid's claim past the age a
439
+ * holder is trusted for: a worker that judges exactly is to decide.
440
+ */
441
+ | { readonly act: "undecided" }
442
+ /** The mutex is busy: nothing is changed and nothing is claimed. */
443
+ | { readonly act: "busy" }
444
+ /**
445
+ * Hand-over: write the claim in the name of the given process, with the
446
+ * start identity `started` (the asker's, or the one the claim already
447
+ * records for that pid when the asker brings none).
448
+ */
449
+ | { readonly act: "stamp"; readonly started: string | null }
450
+ /** Hand-over: the claim is the asker's and already names it with an identity: kept. */
451
+ | { readonly act: "kept" }
452
+ /** Hand-over: the claim is no longer the asker's; nothing is changed. */
453
+ | { readonly act: "lost" }
454
+ /** Release: remove the asker's own claim. */
455
+ | { readonly act: "remove" }
456
+ /** Release: not the asker's claim (or the mutex is busy): left as it is. */
457
+ | { readonly act: "leave" }
458
+ /** Read: a worker runs (`pid` and `since` when the claim names them). */
459
+ | { readonly act: "running"; readonly pid: number | null; readonly since: string | null }
460
+ /** Read: no worker runs. */
461
+ | { readonly act: "idle" };
462
+
463
+ /**
464
+ * Who may hold, take over, hand over and release the worker claim: one
465
+ * pure function of the claim file, its holder as the asker sees it, the
466
+ * mutex and the asker (see the module header for the rules). No file is
467
+ * read and no process is asked here; the callers gather the state.
468
+ */
469
+ export function decideClaim(state: ClaimState): ClaimDecision {
470
+ const { file, holder, asker } = state;
471
+ if (asker.who === "hand-over") {
472
+ if (state.mutex === "busy" || file.kind !== "valid" || file.token !== asker.token) {
473
+ return { act: "lost" };
474
+ }
475
+ // The worker may have stamped itself before its parent hands over:
476
+ // its own identity is never replaced by an unknown one, and its
477
+ // confirmation never by the parent's "awaited".
478
+ const samePid = file.pid === asker.pid;
479
+ if (asker.confirms) {
480
+ const already =
481
+ samePid &&
482
+ file.worker === "confirmed" &&
483
+ (asker.started === null || asker.started === file.started);
484
+ if (already) return { act: "kept" };
485
+ } else if (
486
+ samePid &&
487
+ ((file.started !== null && asker.started === null) || file.worker === "confirmed")
488
+ ) {
489
+ return { act: "kept" };
490
+ }
491
+ return { act: "stamp", started: asker.started ?? (samePid ? file.started : null) };
492
+ }
493
+ if (asker.who === "exited") {
494
+ if (state.mutex === "busy") return { act: "leave" };
495
+ return file.kind === "valid" &&
496
+ file.token === asker.token &&
497
+ file.pid === asker.pid &&
498
+ file.worker === "awaited"
499
+ ? { act: "worker-lost", pid: file.pid, since: file.since }
500
+ : { act: "leave" };
501
+ }
502
+ if (asker.who === "release") {
503
+ if (state.mutex === "busy") return { act: "leave" };
504
+ return file.kind === "valid" && file.token === asker.token
505
+ ? { act: "remove" }
506
+ : { act: "leave" };
507
+ }
508
+ const judge =
509
+ asker.who === "read"
510
+ ? asker.judge
511
+ : asker.who === "start"
512
+ ? AUTO_MIGRATION_LOCK_JUDGE.cheap
513
+ : AUTO_MIGRATION_LOCK_JUDGE.exact;
514
+ const stale = claimStale(file, holder, judge);
515
+ // A claim handed to a worker that never confirmed it, and whose process
516
+ // is gone: that worker never ran its attempt.
517
+ const lost: LostAutoMigrationWorker | null =
518
+ stale === true && file.kind === "valid" && file.worker === "awaited" && holder === "dead"
519
+ ? { pid: file.pid, since: file.since }
520
+ : null;
521
+ if (asker.who === "read") {
522
+ // What the claimer of the same judgement leaves, a worker may hold: a
523
+ // claim being written or one that cannot be read names no process.
524
+ if (lost !== null) return { act: "worker-lost", ...lost };
525
+ if (stale === true) return { act: "idle" };
526
+ return file.kind === "valid"
527
+ ? { act: "running", pid: file.pid, since: file.since }
528
+ : { act: "running", pid: null, since: null };
529
+ }
530
+ if (state.mutex === "busy") return { act: "busy" };
531
+ if (stale === "undecided") return { act: "undecided" };
532
+ if (!stale) return { act: "held" };
533
+ return { act: "claim", replace: file.kind !== "absent", lost };
534
+ }
535
+
536
+ /**
537
+ * Whether a claim may be replaced: true, false, or `undecided` for a
538
+ * live pid's claim the cheap judgement keeps past the age it trusts it
539
+ * for.
540
+ */
541
+ function claimStale(
542
+ file: ClaimFile,
543
+ holder: ClaimHolderSeen,
544
+ judge: AutoMigrationLockJudge,
545
+ ): boolean | "undecided" {
546
+ if (file.kind === "absent") return true;
547
+ // A claim that cannot be read says nothing of its holder: it is never
548
+ // taken over (a permission or an I/O error is not a damaged claim).
549
+ if (file.kind === "unreadable") return false;
550
+ if (file.kind === "torn") {
551
+ return (
552
+ file.ageMs < -FUTURE_MTIME_TOLERANCE_MS ||
553
+ file.ageMs > AUTO_MIGRATION_UNREADABLE_LOCK_GRACE_MS
554
+ );
555
+ }
556
+ const future = file.ageMs < -FUTURE_MTIME_TOLERANCE_MS;
557
+ if (judge === AUTO_MIGRATION_LOCK_JUDGE.cheap) {
558
+ // A live pid's claim is never taken over without an identity check,
559
+ // however old: past the ceiling it is undecided, and the start leaves
560
+ // it to a worker that judges exactly.
561
+ if (holder === "dead") return true;
562
+ const ceiling =
563
+ file.started !== null ? AUTO_MIGRATION_LIVE_PID_CEILING_MS : SELF_HEAL_UPGRADE_LOCK_STALE_MS;
564
+ return future || file.ageMs > ceiling ? "undecided" : false;
565
+ }
566
+ if (holder === "dead") return true;
567
+ if (holder === "alive") return false;
568
+ return future || file.ageMs > SELF_HEAL_UPGRADE_LOCK_STALE_MS;
569
+ }
570
+
571
+ /** The claim file at `path` as it is now ({@link ClaimFile}). */
572
+ function claimFileAt(path: string, now: Date): ClaimFile {
573
+ let stat: Stats;
574
+ try {
575
+ stat = statSync(path);
576
+ } catch (err) {
577
+ if (isMissing(err)) return { kind: "absent" };
578
+ return { kind: "unreadable", ageMs: null };
579
+ }
580
+ const ageMs = now.getTime() - stat.mtimeMs;
581
+ let text: string;
582
+ try {
583
+ text = readFileSync(path, "utf8");
584
+ } catch (err) {
585
+ if (isMissing(err)) return { kind: "absent" };
586
+ return { kind: "unreadable", ageMs };
587
+ }
588
+ const record = parseLockRecord(text);
589
+ return record === null ? { kind: "torn", ageMs } : { kind: "valid", ageMs, ...record };
590
+ }
591
+
592
+ /**
593
+ * The holder of a valid claim as `judge` sees it: the cheap judgement
594
+ * asks only whether the pid is alive, the exact one its start identity
595
+ * too (an external query on some platforms).
596
+ */
597
+ function claimHolderSeen(file: ClaimFile, judge: AutoMigrationLockJudge): ClaimHolderSeen {
598
+ if (file.kind !== "valid") return "unknown";
599
+ if (judge === AUTO_MIGRATION_LOCK_JUDGE.cheap) {
600
+ return processAlive(file.pid) ? "unknown" : "dead";
601
+ }
602
+ return holderLiveness(file.pid, file.started);
603
+ }
604
+
605
+ /** The decision of `asker` on the claim at `path`, under the mutex when `mutex` is free. */
606
+ function claimStateAt(
607
+ path: string,
608
+ now: Date,
609
+ asker: ClaimAsker,
610
+ mutex: "free" | "busy",
611
+ ): ClaimState {
612
+ const file = claimFileAt(path, now);
613
+ const judge =
614
+ asker.who === "read"
615
+ ? asker.judge
616
+ : asker.who === "start"
617
+ ? AUTO_MIGRATION_LOCK_JUDGE.cheap
618
+ : AUTO_MIGRATION_LOCK_JUDGE.exact;
619
+ // The holder is judged only where the decision reads it: a valid claim
620
+ // a start, a claimer or a reader looks at.
621
+ const judged =
622
+ file.kind === "valid" &&
623
+ asker.who !== "hand-over" &&
624
+ asker.who !== "release" &&
625
+ asker.who !== "exited";
626
+ return { file, holder: judged ? claimHolderSeen(file, judge) : "unknown", mutex, asker };
627
+ }
628
+
629
+ function judgeOf(opts: AutoMigrationLockOptions): AutoMigrationLockJudge {
630
+ return opts.judge ?? AUTO_MIGRATION_LOCK_JUDGE.cheap;
631
+ }
632
+
633
+ /**
634
+ * Run `fn` under the lock's device-local mutex. Returns `fallback` when
635
+ * another process holds the mutex past the short budget.
636
+ */
637
+ function underMutex<T>(
638
+ path: string,
639
+ fn: () => T,
640
+ fallback: T,
641
+ budgetMs: number = LOCK_MUTEX_BUDGET_MS,
642
+ ): T {
643
+ try {
644
+ return withLocalLock(path, fn, budgetMs);
645
+ } catch (err) {
646
+ if (isLockContention(err)) return fallback;
647
+ throw err;
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Claim the worker lock without waiting long: under the mutex, the claim
653
+ * there is judged ({@link decideClaim}), a stale one removed and an
654
+ * exclusive create writes the new one. Returns the token, or null when a
655
+ * live claim exists (or another claim is being made right now).
656
+ */
657
+ export function claimAutoMigrationLock(
658
+ vault: string,
659
+ now: Date,
660
+ opts: AutoMigrationLockOptions = {},
661
+ ): string | null {
662
+ const judge = judgeOf(opts);
663
+ const path = autoMigrationLockPath(vault);
664
+ mkdirSync(dirname(path), { recursive: true });
665
+ // The cheap claim records no identity: reading even this process's own
666
+ // can be an external query. A worker stamps its own when it starts.
667
+ const started =
668
+ judge === AUTO_MIGRATION_LOCK_JUDGE.exact ? processStartIdentity(process.pid) : null;
669
+ const asker: ClaimAsker =
670
+ judge === AUTO_MIGRATION_LOCK_JUDGE.cheap ? { who: "start" } : { who: "claim" };
671
+ let lost: LostAutoMigrationWorker | null = null;
672
+ const claim = (): string | null =>
673
+ underMutex(
674
+ path,
675
+ (): string | null => {
676
+ const decision = decideClaim(claimStateAt(path, now, asker, "free"));
677
+ if (decision.act !== "claim") return null;
678
+ lost = decision.lost;
679
+ if (decision.replace) {
680
+ try {
681
+ unlinkSync(path);
682
+ } catch (err) {
683
+ if (!isMissing(err)) throw err;
684
+ }
685
+ }
686
+ const token = randomBytes(16).toString("hex");
687
+ const record: LockRecord = {
688
+ token,
689
+ pid: process.pid,
690
+ started,
691
+ since: now.toISOString(),
692
+ worker: null,
693
+ };
694
+ // On Windows the claim just unlinked, or a release by another
695
+ // process, can still hold the name for a moment: the create is made
696
+ // again over a few tens of milliseconds (`fs-lock.ts`), and a name
697
+ // still refused after that is a claim to try again later. A pruned
698
+ // folder (ENOENT) is not held and goes to the retry below. The
699
+ // create and the record are two steps: a record that cannot be
700
+ // written is not a claim someone holds, so the file the create made
701
+ // is removed again and the write's error is the answer.
702
+ const outcome = tryCreateLockFile(path, (fd) => {
703
+ writeFileSync(fd, JSON.stringify(record));
704
+ });
705
+ return "created" in outcome ? token : null;
706
+ },
707
+ null,
708
+ claimMutexBudgetMs(judge),
709
+ );
710
+ let token: string | null;
711
+ try {
712
+ token = claim();
713
+ } catch (err) {
714
+ // The folder was pruned between its creation and the claim: once more.
715
+ if (!isMissing(err)) throw err;
716
+ mkdirSync(dirname(path), { recursive: true });
717
+ token = claim();
718
+ }
719
+ if (token !== null && lost !== null) opts.onLostWorker?.(lost);
720
+ return token;
721
+ }
722
+
723
+ /**
724
+ * Whether `token` is the claim on the worker lock right now: `owned`,
725
+ * `lost` (no claim, or another one), or `unreadable` (the claim file is
726
+ * there and cannot be read, which says nothing of whose it is).
727
+ */
728
+ export function autoMigrationClaimOwnership(
729
+ vault: string,
730
+ token: string,
731
+ ): "owned" | "lost" | "unreadable" {
732
+ const file = claimFileAt(autoMigrationLockPath(vault), new Date());
733
+ if (file.kind === "unreadable") return "unreadable";
734
+ return file.kind === "valid" && file.token === token ? "owned" : "lost";
735
+ }
736
+
737
+ /** A write under the worker claim refused: the claim is not the writer's (or cannot be told). */
738
+ export class AutoMigrationClaimLostError extends Error {
739
+ constructor(readonly ownership: "lost" | "unreadable" | "busy") {
740
+ super(
741
+ ownership === "busy"
742
+ ? "the worker claim's mutex stayed busy, so this worker cannot tell that it still holds it"
743
+ : ownership === "unreadable"
744
+ ? "the worker claim cannot be read, so this worker cannot tell that it still holds it"
745
+ : "the worker claim was taken over; this worker writes nothing more",
746
+ );
747
+ this.name = "AutoMigrationClaimLostError";
748
+ }
749
+ }
750
+
751
+ /**
752
+ * Run `write` only while `token` is the claim on the worker lock: the
753
+ * check and the write are one step under the claim's mutex, which every
754
+ * claim and takeover also takes, so a worker whose claim was taken over
755
+ * can never write after the takeover. Throws
756
+ * {@link AutoMigrationClaimLostError} (and writes nothing) otherwise.
757
+ */
758
+ export function underOwnAutoMigrationClaim<T>(
759
+ vault: string,
760
+ token: string,
761
+ write: () => T,
762
+ budgetMs: number = LOCK_MUTEX_BUDGET_MS,
763
+ ): T {
764
+ const path = autoMigrationLockPath(vault);
765
+ let refused: "lost" | "unreadable" | "busy" = "busy";
766
+ let done = false;
767
+ let result: T | undefined;
768
+ underMutex(
769
+ path,
770
+ (): boolean => {
771
+ const ownership = autoMigrationClaimOwnership(vault, token);
772
+ if (ownership !== "owned") {
773
+ refused = ownership;
774
+ return false;
775
+ }
776
+ result = write();
777
+ done = true;
778
+ return true;
779
+ },
780
+ false,
781
+ budgetMs,
782
+ );
783
+ if (!done) throw new AutoMigrationClaimLostError(refused);
784
+ return result as T;
785
+ }
786
+
787
+ /** Whether `token` is the claim on the worker lock right now ({@link autoMigrationClaimOwnership}). */
788
+ export function ownsAutoMigrationLock(vault: string, token: string): boolean {
789
+ return autoMigrationClaimOwnership(vault, token) === "owned";
790
+ }
791
+
792
+ /**
793
+ * Put the claim `token` in the name of process `pid` (start identity
794
+ * `started`, or null when not known): the parent hands its claim to the
795
+ * worker it spawned (the claim then awaits the worker's confirmation),
796
+ * and the worker stamps its own identity on it (`confirms`), which
797
+ * confirms that it started. Returns whether the claim was still
798
+ * `token`'s; a claim taken over meanwhile is left alone
799
+ * ({@link decideClaim}).
800
+ */
801
+ export function handAutoMigrationLock(
802
+ vault: string,
803
+ token: string,
804
+ pid: number,
805
+ started: string | null,
806
+ confirms = false,
807
+ ): boolean {
808
+ const path = autoMigrationLockPath(vault);
809
+ return underMutex(
810
+ path,
811
+ (): boolean => {
812
+ const state = claimStateAt(
813
+ path,
814
+ new Date(),
815
+ { who: "hand-over", token, pid, started, confirms },
816
+ "free",
817
+ );
818
+ const decision = decideClaim(state);
819
+ if (decision.act === "lost") return false;
820
+ if (decision.act === "stamp" && state.file.kind === "valid") {
821
+ const { token: t, since } = state.file;
822
+ const record: LockRecord = {
823
+ token: t,
824
+ pid,
825
+ started: decision.started,
826
+ since,
827
+ worker: confirms ? "confirmed" : "awaited",
828
+ };
829
+ atomicWriteFileSync(path, JSON.stringify(record));
830
+ }
831
+ return true;
832
+ },
833
+ false,
834
+ );
835
+ }
836
+
837
+ /**
838
+ * The start that spawned worker `pid` on its claim `token` saw it exit:
839
+ * when the worker never confirmed the claim ({@link decideClaim}'s
840
+ * `worker-lost`), its failure is recorded ({@link recordLostAutoMigrationWorker})
841
+ * and the claim removed, so the next starts back off and every surface
842
+ * names it. Never waits for the mutex; never throws. Returns whether it
843
+ * recorded the worker as lost.
844
+ */
845
+ export function settleExitedAutoMigrationWorker(
846
+ vault: string,
847
+ token: string,
848
+ pid: number,
849
+ exit: string,
850
+ now: Date = new Date(),
851
+ ): boolean {
852
+ const path = autoMigrationLockPath(vault);
853
+ try {
854
+ return underMutex(
855
+ path,
856
+ (): boolean => {
857
+ const decision = decideClaim(
858
+ claimStateAt(path, now, { who: "exited", token, pid }, "free"),
859
+ );
860
+ if (decision.act !== "worker-lost") return false;
861
+ recordLostAutoMigrationWorker(vault, decision, now, exit);
862
+ try {
863
+ unlinkSync(path);
864
+ } catch {
865
+ // already gone
866
+ }
867
+ return true;
868
+ },
869
+ false,
870
+ 0,
871
+ );
872
+ } catch {
873
+ return false;
874
+ }
875
+ }
876
+
877
+ /** The lost worker a reader sees on the claim, or null ({@link decideClaim}'s `worker-lost`). */
878
+ export function readLostAutoMigrationWorker(
879
+ vault: string,
880
+ now: Date = new Date(),
881
+ opts: AutoMigrationLockOptions = {},
882
+ ): LostAutoMigrationWorker | null {
883
+ const path = autoMigrationLockPath(vault);
884
+ const decision = decideClaim(
885
+ claimStateAt(path, now, { who: "read", judge: judgeOf(opts) }, "free"),
886
+ );
887
+ return decision.act === "worker-lost" ? { pid: decision.pid, since: decision.since } : null;
888
+ }
889
+
890
+ /**
891
+ * The reason a lost worker is recorded with: what became of it, its exit
892
+ * when the start saw it, the tail of its error output, and the log that
893
+ * holds the whole of it.
894
+ */
895
+ export function describeLostAutoMigrationWorker(
896
+ vault: string,
897
+ worker: LostAutoMigrationWorker,
898
+ exit: string | null,
899
+ ): string {
900
+ const tail = readAutoMigrationWorkerLogTail(vault);
901
+ return (
902
+ `the automatic migration worker (process ${worker.pid}, started at ${worker.since}) ` +
903
+ `exited before it started${exit !== null ? ` (${exit})` : ""}` +
904
+ (tail !== null ? `; its error output: ${tail}` : "; it wrote no error output") +
905
+ ` (log: ${autoMigrationWorkerLogPath(vault)})`
906
+ );
907
+ }
908
+
909
+ /**
910
+ * Release the claim `token` made. A lock that is no longer ours (taken
911
+ * over as stale by another process) is left alone. Never throws.
912
+ *
913
+ * The check and the removal are one step under the mutex. When the mutex
914
+ * stays busy the claim is left: a takeover may be replacing it right now
915
+ * (the exact judge takes over a holder whose identity cannot be read past
916
+ * the age rule), and an unlocked removal could delete the successor's
917
+ * claim. The claim left
918
+ * behind is stale once this process ends.
919
+ */
920
+ export function releaseAutoMigrationLock(vault: string, token: string): void {
921
+ const path = autoMigrationLockPath(vault);
922
+ const release = (): void => {
923
+ const decision = decideClaim(claimStateAt(path, new Date(), { who: "release", token }, "free"));
924
+ if (decision.act !== "remove") return;
925
+ try {
926
+ unlinkSync(path);
927
+ } catch {
928
+ // already gone
929
+ }
930
+ };
931
+ try {
932
+ underMutex(path, () => (release(), true), false);
933
+ } catch {
934
+ // Nothing left to do: a claim left behind is stale once this process ends.
935
+ }
936
+ pruneAutoMigrationStateDir(vault);
937
+ }
938
+
939
+ /**
940
+ * The `--auto` value of a worker started with no claim of its own: it
941
+ * claims the lock itself with the exact judge. Claim tokens are 32 hex
942
+ * characters, so it is never one.
943
+ */
944
+ export const AUTO_MIGRATION_SELF_CLAIM = "self";
945
+
946
+ /**
947
+ * Whether a claim the cheap judge keeps (its pid is alive) is past the age
948
+ * a running holder is trusted for without an identity check: the pid may
949
+ * be the worker, hung or slow, or a later process that reuses it. A start
950
+ * cannot tell them apart, so it starts a worker that claims with the exact
951
+ * judge, which takes the claim over only from a holder that is gone.
952
+ */
953
+ export function autoMigrationClaimUndecided(vault: string, now: Date): boolean {
954
+ const path = autoMigrationLockPath(vault);
955
+ return decideClaim(claimStateAt(path, now, { who: "start" }, "free")).act === "undecided";
956
+ }
957
+
958
+ /** "process <pid>, since <time>", or what a claim that cannot be read leaves to say. */
959
+ export function describeAutoMigrationRunning(running: AutoMigrationRunning): string {
960
+ return running.pid !== null && running.since !== null
961
+ ? `process ${running.pid}, since ${running.since}`
962
+ : "its claim on this vault cannot be read right now";
963
+ }
964
+
965
+ /** What a live (not stale) claim says, for the reporting surfaces. */
966
+ export function readAutoMigrationRunning(
967
+ vault: string,
968
+ now: Date = new Date(),
969
+ opts: AutoMigrationLockOptions = {},
970
+ ): AutoMigrationRunning | null {
971
+ const path = autoMigrationLockPath(vault);
972
+ const decision = decideClaim(
973
+ claimStateAt(path, now, { who: "read", judge: judgeOf(opts) }, "free"),
974
+ );
975
+ return decision.act === "running" ? { pid: decision.pid, since: decision.since } : null;
976
+ }
977
+
978
+ // ----- Failure and waiting state ------------------------------------------
979
+
980
+ /** One recorded failed attempt of the automatic migration. */
981
+ export interface AutoMigrationFailure {
982
+ readonly state: "failed";
983
+ /** ISO-8601 instant of the last failed attempt. */
984
+ readonly failedAt: string;
985
+ /** The failure, as the attempt reported it. */
986
+ readonly error: string;
987
+ /** Attempts in a row that failed, this one included. At least 1. */
988
+ readonly consecutiveFailures: number;
989
+ /** ISO-8601 instant from which an automatic attempt is due again. */
990
+ readonly retryAfter: string;
991
+ /** The command the operator can run instead of waiting. */
992
+ readonly manualCommand: string;
993
+ /**
994
+ * True for the record an attempt writes BEFORE it starts
995
+ * ({@link recordAutoMigrationAttempt}): the attempt has not reported
996
+ * how it ended (it runs, it was killed, or it could not write its
997
+ * outcome). It already carries the cooldown a failure would start, so
998
+ * an attempt that cannot record its failure still holds the next ones
999
+ * off.
1000
+ */
1001
+ readonly attempt: boolean;
1002
+ /**
1003
+ * The success outputs this attempt already wrote (the metrics row, the
1004
+ * brain log line, the one-time notice), each marked right after it was
1005
+ * written: a pass that finishes the attempt later writes only the ones
1006
+ * not marked, so an output that failed is retried on its own and none
1007
+ * is written twice.
1008
+ */
1009
+ readonly written: AutoMigrationSuccessWritten;
1010
+ /**
1011
+ * The run id of the stopped migration run's gate this attempt should
1012
+ * have opened and could not ({@link recordAutoMigrationGateOwed}), or
1013
+ * null: the next start opens it before anything else.
1014
+ */
1015
+ readonly gateOwed: string | null;
1016
+ }
1017
+
1018
+ /** Which success outputs an attempt wrote (see {@link AutoMigrationFailure.written}). */
1019
+ export interface AutoMigrationSuccessWritten {
1020
+ readonly row: boolean;
1021
+ readonly log: boolean;
1022
+ readonly notice: boolean;
1023
+ }
1024
+
1025
+ /** The success outputs, by the key each is marked under. */
1026
+ export type AutoMigrationSuccessOutput = keyof AutoMigrationSuccessWritten;
1027
+
1028
+ const NOTHING_WRITTEN: AutoMigrationSuccessWritten = Object.freeze({
1029
+ row: false,
1030
+ log: false,
1031
+ notice: false,
1032
+ });
1033
+
1034
+ function writtenOf(raw: unknown): AutoMigrationSuccessWritten {
1035
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return NOTHING_WRITTEN;
1036
+ const r = raw as Record<string, unknown>;
1037
+ return { row: r["row"] === true, log: r["log"] === true, notice: r["notice"] === true };
1038
+ }
1039
+
1040
+ /** A later machine whose first machine's cut has not arrived. */
1041
+ export interface AutoMigrationWaiting {
1042
+ readonly state: "waiting";
1043
+ /** ISO-8601 instant the waiting state was last recorded. */
1044
+ readonly since: string;
1045
+ /** `<partition>/<shard>` entries the local store does not hold yet. */
1046
+ readonly missing: ReadonlyArray<string>;
1047
+ /** Devices whose completion record this machine waits on. */
1048
+ readonly firstMachines: ReadonlyArray<string>;
1049
+ /** What this machine waits for, in one operator sentence, when it is not a cut. */
1050
+ readonly reason: string | null;
1051
+ /**
1052
+ * It waits for a store another device created for this vault to arrive
1053
+ * (no store here yet): a start starts no worker for it until a store is
1054
+ * there, or until {@link AUTO_MIGRATION_WAIT_RECHECK_MS} after `since`.
1055
+ */
1056
+ readonly awaitsStore: boolean;
1057
+ }
1058
+
1059
+ /**
1060
+ * How long a start trusts a remembered "waits for another device's store"
1061
+ * before a worker looks at the synced log again.
1062
+ */
1063
+ export const AUTO_MIGRATION_WAIT_RECHECK_MS = 24 * 60 * 60_000;
1064
+
1065
+ /**
1066
+ * Whether a start still trusts the remembered wait for another device's
1067
+ * store at `now`: recorded less than a day ago (and not in the future).
1068
+ */
1069
+ export function autoMigrationWaitStillFresh(waiting: AutoMigrationWaiting, now: Date): boolean {
1070
+ if (!waiting.awaitsStore) return false;
1071
+ const since = Date.parse(waiting.since);
1072
+ if (!Number.isFinite(since) || since > now.getTime() + 60_000) return false;
1073
+ return now.getTime() - since < AUTO_MIGRATION_WAIT_RECHECK_MS;
1074
+ }
1075
+
1076
+ export type AutoMigrationState = AutoMigrationFailure | AutoMigrationWaiting;
1077
+
1078
+ function readStateRecord(vault: string): AutoMigrationState | null {
1079
+ const path = autoMigrationStatePath(vault);
1080
+ try {
1081
+ let text: string;
1082
+ try {
1083
+ text = readFileSync(path, "utf8");
1084
+ } catch (err) {
1085
+ // Only an absent file is no record; a folder or file that cannot be
1086
+ // read is the damaged record below.
1087
+ const code = (err as NodeJS.ErrnoException | null)?.code;
1088
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
1089
+ throw err;
1090
+ }
1091
+ const raw: unknown = JSON.parse(text);
1092
+ if (typeof raw !== "object" || raw === null) throw new Error("not a JSON object");
1093
+ const r = raw as Record<string, unknown>;
1094
+ if (r["state"] === "waiting") {
1095
+ const missing = Array.isArray(r["missing"])
1096
+ ? r["missing"].filter((m): m is string => typeof m === "string")
1097
+ : [];
1098
+ const firstMachines = Array.isArray(r["first_machines"])
1099
+ ? r["first_machines"].filter((m): m is string => typeof m === "string")
1100
+ : [];
1101
+ return {
1102
+ state: "waiting",
1103
+ since: typeof r["since"] === "string" ? r["since"] : new Date(0).toISOString(),
1104
+ missing,
1105
+ firstMachines,
1106
+ reason: typeof r["reason"] === "string" ? r["reason"] : null,
1107
+ awaitsStore: r["awaits_store"] === true,
1108
+ };
1109
+ }
1110
+ if (r["state"] === "failed" && typeof r["error"] === "string") {
1111
+ const consecutive =
1112
+ typeof r["consecutive_failures"] === "number" && r["consecutive_failures"] >= 1
1113
+ ? Math.floor(r["consecutive_failures"])
1114
+ : 1;
1115
+ return {
1116
+ state: "failed",
1117
+ failedAt: typeof r["failed_at"] === "string" ? r["failed_at"] : new Date(0).toISOString(),
1118
+ error: r["error"],
1119
+ consecutiveFailures: consecutive,
1120
+ retryAfter:
1121
+ typeof r["retry_after"] === "string" ? r["retry_after"] : new Date(0).toISOString(),
1122
+ manualCommand:
1123
+ typeof r["manual_command"] === "string"
1124
+ ? r["manual_command"]
1125
+ : AUTO_MIGRATION_MANUAL_COMMAND,
1126
+ attempt: r["attempt"] === true,
1127
+ written: writtenOf(r["written"]),
1128
+ gateOwed: typeof r["gate_owed"] === "string" ? r["gate_owed"] : null,
1129
+ };
1130
+ }
1131
+ return null;
1132
+ } catch (err) {
1133
+ // A damaged record says a failure happened but not which: report it
1134
+ // as one, dated at the epoch, so it never blocks a retry either.
1135
+ return {
1136
+ state: "failed",
1137
+ failedAt: new Date(0).toISOString(),
1138
+ error: `unreadable automatic migration state (${messageOf(err)})`,
1139
+ consecutiveFailures: 1,
1140
+ retryAfter: new Date(0).toISOString(),
1141
+ manualCommand: AUTO_MIGRATION_MANUAL_COMMAND,
1142
+ attempt: false,
1143
+ written: NOTHING_WRITTEN,
1144
+ gateOwed: null,
1145
+ };
1146
+ }
1147
+ }
1148
+
1149
+ /** The recorded failure, or null when none (or a waiting state) is recorded. */
1150
+ export function readAutoMigrationFailure(vault: string): AutoMigrationFailure | null {
1151
+ const state = readStateRecord(vault);
1152
+ return state?.state === "failed" ? state : null;
1153
+ }
1154
+
1155
+ /** The recorded waiting state, or null when none (or a failure) is recorded. */
1156
+ export function readAutoMigrationWaiting(vault: string): AutoMigrationWaiting | null {
1157
+ const state = readStateRecord(vault);
1158
+ return state?.state === "waiting" ? state : null;
1159
+ }
1160
+
1161
+ /**
1162
+ * Whether an automatic attempt must wait: a failure is recorded and its
1163
+ * cooldown has not run out at `now`. The same rule as the other workers
1164
+ * (`selfHealUpgradeBackoffActive`), on this state file's shape: a marker
1165
+ * this build did not write (dated in the future) never holds the
1166
+ * attempt off, and a cooldown longer than the longest one never applies.
1167
+ */
1168
+ export function autoMigrationBackoffActive(
1169
+ failure: AutoMigrationFailure | null,
1170
+ now: Date,
1171
+ ): boolean {
1172
+ if (failure === null) return false;
1173
+ const until = Date.parse(failure.retryAfter);
1174
+ if (!Number.isFinite(until)) return false;
1175
+ const failedAt = Date.parse(failure.failedAt);
1176
+ if (!Number.isFinite(failedAt) || failedAt > now.getTime()) return false;
1177
+ return now.getTime() < Math.min(until, failedAt + SELF_HEAL_UPGRADE_MAX_COOLDOWN_MS);
1178
+ }
1179
+
1180
+ function writeFailure(
1181
+ vault: string,
1182
+ error: string,
1183
+ opts: {
1184
+ manualCommand: string;
1185
+ now: Date;
1186
+ attempt: boolean;
1187
+ consecutiveFailures: number;
1188
+ gateOwed?: string;
1189
+ written?: AutoMigrationSuccessWritten;
1190
+ },
1191
+ ): AutoMigrationFailure {
1192
+ const written = opts.written ?? NOTHING_WRITTEN;
1193
+ const anyWritten = written.row || written.log || written.notice;
1194
+ const retryAfter = new Date(
1195
+ opts.now.getTime() + selfHealUpgradeCooldownMs(opts.consecutiveFailures),
1196
+ );
1197
+ const text = reportableText(error);
1198
+ const record = {
1199
+ state: "failed",
1200
+ failed_at: opts.now.toISOString(),
1201
+ error: text,
1202
+ consecutive_failures: opts.consecutiveFailures,
1203
+ retry_after: retryAfter.toISOString(),
1204
+ manual_command: opts.manualCommand,
1205
+ ...(opts.attempt ? { attempt: true } : {}),
1206
+ ...(opts.gateOwed !== undefined ? { gate_owed: opts.gateOwed } : {}),
1207
+ ...(anyWritten ? { written } : {}),
1208
+ };
1209
+ const path = autoMigrationStatePath(vault);
1210
+ writeStateFile(path, JSON.stringify(record, null, 2) + "\n");
1211
+ return {
1212
+ state: "failed",
1213
+ failedAt: record.failed_at,
1214
+ error: text,
1215
+ consecutiveFailures: opts.consecutiveFailures,
1216
+ retryAfter: record.retry_after,
1217
+ manualCommand: opts.manualCommand,
1218
+ attempt: opts.attempt,
1219
+ written,
1220
+ gateOwed: opts.gateOwed ?? null,
1221
+ };
1222
+ }
1223
+
1224
+ /**
1225
+ * Record a failure a START saw (a worker that could not be started, or
1226
+ * that exited before it confirmed its claim), under the claim it holds,
1227
+ * with the same count and cooldown as any failure. A record an earlier
1228
+ * attempt left keeps what it says beyond its reason (that it is an
1229
+ * attempt's, the gate it owes, the success outputs it wrote), so what
1230
+ * the next start finishes is unchanged.
1231
+ */
1232
+ function recordStartSeenFailure(vault: string, reason: string, now: Date): AutoMigrationFailure {
1233
+ const previous = readAutoMigrationFailure(vault);
1234
+ return writeFailure(vault, reason, {
1235
+ manualCommand: AUTO_MIGRATION_MANUAL_COMMAND,
1236
+ now,
1237
+ attempt: previous?.attempt === true,
1238
+ consecutiveFailures: (previous?.consecutiveFailures ?? 0) + 1,
1239
+ ...(previous?.gateOwed != null ? { gateOwed: previous.gateOwed } : {}),
1240
+ written: previous?.written ?? NOTHING_WRITTEN,
1241
+ });
1242
+ }
1243
+
1244
+ /**
1245
+ * Record that the worker a start spawned exited before it confirmed its
1246
+ * claim ({@link describeLostAutoMigrationWorker}). The caller holds the
1247
+ * claim (or its mutex).
1248
+ */
1249
+ export function recordLostAutoMigrationWorker(
1250
+ vault: string,
1251
+ worker: LostAutoMigrationWorker,
1252
+ now: Date,
1253
+ exit: string | null = null,
1254
+ ): AutoMigrationFailure {
1255
+ return recordStartSeenFailure(vault, describeLostAutoMigrationWorker(vault, worker, exit), now);
1256
+ }
1257
+
1258
+ /** Record that a start could not start the worker at all. The caller holds the claim. */
1259
+ export function recordAutoMigrationSpawnFailure(
1260
+ vault: string,
1261
+ error: string,
1262
+ now: Date,
1263
+ ): AutoMigrationFailure {
1264
+ return recordStartSeenFailure(
1265
+ vault,
1266
+ `the automatic migration worker could not be started: ${error}`,
1267
+ now,
1268
+ );
1269
+ }
1270
+
1271
+ /**
1272
+ * The consecutive count a new failure continues: a recorded failure's
1273
+ * count, including the one an unfinished attempt left (it counted itself
1274
+ * when it started), never an attempt's own record twice.
1275
+ */
1276
+ function previousFailures(vault: string, replacingAttempt: boolean): number {
1277
+ const previous = readAutoMigrationFailure(vault);
1278
+ if (previous === null) return 0;
1279
+ // The record this attempt wrote when it started already counts it.
1280
+ if (replacingAttempt && previous.attempt) return previous.consecutiveFailures - 1;
1281
+ return previous.consecutiveFailures;
1282
+ }
1283
+
1284
+ /**
1285
+ * Record a failed attempt; the cooldown doubles with each consecutive
1286
+ * failure. The reason is reduced for the surfaces it reaches
1287
+ * ({@link reportableText}).
1288
+ */
1289
+ export function recordAutoMigrationFailure(
1290
+ vault: string,
1291
+ error: string,
1292
+ opts: { manualCommand: string; now: Date },
1293
+ ): AutoMigrationFailure {
1294
+ return writeFailure(vault, error, {
1295
+ ...opts,
1296
+ attempt: false,
1297
+ consecutiveFailures: previousFailures(vault, true) + 1,
1298
+ });
1299
+ }
1300
+
1301
+ /**
1302
+ * Record, before an attempt starts, that it has not reported how it
1303
+ * ended yet: a failure record with the cooldown the attempt would start
1304
+ * if it failed. The attempt replaces it with its real outcome (cleared on
1305
+ * success, a waiting state, or the failure with its reason). When the
1306
+ * attempt is killed, or cannot write its outcome (a full disk), this
1307
+ * record stays: the next starts do not spawn a worker each, and the
1308
+ * doctor names an attempt that did not finish. Throws when it cannot be
1309
+ * written; the caller then starts nothing.
1310
+ */
1311
+ export function recordAutoMigrationAttempt(vault: string, now: Date): AutoMigrationFailure {
1312
+ return writeFailure(
1313
+ vault,
1314
+ `the automatic attempt that started at ${now.toISOString()} did not report how it ended ` +
1315
+ "(the worker stopped, or could not write its outcome)",
1316
+ {
1317
+ manualCommand: AUTO_MIGRATION_MANUAL_COMMAND,
1318
+ now,
1319
+ attempt: true,
1320
+ consecutiveFailures: previousFailures(vault, false) + 1,
1321
+ },
1322
+ );
1323
+ }
1324
+
1325
+ /**
1326
+ * Record that an attempt switched this machine and then failed before
1327
+ * its last steps (or its success records): the record stays an attempt's,
1328
+ * so the next start finishes the switch at once instead of waiting out a
1329
+ * cooldown, and names the reason meanwhile.
1330
+ */
1331
+ export function recordAutoMigrationUnfinishedSwitch(
1332
+ vault: string,
1333
+ reason: string,
1334
+ now: Date,
1335
+ ): AutoMigrationFailure {
1336
+ return writeFailure(vault, `the switch to the brain store did not finish: ${reason}`, {
1337
+ manualCommand: AUTO_MIGRATION_MANUAL_COMMAND,
1338
+ now,
1339
+ attempt: true,
1340
+ consecutiveFailures: previousFailures(vault, true) + 1,
1341
+ });
1342
+ }
1343
+
1344
+ /**
1345
+ * Record that the gate a stopped run (`runId`) left on this vault could
1346
+ * not be opened: the attempt's outcome (a refusal, a wait) would let the
1347
+ * next start honour the opt-out or a cooldown while that gate still
1348
+ * refuses every content write. The record stays an attempt's, so the next
1349
+ * start recovers it at once (`attemptMustBeRecovered`), until a pass sees
1350
+ * the gate gone. The count the record carries is kept.
1351
+ */
1352
+ export function recordAutoMigrationGateOwed(
1353
+ vault: string,
1354
+ runId: string,
1355
+ reason: string,
1356
+ now: Date,
1357
+ ): AutoMigrationFailure {
1358
+ return writeFailure(
1359
+ vault,
1360
+ `the migration gate run ${runId} left on this vault could not be opened yet (${reason}); ` +
1361
+ "the next start opens it",
1362
+ {
1363
+ manualCommand: AUTO_MIGRATION_MANUAL_COMMAND,
1364
+ now,
1365
+ attempt: true,
1366
+ consecutiveFailures: Math.max(1, previousFailures(vault, false)),
1367
+ gateOwed: runId,
1368
+ },
1369
+ );
1370
+ }
1371
+
1372
+ /**
1373
+ * The gate an attempt owed (run `runId`) is gone: its record becomes the
1374
+ * failure it stands for, its cooldown kept, no longer an attempt that owes
1375
+ * a gate. Any other record is left as it is.
1376
+ */
1377
+ export function settleAutoMigrationGateOwed(vault: string, runId: string): void {
1378
+ const path = autoMigrationStatePath(vault);
1379
+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
1380
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return;
1381
+ const record = { ...(raw as Record<string, unknown>) };
1382
+ if (record["gate_owed"] !== runId) return;
1383
+ delete record["gate_owed"];
1384
+ delete record["attempt"];
1385
+ writeStateFile(path, JSON.stringify(record, null, 2) + "\n");
1386
+ }
1387
+
1388
+ /** Record (or refresh) the waiting state of a later machine. No cooldown. */
1389
+ export function recordAutoMigrationWaiting(
1390
+ vault: string,
1391
+ wait: {
1392
+ missing: ReadonlyArray<string>;
1393
+ firstMachines: ReadonlyArray<string>;
1394
+ reason?: string | null;
1395
+ awaitsStore?: boolean;
1396
+ },
1397
+ now: Date,
1398
+ ): AutoMigrationWaiting {
1399
+ const reason = wait.reason === undefined || wait.reason === null ? null : wait.reason;
1400
+ const record = {
1401
+ state: "waiting",
1402
+ since: now.toISOString(),
1403
+ missing: [...wait.missing],
1404
+ first_machines: [...wait.firstMachines],
1405
+ ...(reason !== null ? { reason: reportableText(reason) } : {}),
1406
+ ...(wait.awaitsStore === true ? { awaits_store: true } : {}),
1407
+ };
1408
+ const path = autoMigrationStatePath(vault);
1409
+ writeStateFile(path, JSON.stringify(record, null, 2) + "\n");
1410
+ return {
1411
+ state: "waiting",
1412
+ since: record.since,
1413
+ missing: record.missing,
1414
+ firstMachines: record.first_machines,
1415
+ reason: record.reason ?? null,
1416
+ awaitsStore: wait.awaitsStore === true,
1417
+ };
1418
+ }
1419
+
1420
+ /**
1421
+ * Mark on the attempt's record that the success output `output` was
1422
+ * written ({@link AutoMigrationFailure.written}). Throws when there is no
1423
+ * record or it cannot be written.
1424
+ */
1425
+ export function markAutoMigrationSuccessWritten(
1426
+ vault: string,
1427
+ output: AutoMigrationSuccessOutput,
1428
+ ): void {
1429
+ const path = autoMigrationStatePath(vault);
1430
+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
1431
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
1432
+ throw new Error("not a JSON object");
1433
+ }
1434
+ const record = raw as Record<string, unknown>;
1435
+ const written = { ...writtenOf(record["written"]), [output]: true };
1436
+ writeStateFile(path, JSON.stringify({ ...record, written }, null, 2) + "\n");
1437
+ }
1438
+
1439
+ /** Drop the state record once nothing of it is left (success, or moot). */
1440
+ export function clearAutoMigrationState(vault: string): void {
1441
+ try {
1442
+ unlinkSync(autoMigrationStatePath(vault));
1443
+ } catch (err) {
1444
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
1445
+ }
1446
+ pruneAutoMigrationStateDir(vault);
1447
+ }
1448
+
1449
+ export function clearAutoMigrationFailure(vault: string): void {
1450
+ if (readAutoMigrationFailure(vault) !== null) clearAutoMigrationState(vault);
1451
+ }
1452
+
1453
+ export function clearAutoMigrationWaiting(vault: string): void {
1454
+ if (readAutoMigrationWaiting(vault) !== null) clearAutoMigrationState(vault);
1455
+ }
1456
+
1457
+ /**
1458
+ * One-line operator description of a recorded failure, for the doctor,
1459
+ * the status block and the session start notice.
1460
+ */
1461
+ export function describeAutoMigrationFailure(
1462
+ failure: AutoMigrationFailure,
1463
+ opts: { readonly retries?: boolean } = {},
1464
+ ): string {
1465
+ // With the automatic migration off no start retries it: the schedule is
1466
+ // left out, the reason and the manual command stay.
1467
+ const retry =
1468
+ opts.retries === false ? "" : `, next automatic attempt after ${printable(failure.retryAfter)}`;
1469
+ return (
1470
+ `the automatic store migration failed at ${printable(failure.failedAt)}: ` +
1471
+ `${reportableText(failure.error)}; ${failure.consecutiveFailures} consecutive failure(s)` +
1472
+ `${retry}; run \`${failure.manualCommand}\` to run it yourself`
1473
+ );
1474
+ }
1475
+
1476
+ /**
1477
+ * Reported to a terminal and injected into a session, so control
1478
+ * characters are replaced before they reach either.
1479
+ */
1480
+ export function printable(text: string): string {
1481
+ // oxlint-disable-next-line no-control-regex -- matching control characters is the point
1482
+ return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
1483
+ }
1484
+
1485
+ /** Home directories as this process sees them, longest first. */
1486
+ function homeDirs(): string[] {
1487
+ const dirs = new Set<string>();
1488
+ for (const value of [process.env["HOME"], process.env["USERPROFILE"]]) {
1489
+ if (value !== undefined && value.trim().length > 1) dirs.add(value.replace(/[\\/]+$/, ""));
1490
+ }
1491
+ try {
1492
+ const home = homedir();
1493
+ if (home.length > 1) dirs.add(home.replace(/[\\/]+$/, ""));
1494
+ } catch {
1495
+ // no home directory known
1496
+ }
1497
+ return [...dirs].toSorted((a, b) => b.length - a.length);
1498
+ }
1499
+
1500
+ /** `/home/<name>`, `/Users/<name>` and the like, wherever they appear. */
1501
+ const HOME_PATTERN = /[\\/](?:home|Users|users)[\\/][^\\/\s"'`;,)]+/g;
1502
+
1503
+ /** `C:\\Users\\<name>` in any case, wherever it appears: Windows paths are not case-sensitive. */
1504
+ const WINDOWS_HOME_PATTERN = /[A-Za-z]:[\\/]users[\\/][^\\/\s"'`;,)]+/gi;
1505
+
1506
+ /** `text` with every occurrence of `home` reduced to `~`, in any case on Windows. */
1507
+ function withoutHome(text: string, home: string, platform: NodeJS.Platform): string {
1508
+ if (platform !== "win32") return text.split(home).join("~");
1509
+ const escaped = home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1510
+ return text.replace(new RegExp(escaped, "gi"), "~");
1511
+ }
1512
+
1513
+ /**
1514
+ * A failure or waiting reason as it may be kept and shown.
1515
+ *
1516
+ * What it reduces: control characters (replaced by spaces); every home
1517
+ * directory this process knows (`HOME`, `USERPROFILE`, `os.homedir()`)
1518
+ * wherever it appears (in any case on Windows, whose paths are not
1519
+ * case-sensitive), and any `/home/<name>`, `/Users/<name>` or
1520
+ * `<drive>:\Users\<name>` path (the last in any case), to `~`; and the
1521
+ * length, to 2000 characters.
1522
+ *
1523
+ * What it does not reduce: a path that names the account some other way
1524
+ * (`D:\data\<name>\...`, a `\\server\homes\<name>` share,
1525
+ * `/var/folders/.../T/...`, a store root or vault the person placed
1526
+ * elsewhere), and a user name that appears outside a path. It is a
1527
+ * courtesy for local display, not a privacy boundary: the text is kept
1528
+ * only in this machine's device-local state, shown by the doctor, the
1529
+ * status block and the local terminal, and injected into this machine's
1530
+ * session digest. Nothing that leaves the machine carries it: the brain
1531
+ * log line names no path and the metrics rows carry no text.
1532
+ */
1533
+ export function reportableText(text: string): string {
1534
+ return reportableTextFor(text, process.platform, homeDirs());
1535
+ }
1536
+
1537
+ /**
1538
+ * {@link reportableText} with the platform and the known home directories
1539
+ * as inputs: pure, so the Windows rule and the case-sensitive rule can be
1540
+ * checked on any platform.
1541
+ */
1542
+ export function reportableTextFor(
1543
+ text: string,
1544
+ platform: NodeJS.Platform,
1545
+ homes: readonly string[],
1546
+ ): string {
1547
+ let out = printable(text);
1548
+ const known = homes
1549
+ .map((home) => home.replace(/[\\/]+$/, ""))
1550
+ .filter((home) => home.trim().length > 1)
1551
+ .toSorted((a, b) => b.length - a.length);
1552
+ for (const home of known) out = withoutHome(out, home, platform);
1553
+ out = out.replace(WINDOWS_HOME_PATTERN, "~").replace(HOME_PATTERN, "~");
1554
+ return out.length <= REPORTABLE_TEXT_CHARS
1555
+ ? out
1556
+ : `${out.slice(0, REPORTABLE_TEXT_CHARS - 3)}...`;
1557
+ }
1558
+
1559
+ /** Longest reason kept in the state file. */
1560
+ const REPORTABLE_TEXT_CHARS = 2000;
1561
+
1562
+ // ----- One-time success notice ---------------------------------------------
1563
+
1564
+ /** The one-time success notice's content. */
1565
+ export interface AutoMigrationNotice {
1566
+ /** ISO-8601 instant the migration succeeded. */
1567
+ readonly at: string;
1568
+ /** The migration snapshot's run id, where the pre-migration copy lives; null when none was taken. */
1569
+ readonly snapshot: string | null;
1570
+ /** How to undo the switch, spelled for the surfaces that show it. */
1571
+ readonly rollbackCommand: string;
1572
+ }
1573
+
1574
+ /**
1575
+ * Record the one-time success notice of the run `runId`; the next session
1576
+ * start shows it. Not written again for a run whose notice a session
1577
+ * already showed ({@link clearAutoMigrationNotice}).
1578
+ */
1579
+ export function recordAutoMigrationNotice(
1580
+ vault: string,
1581
+ notice: { snapshot: string | null; runId?: string | null },
1582
+ now: Date,
1583
+ ): void {
1584
+ const run = notice.runId ?? "";
1585
+ if (noticeConsumedFor(vault) === run) return;
1586
+ const snapshot =
1587
+ notice.snapshot === null || notice.snapshot.trim() === "" ? null : notice.snapshot;
1588
+ const written = {
1589
+ at: now.toISOString(),
1590
+ run_id: run,
1591
+ snapshot,
1592
+ rollback_command: AUTO_MIGRATION_ROLLBACK_COMMAND,
1593
+ };
1594
+ writeStateFile(autoMigrationNoticePath(vault), JSON.stringify(written, null, 2) + "\n");
1595
+ }
1596
+
1597
+ function readNoticeRecord(vault: string): Record<string, unknown> | null {
1598
+ const path = autoMigrationNoticePath(vault);
1599
+ if (!existsSync(path)) return null;
1600
+ try {
1601
+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
1602
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
1603
+ return raw as Record<string, unknown>;
1604
+ } catch {
1605
+ return null;
1606
+ }
1607
+ }
1608
+
1609
+ /** The run whose notice a session showed while its attempt was unfinished, or null. */
1610
+ function noticeConsumedFor(vault: string): string | null {
1611
+ const r = readNoticeRecord(vault);
1612
+ return r !== null && typeof r["consumed_run"] === "string" ? r["consumed_run"] : null;
1613
+ }
1614
+
1615
+ /**
1616
+ * The notice to show, or null when there is none: no file, a file that is
1617
+ * not a plain JSON object, a record whose `at` is not a time, or the mark
1618
+ * of a notice already shown. `snapshot: null` is a notice (a run without
1619
+ * a snapshot).
1620
+ */
1621
+ export function readAutoMigrationNotice(vault: string): AutoMigrationNotice | null {
1622
+ const r = readNoticeRecord(vault);
1623
+ if (r === null || typeof r["at"] !== "string" || !Number.isFinite(Date.parse(r["at"]))) {
1624
+ return null;
1625
+ }
1626
+ const snapshot =
1627
+ typeof r["snapshot"] === "string" && r["snapshot"].trim() !== "" ? r["snapshot"] : null;
1628
+ return {
1629
+ at: r["at"],
1630
+ snapshot,
1631
+ rollbackCommand:
1632
+ typeof r["rollback_command"] === "string"
1633
+ ? r["rollback_command"]
1634
+ : AUTO_MIGRATION_ROLLBACK_COMMAND,
1635
+ };
1636
+ }
1637
+
1638
+ /**
1639
+ * Drop the notice once a session start has shown it. While the attempt
1640
+ * that wrote it has not finished (its record is still there), the file is
1641
+ * replaced by a mark naming the run, so a pass that finishes that attempt
1642
+ * does not write the same notice again; the pass drops the mark when it
1643
+ * clears the attempt ({@link dropShownAutoMigrationNotice}).
1644
+ */
1645
+ export function clearAutoMigrationNotice(vault: string): void {
1646
+ const record = readNoticeRecord(vault);
1647
+ const attempt = readAutoMigrationFailure(vault)?.attempt === true;
1648
+ // Already cleared by another session while the attempt is unfinished:
1649
+ // the mark stays, so the notice is not published again.
1650
+ if (attempt && record !== null && typeof record["consumed_run"] === "string") return;
1651
+ if (attempt && record !== null && typeof record["run_id"] === "string") {
1652
+ writeStateFile(
1653
+ autoMigrationNoticePath(vault),
1654
+ JSON.stringify({ consumed_run: record["run_id"] }, null, 2) + "\n",
1655
+ );
1656
+ return;
1657
+ }
1658
+ try {
1659
+ unlinkSync(autoMigrationNoticePath(vault));
1660
+ } catch (err) {
1661
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
1662
+ }
1663
+ pruneAutoMigrationStateDir(vault);
1664
+ }
1665
+
1666
+ /**
1667
+ * Consume the one-time success notice a session start rendered (the one
1668
+ * whose `at` is `at`), after the session's text is assembled: the session
1669
+ * whose consumption succeeds shows it, and no other, so two sessions that
1670
+ * start at once never both show it. The notice file is renamed to a name
1671
+ * of this process's own, and only one rename wins. A file that is not
1672
+ * that notice (a newer one, or the mark of one already shown) is put back
1673
+ * unless something took its place meanwhile. Then, as
1674
+ * {@link clearAutoMigrationNotice} does: while the attempt that wrote it is
1675
+ * unfinished, a mark naming its run stays, so a pass that finishes the
1676
+ * attempt does not publish it again. Never throws; false keeps the notice
1677
+ * for a later session.
1678
+ */
1679
+ export function consumeAutoMigrationNotice(
1680
+ vault: string,
1681
+ at: string,
1682
+ hooks: { readonly afterRename?: () => void } = {},
1683
+ ): boolean {
1684
+ const path = autoMigrationNoticePath(vault);
1685
+ const claimed = `${path}${CLAIMED_NOTICE_INFIX}${process.pid}-${randomBytes(4).toString("hex")}`;
1686
+ try {
1687
+ renameSync(path, claimed);
1688
+ } catch {
1689
+ // Another session consumed it, or it cannot be moved now.
1690
+ return false;
1691
+ }
1692
+ hooks.afterRename?.();
1693
+ const record = readJsonRecord(claimed);
1694
+ if (record === null || record["at"] !== at) {
1695
+ putBack(claimed, path);
1696
+ return false;
1697
+ }
1698
+ try {
1699
+ if (readAutoMigrationFailure(vault)?.attempt === true && typeof record["run_id"] === "string") {
1700
+ // Never over a notice a worker wrote since the rename: that one is
1701
+ // newer and still to be shown.
1702
+ placeIfAbsent(
1703
+ path,
1704
+ `${claimed}.mark`,
1705
+ JSON.stringify({ consumed_run: record["run_id"] }, null, 2) + "\n",
1706
+ );
1707
+ }
1708
+ } catch {
1709
+ // Best effort: without the mark, the pass that finishes the attempt
1710
+ // may publish the notice once more.
1711
+ }
1712
+ try {
1713
+ unlinkSync(claimed);
1714
+ } catch {
1715
+ // left for the next session start ({@link recoverClaimedAutoMigrationNotices})
1716
+ }
1717
+ pruneAutoMigrationStateDir(vault);
1718
+ return true;
1719
+ }
1720
+
1721
+ /** The infix of a notice a session start claimed: `<notice>.shown-<pid>-<hex>`. */
1722
+ const CLAIMED_NOTICE_INFIX = ".shown-";
1723
+
1724
+ /** The JSON object in `path`, or null (absent, unreadable, not an object). */
1725
+ function readJsonRecord(path: string): Record<string, unknown> | null {
1726
+ try {
1727
+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
1728
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw)
1729
+ ? (raw as Record<string, unknown>)
1730
+ : null;
1731
+ } catch {
1732
+ return null;
1733
+ }
1734
+ }
1735
+
1736
+ /**
1737
+ * Write `text` to `path` only when nothing is there: written to `temp`
1738
+ * first and hard-linked in, so a file that appeared at `path` meanwhile is
1739
+ * never replaced. Returns whether it was placed.
1740
+ */
1741
+ function placeIfAbsent(path: string, temp: string, text: string): boolean {
1742
+ writeFileSync(temp, text);
1743
+ try {
1744
+ linkSync(temp, path);
1745
+ return true;
1746
+ } catch (err) {
1747
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
1748
+ throw err;
1749
+ } finally {
1750
+ try {
1751
+ unlinkSync(temp);
1752
+ } catch {
1753
+ // already gone
1754
+ }
1755
+ }
1756
+ }
1757
+
1758
+ /**
1759
+ * Give back what a session start that died while it consumed the notice
1760
+ * left (`<notice>.shown-<pid>-<hex>`, and its `.mark` scratch file), so
1761
+ * nothing a worker wrote is lost: the session died before it showed the
1762
+ * notice (a session shows it only after the consume returns). Run by a
1763
+ * session start before it reads the notice. For each claimed file whose
1764
+ * process is gone: with no notice in place it is put back; in place of the
1765
+ * mark that session wrote for the same run it is put back over that mark
1766
+ * (shown now, it is marked again); beside a newer notice or another mark
1767
+ * it is dropped. A claimed file of a live process (a session consuming
1768
+ * right now, or a pid reused since) is left alone; such a leftover costs
1769
+ * one small file in the device-local folder until its pid is gone. Never
1770
+ * throws.
1771
+ */
1772
+ export function recoverClaimedAutoMigrationNotices(vault: string): void {
1773
+ const path = autoMigrationNoticePath(vault);
1774
+ const prefix = `${AUTO_MIGRATION_NOTICE_FILE}${CLAIMED_NOTICE_INFIX}`;
1775
+ let names: string[];
1776
+ try {
1777
+ names = readdirSync(dirname(path)).filter((n) => n.startsWith(prefix));
1778
+ } catch {
1779
+ return;
1780
+ }
1781
+ for (const name of names) {
1782
+ const pid = Number.parseInt(name.slice(prefix.length), 10);
1783
+ if (processAlive(pid)) continue;
1784
+ const leftover = join(dirname(path), name);
1785
+ try {
1786
+ if (name.endsWith(".mark") || name.endsWith(".aside")) {
1787
+ unlinkSync(leftover);
1788
+ continue;
1789
+ }
1790
+ // Claimed again under this process's own name, by one rename: two
1791
+ // starts that recover at once never both work on it.
1792
+ const claimed = `${path}${CLAIMED_NOTICE_INFIX}${process.pid}-${randomBytes(4).toString("hex")}`;
1793
+ renameSync(leftover, claimed);
1794
+ recoverClaimed(claimed, path);
1795
+ } catch {
1796
+ // left for the next session start
1797
+ }
1798
+ }
1799
+ pruneAutoMigrationStateDir(vault);
1800
+ }
1801
+
1802
+ function recoverClaimed(claimed: string, path: string): void {
1803
+ const notice = readJsonRecord(claimed);
1804
+ const runId = typeof notice?.["run_id"] === "string" ? notice["run_id"] : null;
1805
+ const current = readJsonRecord(path);
1806
+ if (!existsSync(path)) {
1807
+ putBack(claimed, path);
1808
+ return;
1809
+ }
1810
+ if (notice !== null && current !== null && runId !== null && current["consumed_run"] === runId) {
1811
+ // The mark that session wrote for this very notice: moved aside by one
1812
+ // atomic rename, so a notice written meanwhile is never lost.
1813
+ const aside = `${claimed}.aside`;
1814
+ renameSync(path, aside);
1815
+ if (readJsonRecord(aside)?.["consumed_run"] !== runId) {
1816
+ putBack(aside, path);
1817
+ unlinkSync(claimed);
1818
+ return;
1819
+ }
1820
+ unlinkSync(aside);
1821
+ putBack(claimed, path);
1822
+ return;
1823
+ }
1824
+ unlinkSync(claimed);
1825
+ }
1826
+
1827
+ /** Move a claimed file back to `path`, unless something took its place. Never throws. */
1828
+ function putBack(claimed: string, path: string): void {
1829
+ try {
1830
+ // A hard link never replaces a file that appeared at `path`.
1831
+ linkSync(claimed, path);
1832
+ } catch (err) {
1833
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST" && !existsSync(path)) {
1834
+ try {
1835
+ renameSync(claimed, path);
1836
+ return;
1837
+ } catch {
1838
+ // lost: the attempt's pass writes an unshown notice again
1839
+ }
1840
+ }
1841
+ }
1842
+ try {
1843
+ unlinkSync(claimed);
1844
+ } catch {
1845
+ // already gone
1846
+ }
1847
+ }
1848
+
1849
+ /** Drop the mark of a notice already shown, once its attempt is finished. Never throws. */
1850
+ export function dropShownAutoMigrationNotice(vault: string): void {
1851
+ if (noticeConsumedFor(vault) === null) return;
1852
+ try {
1853
+ unlinkSync(autoMigrationNoticePath(vault));
1854
+ } catch {
1855
+ // already gone
1856
+ }
1857
+ pruneAutoMigrationStateDir(vault);
1858
+ }