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,4059 @@
1
+ /**
2
+ * Pre-`dream` snapshot, rotation, and rollback support.
3
+ *
4
+ * The contract (design doc §7.4 "Pre-run snapshot" + §15 Step 9a):
5
+ *
6
+ * - Before any state-changing operation in a `dream` run we write
7
+ * `Brain/.snapshots/<run_id>.tar.zst` containing the entire
8
+ * `Brain/` tree **excluding** {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES}.
9
+ * Including the snapshots dir would either explode the archive or
10
+ * racy-clobber an in-progress write; including the artifact cache
11
+ * would hash TTL'd tool output into a drift gate that no rollback
12
+ * would ever act on.
13
+ *
14
+ * - Retention is enforced by `pruneSnapshots`: keep the
15
+ * `snapshots.retention_count` newest files, delete the rest.
16
+ *
17
+ * - `restoreSnapshot` extracts the archive over `Brain/`. Critical
18
+ * constraint: the restore must NOT touch `Brain/.snapshots/`,
19
+ * otherwise rolling back to an older state could destroy newer
20
+ * snapshots (and with them the user's only path forward again).
21
+ * We achieve this by extracting into a sibling temp directory,
22
+ * verifying the contents, then replacing every top-level entry
23
+ * under `Brain/` *except* `.snapshots/`.
24
+ *
25
+ * - Tooling: a snapshot is written by the system `tar` (GNU tar on
26
+ * Linux, bsdtar on macOS) and, on Windows, in process
27
+ * (`tar-writer.ts`); every archive is read back in process
28
+ * (`tar-extract.ts`), so a restore needs no `tar` at all. `zstd` is
29
+ * used when it is on PATH. Without `zstd` the archive is
30
+ * gzip-compressed in-process through `node:zlib`, so no `gzip` binary
31
+ * is needed - native Windows has none. A create without `tar` on
32
+ * PATH throws {@link BrainSnapshotToolingMissingError} with an
33
+ * actionable message.
34
+ *
35
+ * No external dependencies. Everything is `node:child_process` +
36
+ * `node:fs` + `node:zlib`, so the cost is one subprocess per archive
37
+ * operation.
38
+ *
39
+ * ## On a switched machine
40
+ *
41
+ * Once this machine is switched to the brain store (design D14 item 9),
42
+ * the store needs no snapshot: its shards are append-only with record
43
+ * sums and partition digests. What a snapshot covers then is this
44
+ * machine's device-local state, which keeps the same `Brain/` layout
45
+ * under its own root (`state/machine-state.ts`). Every public entry point
46
+ * below maps its `vault` argument to that root first, so the archive is
47
+ * of `<device state>/migration/local/Brain/`, it lives in that tree's
48
+ * `.snapshots/`, and a restore replaces that tree. Nothing under the vault
49
+ * is read or written. An unswitched machine maps to the vault itself.
50
+ *
51
+ * ## Derived-store coverage, and why it is off by default
52
+ *
53
+ * The derived SQLite store (`<vault>/.open-second-brain/brain.sqlite`)
54
+ * is a sibling of `Brain/`, and until now it was in no snapshot, no
55
+ * manifest and no rollback - with nothing saying so, which made a
56
+ * complete-looking pre-restore diff while the embeddings stayed at
57
+ * whatever the live store happened to hold.
58
+ *
59
+ * What coverage buys is SPEND, not information. Feedback, activation and
60
+ * tuning are replayable JSON folds inside `Brain/`; only the embeddings
61
+ * and a tier baseline are database-only, so a lost store costs an
62
+ * embedding bill and a reindex, never a fact. Against that: retention
63
+ * keeps ten archives, and `.snapshots/` sits inside a vault replicated
64
+ * peer-to-peer, so every retained copy is pushed to every device. Ten
65
+ * multiples of a store on every peer is a real cost to pay for a
66
+ * regenerable artifact.
67
+ *
68
+ * Hence the three-part answer. Coverage is opt-in. The ceiling REFUSES
69
+ * rather than truncating, because half a database is not a recovery
70
+ * point. And the live store size is recorded in every manifest whether
71
+ * or not it was included, so an operator who has never enabled coverage
72
+ * can still read what enabling it would cost.
73
+ *
74
+ * ## Every recovery point says why it exists
75
+ *
76
+ * `createSnapshot` requires a {@link BrainSnapshotReason}. It goes into
77
+ * the manifest sidecar as an additive key at the existing schema version,
78
+ * and into the Brain event log as one `snapshot` event carrying the run
79
+ * id, the reason and the archive size — the counterpart the log has been
80
+ * missing since `rollback` shipped, which recorded the restore while the
81
+ * point it restores to left no trace but a filename.
82
+ *
83
+ * The reason is also the run-id prefix at every call site, which is
84
+ * exactly why the READ path must not parse it back out: recovering the
85
+ * field from the filename would look right on almost every archive this
86
+ * project writes and would invent provenance for one it did not.
87
+ */
88
+
89
+ import { Database } from "bun:sqlite";
90
+ import { spawnSync, type SpawnSyncOptions, type SpawnSyncReturns } from "node:child_process";
91
+ import { randomBytes } from "node:crypto";
92
+ import { gunzipSync, gzipSync } from "node:zlib";
93
+ import {
94
+ closeSync,
95
+ cpSync,
96
+ existsSync,
97
+ linkSync,
98
+ lstatSync,
99
+ mkdirSync,
100
+ mkdtempSync,
101
+ openSync,
102
+ readFileSync,
103
+ readSync,
104
+ readdirSync,
105
+ readlinkSync,
106
+ realpathSync,
107
+ rmSync,
108
+ statSync,
109
+ writeFileSync,
110
+ writeSync,
111
+ type Dirent,
112
+ } from "node:fs";
113
+ import { tmpdir } from "node:os";
114
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
115
+
116
+ import { FileAlreadyExistsError, renameWithRetry, unlinkWithRetry } from "../fs-atomic.ts";
117
+ import { productTransientKind } from "./snapshot-transient.ts";
118
+ import { writeTarArchive } from "./tar-writer.ts";
119
+ import { extractTarArchive } from "./tar-extract.ts";
120
+ import { readTarMemberNames, type TarMemberName, type TarRead } from "./tar-names.ts";
121
+ import { classifyRecoverability, type RecoverabilityVerdict } from "./gates/recoverability.ts";
122
+ import { sha256HexOfFile } from "../integrity/digest.ts";
123
+ import { resolveConfiguredIndexPath } from "../search/paths.ts";
124
+ import { compareKey, foldsCase, isStoreFamilyEntry } from "../search/store-family.ts";
125
+
126
+ export { isStoreFamilyEntry };
127
+ import {
128
+ clearParkMarker,
129
+ restoreParkedIndexUnderLock,
130
+ runIntegrityCheck,
131
+ writeParkMarker,
132
+ } from "../search/store/lifecycle.ts";
133
+ import {
134
+ acquireWriterLeaseSync,
135
+ acquireWriterLockSync,
136
+ keepWriterLeasesFresh,
137
+ resolveWriterLockStaleMs,
138
+ WRITER_LEASE_BLOCKING_BUDGET_MS,
139
+ type WriterLease,
140
+ } from "../search/store/writer-lock.ts";
141
+ import { appendLogEvent } from "./log.ts";
142
+ import {
143
+ buildManifest,
144
+ manifestSidecarPath,
145
+ readManifestSidecar,
146
+ SNAPSHOT_STORE_EXCLUSION,
147
+ writeManifestSidecar,
148
+ type BrainManifestDerivedStore,
149
+ type SnapshotStoreExclusionReason,
150
+ } from "./manifest.ts";
151
+ import {
152
+ BRAIN_RESTORE_STAGING_PREFIX,
153
+ BRAIN_ROOT_REL,
154
+ BRAIN_SNAPSHOT_EXCLUDED_ENTRIES,
155
+ BRAIN_SNAPSHOTS_REL,
156
+ brainDirs,
157
+ brainDirsForWrite,
158
+ SNAPSHOT_ARCHIVE_SUFFIX,
159
+ snapshotPath,
160
+ snapshotStorePath,
161
+ validateRunId,
162
+ } from "./paths.ts";
163
+ import { loadSnapshotDerivedStorePolicySafe, type BrainDerivedStorePolicy } from "./policy.ts";
164
+ import { isoSecond } from "./time.ts";
165
+ import { BRAIN_LOG_EVENT_KIND, type BrainSnapshotReason } from "./types.ts";
166
+ import { assertVaultIdentityForWrite } from "./vault-identity.ts";
167
+ import type { WriteLane } from "./freeze-marker.ts";
168
+ import { closeDatabase } from "../sqlite-close.ts";
169
+ import {
170
+ parkSqliteFileSet,
171
+ sqliteJournalsPresent,
172
+ SQLITE_SIBLING_SUFFIXES,
173
+ SqliteFileSetMoveError,
174
+ unparkSqliteFileSet,
175
+ } from "../sqlite-file-set.ts";
176
+ import { machineStateRoot } from "../state/machine-state.ts";
177
+
178
+ // ----- Errors ---------------------------------------------------------------
179
+
180
+ /**
181
+ * Thrown when the host lacks both `tar` and any compressor we know how
182
+ * to use. Distinct from `BrainSnapshotError` so callers can pattern-
183
+ * match and offer install instructions.
184
+ */
185
+ export class BrainSnapshotToolingMissingError extends Error {
186
+ constructor(tool: string, hint: string) {
187
+ super(`snapshot tooling missing: '${tool}' not found on PATH. ${hint}`);
188
+ this.name = "BrainSnapshotToolingMissingError";
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Generic snapshot failure (archive write failed, restore failed,
194
+ * archive contents corrupted). Includes the runId in the message so
195
+ * the operator can locate it.
196
+ */
197
+ export class BrainSnapshotError extends Error {
198
+ readonly runId: string;
199
+ /**
200
+ * `cause` is forwarded rather than flattened into the message because the
201
+ * caller that allocates a unique run id retries a lost race and has to
202
+ * recognise a collision by its errno AND the path it names.
203
+ * `createUniqueSnapshot` keys on
204
+ * `isFileAlreadyExistsAt`, which walks the cause chain; an error that only
205
+ * described its errno in prose would turn a retriable collision into a
206
+ * terminal failure, which is the shape this release removes.
207
+ */
208
+ constructor(message: string, runId: string, options?: { readonly cause?: unknown }) {
209
+ super(`snapshot[${runId}]: ${message}`, options);
210
+ this.name = "BrainSnapshotError";
211
+ this.runId = runId;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Thrown when `.snapshots/` is present and cannot be enumerated.
217
+ *
218
+ * {@link listSnapshots} used to answer an unreadable directory with `[]`,
219
+ * which put "this vault has taken no recovery points" and "nobody could
220
+ * read the recovery points" on one wire - and every surface above it then
221
+ * printed the first sentence over the second. It is not a
222
+ * {@link BrainSnapshotError} because it belongs to no run id: the failure
223
+ * is the directory, and naming an arbitrary archive in the message would
224
+ * imply the read got as far as one.
225
+ */
226
+ export class BrainSnapshotListingError extends Error {
227
+ /** Absolute path of the directory that could not be read. */
228
+ readonly path: string;
229
+ constructor(path: string, cause: unknown) {
230
+ super(
231
+ `snapshots directory ${path} could not be read: ${
232
+ cause instanceof Error ? cause.message : String(cause)
233
+ }`,
234
+ { cause },
235
+ );
236
+ this.name = "BrainSnapshotListingError";
237
+ this.path = path;
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Thrown when derived-store coverage was REQUESTED and could not be
243
+ * honoured. Carries the reason from the same closed vocabulary a
244
+ * manifest records, so the caller that reports the refusal and the
245
+ * manifest that records an omission speak one language.
246
+ *
247
+ * It is a `BrainSnapshotError` because it is a snapshot failure in every
248
+ * sense that matters to a caller: `createSnapshot` throws, nothing is
249
+ * left on disk, and the destructive-snapshot gate consequently never
250
+ * runs the operation it was protecting. That last property needs no
251
+ * plumbing - it follows from refusing here rather than downgrading to a
252
+ * partial snapshot that reports success.
253
+ */
254
+ export class BrainSnapshotStoreError extends BrainSnapshotError {
255
+ readonly reason: SnapshotStoreExclusionReason;
256
+ constructor(message: string, runId: string, reason: SnapshotStoreExclusionReason) {
257
+ super(`derived store not archived (${reason}): ${message}`, runId);
258
+ this.name = "BrainSnapshotStoreError";
259
+ this.reason = reason;
260
+ }
261
+ }
262
+
263
+ // ----- Types ---------------------------------------------------------------
264
+
265
+ export interface CreateSnapshotResult {
266
+ /** Absolute path of the resulting archive. */
267
+ readonly path: string;
268
+ /** What this snapshot did about the derived store. */
269
+ readonly derived_store: BrainManifestDerivedStore;
270
+ }
271
+
272
+ /**
273
+ * The derived-store knobs, shared by the create and the restore path
274
+ * because both resolve the same live store: one to archive it, one to
275
+ * write it back.
276
+ */
277
+ export interface SnapshotStoreOptions {
278
+ /**
279
+ * Derived-store coverage policy. Defaults to the vault's
280
+ * `snapshots:` block, so every existing call site picks the operator's
281
+ * setting up without threading it through.
282
+ */
283
+ readonly derivedStore?: BrainDerivedStorePolicy;
284
+ /**
285
+ * Absolute path of the live derived store. Defaults to
286
+ * {@link liveDerivedStorePath}, which resolves it the way the search
287
+ * layer does - honouring both the `OPEN_SECOND_BRAIN_SEARCH_DB`
288
+ * environment variable and the `search_db_path` config key. A caller
289
+ * that already holds a resolved search config passes its own answer.
290
+ */
291
+ readonly derivedStorePath?: string;
292
+ }
293
+
294
+ export interface CreateSnapshotOptions extends SnapshotStoreOptions {
295
+ /**
296
+ * Why this recovery point is being taken. REQUIRED, and required
297
+ * precisely because it used to be optional in effect: the reasons
298
+ * existed only as run-id prefixes, three of them inline literals, and
299
+ * nothing read them back. A default here would restore that state -
300
+ * every unnamed call site would silently claim whatever the default
301
+ * said - so there is none, and the compiler asks each caller instead.
302
+ */
303
+ readonly reason: BrainSnapshotReason;
304
+ /**
305
+ * The write lane the guard checks. Content by default, so a frozen vault
306
+ * refuses a snapshot like any content write. The store migration takes
307
+ * its recovery point after it froze the legacy writers, on the audit
308
+ * lane, because an archive of a tree still being written is not one.
309
+ */
310
+ readonly lane?: WriteLane;
311
+ /**
312
+ * Clock for the `snapshot` audit line's timestamp. Defaults to wall
313
+ * clock. A caller that already has an injected clock passes it, so a
314
+ * pass whose output is byte-reproducible given `now` - the dream pass
315
+ * is, and a test asserts it - does not become non-reproducible merely
316
+ * by recording that it took a recovery point.
317
+ */
318
+ readonly now?: Date;
319
+ /**
320
+ * The token of a derived-store writer lock the CALLER already holds.
321
+ * When it is a live token on exactly the store this snapshot archives,
322
+ * the archive is written under that lock instead of acquiring it again
323
+ * (the lock is not re-entrant, so a second acquire would refuse).
324
+ * Anything else - a released token, a token on another path, a string
325
+ * naming the path, an object that merely looks like a token - takes
326
+ * the lock as usual. A token is minted only where the restore acquires
327
+ * the lock, so naming the store is not enough to skip it.
328
+ *
329
+ * One caller needs it: the gated restore takes the lock before its
330
+ * recovery point and keeps it through the swap, so no write lands
331
+ * between the two.
332
+ */
333
+ readonly heldStoreLock?: StoreLockToken;
334
+ }
335
+
336
+ /** Mints {@link StoreLockToken}s; never leaves this module. */
337
+ const STORE_LOCK_TOKEN_MINT: unique symbol = Symbol("store-lock-token-mint");
338
+
339
+ /**
340
+ * The tokens whose lock is still held. A token leaves the set when its
341
+ * lock is released, so a kept reference stops counting at that moment.
342
+ */
343
+ // Live token -> the store path its lock is held on. The path is read from
344
+ // here, never from the token, so a caller cannot redirect a genuine token.
345
+ const liveStoreLockTokens = new WeakMap<StoreLockToken, string>();
346
+
347
+ /**
348
+ * Proof that this module holds the derived store's writer lock on
349
+ * {@link StoreLockToken.path}. Constructed only with the module-private
350
+ * mint symbol, by the restore's lock acquisition, and honoured only
351
+ * while the lock is held (see {@link isLiveStoreLockToken}).
352
+ */
353
+ export class StoreLockToken {
354
+ readonly #path: string;
355
+
356
+ constructor(mint: symbol, path: string) {
357
+ if (mint !== STORE_LOCK_TOKEN_MINT) {
358
+ throw new TypeError("a store lock token is minted only by the restore's lock acquisition");
359
+ }
360
+ this.#path = path;
361
+ }
362
+
363
+ /** The live store path the lock is held on. */
364
+ get path(): string {
365
+ return this.#path;
366
+ }
367
+ }
368
+
369
+ /** True only for a minted, unreleased token on exactly `path`. */
370
+ function isLiveStoreLockToken(token: unknown, path: string): boolean {
371
+ return token instanceof StoreLockToken && liveStoreLockTokens.get(token) === path;
372
+ }
373
+
374
+ export interface SnapshotInfo {
375
+ readonly run_id: string;
376
+ readonly path: string;
377
+ /**
378
+ * ISO-8601 UTC creation time: the `generated_at` the manifest sidecar
379
+ * recorded when the archive was taken, or the archive file's mtime when
380
+ * there is no readable sidecar. The manifest wins because an mtime is a
381
+ * property of the copy, not of the snapshot: `rsync -t`, `cp -p` or a
382
+ * stepped clock rewrite it, and retention orders by this field.
383
+ */
384
+ readonly created_at: string;
385
+ /**
386
+ * Present only when the sidecar's `generated_at` was set aside for the
387
+ * mtime: why it was not believed (later than now, or earlier than the
388
+ * time the run id itself carries). A hand-edited sidecar or a broken
389
+ * clock would otherwise pin one archive as the newest forever, and every
390
+ * prune would then delete the genuinely newest ones.
391
+ */
392
+ readonly created_at_untrusted?: string;
393
+ readonly size_bytes: number;
394
+ /**
395
+ * Absolute path of the sidecar manifest, or `null` when the
396
+ * sidecar write failed at snapshot time (read-only directory or
397
+ * similar). Rollback gracefully degrades on `null`.
398
+ */
399
+ readonly manifest_path: string | null;
400
+ /**
401
+ * Absolute path of the sibling derived-store archive when one is on
402
+ * disk, `null` otherwise. Probed rather than believed: the manifest
403
+ * says what the snapshot INTENDED, this says what retention has to
404
+ * delete.
405
+ */
406
+ readonly store_archive_path: string | null;
407
+ /**
408
+ * The sidecar's derived-store record, or `null` when there is no
409
+ * sidecar or the sidecar predates the feature. `null` is UNKNOWN
410
+ * coverage and must never be rendered as "excluded".
411
+ */
412
+ readonly derived_store: BrainManifestDerivedStore | null;
413
+ /**
414
+ * Why the recovery point was taken, read back off the sidecar, or
415
+ * `null` when there is no sidecar, the sidecar is unreadable, or it
416
+ * predates the reason. `null` is UNKNOWN and is NOT recovered from the
417
+ * run id, even though every run id this project mints begins with the
418
+ * reason: parsing it back would report provenance for an archive that
419
+ * never recorded any.
420
+ */
421
+ readonly reason: BrainSnapshotReason | null;
422
+ }
423
+
424
+ /**
425
+ * Why one `.snapshots/` entry could not become a {@link SnapshotInfo}.
426
+ *
427
+ * Both members describe an entry that IS an archive by name - the suffix
428
+ * matched - and could not be turned into a listing row. A file that is not
429
+ * an archive at all (a sidecar manifest, a store archive, an operator's
430
+ * stray note) is not in this vocabulary: it is not a recovery point that
431
+ * could not be read, it is not a recovery point.
432
+ */
433
+ export const SNAPSHOT_ENTRY_SKIP_REASON = Object.freeze({
434
+ /** The name carries the archive suffix and the run id inside it does not validate. */
435
+ runIdUnparseable: "run_id_unparseable",
436
+ /** The archive is named in the directory and could not be stat'ed. */
437
+ entryUnreadable: "entry_unreadable",
438
+ } as const);
439
+
440
+ export type SnapshotEntrySkipReason =
441
+ (typeof SNAPSHOT_ENTRY_SKIP_REASON)[keyof typeof SNAPSHOT_ENTRY_SKIP_REASON];
442
+
443
+ export const SNAPSHOT_ENTRY_SKIP_REASONS: ReadonlyArray<SnapshotEntrySkipReason> = Object.freeze(
444
+ Object.values(SNAPSHOT_ENTRY_SKIP_REASON),
445
+ );
446
+
447
+ export function isSnapshotEntrySkipReason(value: unknown): value is SnapshotEntrySkipReason {
448
+ return (
449
+ typeof value === "string" &&
450
+ (SNAPSHOT_ENTRY_SKIP_REASONS as ReadonlyArray<string>).includes(value)
451
+ );
452
+ }
453
+
454
+ /** One archive-shaped entry that is missing from {@link SnapshotListing.snapshots}. */
455
+ export interface SnapshotEntrySkip {
456
+ /** Directory entry name, as `readdir` reported it. */
457
+ readonly name: string;
458
+ /** Absolute path of that entry. */
459
+ readonly path: string;
460
+ readonly reason: SnapshotEntrySkipReason;
461
+ /** The underlying failure, in the words of whatever refused. */
462
+ readonly detail: string;
463
+ }
464
+
465
+ /**
466
+ * One skipped entry as a phrase, spelled once for every surface that
467
+ * reports one: the doctor's uncertain stream and both CLI listings say the
468
+ * same thing about the same file, and a second wording would be a second
469
+ * claim about it.
470
+ */
471
+ export function describeSnapshotEntrySkip(skip: SnapshotEntrySkip): string {
472
+ return `${skip.name} (${skip.reason}: ${skip.detail})`;
473
+ }
474
+
475
+ /**
476
+ * What {@link listSnapshots} found: the recovery points it could describe,
477
+ * and the archive-shaped entries it could not.
478
+ *
479
+ * Two fields rather than one array because "these are the recovery points"
480
+ * and "this listing is complete" are two different facts, and the second
481
+ * one used to have no wire at all: every per-entry failure was dropped, so
482
+ * a directory full of archives nobody could stat answered exactly like a
483
+ * vault that had never taken one. Callers that only count archives read
484
+ * {@link snapshots}; callers that tell an operator what their vault
485
+ * contains have to read {@link skipped} too, and the compiler now makes
486
+ * them look at it.
487
+ */
488
+ export interface SnapshotListing {
489
+ /** Newest-first by archive mtime. */
490
+ readonly snapshots: SnapshotInfo[];
491
+ /** Empty when every archive-shaped entry became a row. */
492
+ readonly skipped: ReadonlyArray<SnapshotEntrySkip>;
493
+ }
494
+
495
+ /**
496
+ * Why a prune did not remove what it was asked to.
497
+ *
498
+ * One member, and it is the one that mattered: `snapshots.retention_count`
499
+ * is operator-supplied, and a zero silently removed every recovery point
500
+ * in the vault on the next dream. A refusal is a value here rather than a
501
+ * throw because the prune runs as a hygiene step behind every snapshot -
502
+ * throwing would fail the operation the snapshot was protecting, which
503
+ * trades a real guarantee for a tidy directory.
504
+ */
505
+ export const SNAPSHOT_PRUNE_REFUSAL = Object.freeze({
506
+ /** The requested retention is under {@link SNAPSHOT_RETENTION_FLOOR}. */
507
+ belowRetentionFloor: "below_retention_floor",
508
+ } as const);
509
+
510
+ /** Closed union over {@link SNAPSHOT_PRUNE_REFUSAL}. */
511
+ export type SnapshotPruneRefusal =
512
+ (typeof SNAPSHOT_PRUNE_REFUSAL)[keyof typeof SNAPSHOT_PRUNE_REFUSAL];
513
+
514
+ /** Membership list, in declaration order. */
515
+ export const SNAPSHOT_PRUNE_REFUSALS: ReadonlyArray<SnapshotPruneRefusal> = Object.freeze(
516
+ Object.values(SNAPSHOT_PRUNE_REFUSAL),
517
+ );
518
+
519
+ /**
520
+ * `unknown` rather than `string`: the value rides out of TypeScript in
521
+ * the prune report a caller may persist or print, and the vocabulary
522
+ * census probes every guard with `null`, `42` and `{}`.
523
+ */
524
+ export function isSnapshotPruneRefusal(value: unknown): value is SnapshotPruneRefusal {
525
+ return (
526
+ typeof value === "string" && (SNAPSHOT_PRUNE_REFUSALS as ReadonlyArray<string>).includes(value)
527
+ );
528
+ }
529
+
530
+ /**
531
+ * The smallest retention {@link pruneSnapshots} will act on.
532
+ *
533
+ * One, because one archive is the difference between a vault with a way
534
+ * back and a vault without one. A retention of zero is a configuration
535
+ * that asks the most destructive operation in this module to leave
536
+ * nothing behind, and obeying it silently is what made it dangerous.
537
+ */
538
+ export const SNAPSHOT_RETENTION_FLOOR = 1;
539
+
540
+ export interface PruneSnapshotsOptions {
541
+ /**
542
+ * Run ids this pass must never remove, whatever the ordering says.
543
+ *
544
+ * The retention order was by MTIME when this was added (it is now the
545
+ * manifest's creation time, falling back to mtime for an archive with
546
+ * no readable sidecar), and the caller that most needs this
547
+ * is the one that just wrote an archive: "the newest file is the newest
548
+ * mtime" is an assumption about the filesystem, not arithmetic. `rsync
549
+ * -t`, `cp -p`, an NFS server with clock skew, or a system clock
550
+ * stepped backwards all leave an older archive claiming a newer mtime,
551
+ * and at retention 1 the prune then evicted the recovery point the gate
552
+ * had made one line earlier - which the gate reported as `covered`.
553
+ *
554
+ * The rollback is the second such caller: it takes a recovery point
555
+ * mid-restore, and the archive being restored is still being read from
556
+ * `.snapshots/` (its manifest sidecar, its derived-store archive) after
557
+ * that point lands. Both are named here rather than trusted to sort.
558
+ */
559
+ readonly protectRunIds?: ReadonlyArray<string>;
560
+ /** The write lane the prune's guard checks; see {@link CreateSnapshotOptions.lane}. */
561
+ readonly lane?: WriteLane;
562
+ }
563
+
564
+ export interface PruneSnapshotsResult {
565
+ /** Vault-relative path of each deleted archive. */
566
+ readonly deleted: ReadonlyArray<string>;
567
+ /**
568
+ * Archives the prune tried and failed to remove. Previously swallowed
569
+ * whole: a permission error left the archive in place and reported a
570
+ * clean prune, so retention silently stopped working and nothing said
571
+ * so.
572
+ */
573
+ readonly failed: ReadonlyArray<string>;
574
+ /**
575
+ * How many archives the listing could DESCRIBE when the prune returns.
576
+ *
577
+ * An entry `listSnapshots` had to skip - a run id that will not validate,
578
+ * a `stat` that failed - is still on disk and is not in this count, and
579
+ * is not a prune candidate either: this function removes what it can
580
+ * name. {@link SnapshotListing.skipped} is where those are reported.
581
+ */
582
+ readonly retained: number;
583
+ /** Why nothing was pruned, or `null` when the prune ran. */
584
+ readonly refusal: SnapshotPruneRefusal | null;
585
+ }
586
+
587
+ /**
588
+ * What a restore did about the derived store. Separate fields rather than
589
+ * a single verdict string, because "not replaced" splits into answers an
590
+ * operator must be able to tell apart: the snapshot recorded that it did
591
+ * not include the store, or the snapshot carries no record at all.
592
+ */
593
+ export interface RestoreDerivedStoreResult {
594
+ /** True when the archived store replaced the live one. */
595
+ readonly replaced: boolean;
596
+ /**
597
+ * False when the snapshot carries no derived-store record: coverage is
598
+ * unknown, and the live store was deliberately left untouched.
599
+ */
600
+ readonly coverage_known: boolean;
601
+ /** Absolute path of the store that was replaced; null when none was. */
602
+ readonly path: string | null;
603
+ /** The manifest's named reason; null when included or unknown. */
604
+ readonly exclusion_reason: SnapshotStoreExclusionReason | null;
605
+ /**
606
+ * Whether a sibling store archive is on disk for this snapshot, probed
607
+ * rather than believed.
608
+ *
609
+ * Load-bearing exactly when {@link coverage_known} is false. The sidecar
610
+ * write is non-fatal in `createSnapshot`, so coverage can run to
611
+ * completion and leave no record of itself - and an archive sitting
612
+ * beside the tar proves that happened. Without this field the reporting
613
+ * surface had one sentence for two facts and chose the wrong one: it
614
+ * called a lost RECORD a snapshot older than the FEATURE, while the
615
+ * evidence to the contrary was in the same directory.
616
+ */
617
+ readonly store_archive_present: boolean;
618
+ }
619
+
620
+ export interface RestoreSnapshotResult {
621
+ /** Number of regular files restored under `Brain/` (excluding the excluded entries). */
622
+ readonly restored_files: number;
623
+ readonly derived_store: RestoreDerivedStoreResult;
624
+ /**
625
+ * What the LIVE tree's recoverability was worth at the moment it was
626
+ * discarded - not the archive's. A restore deletes every top-level
627
+ * entry under `Brain/` and, before this field existed, said nothing
628
+ * about the state it destroyed doing so. Without a
629
+ * {@link RestoreSnapshotOptions.beforeDiscard} this reads `unproven`,
630
+ * which is the honest answer and the reason `restoreSnapshotWithRecoveryPoint`
631
+ * exists.
632
+ */
633
+ readonly recoverability: RecoverabilityVerdict;
634
+ }
635
+
636
+ /**
637
+ * What a {@link RestoreSnapshotOptions.beforeDiscard} callback hands back
638
+ * to prove it archived the tree about to be discarded.
639
+ *
640
+ * A structural pair rather than the gate's own `DestructiveSnapshot`,
641
+ * because this module is the one `snapshot-gate.ts` composes: importing
642
+ * its type back would make the pair a cycle. The `path` is the field that
643
+ * matters - {@link restoreSnapshot} probes it on disk, so the verdict
644
+ * rests on an archive rather than on a promise that one was taken.
645
+ */
646
+ export interface RecoveryPointEvidence {
647
+ /** Run id of the archive the callback wrote. */
648
+ readonly runId: string;
649
+ /** Absolute path of that archive. */
650
+ readonly path: string;
651
+ }
652
+
653
+ /**
654
+ * What {@link restoreSnapshot} tells its
655
+ * {@link RestoreSnapshotOptions.beforeDiscard} callback.
656
+ */
657
+ export interface BeforeDiscardContext {
658
+ /**
659
+ * The live derived store the restore will replace, or null when it
660
+ * does not replace the store. A recovery point taken here archives
661
+ * exactly this path (`derivedStorePath`), and the restore refuses when
662
+ * the recovery point's manifest records another source.
663
+ */
664
+ readonly storeTarget: string | null;
665
+ /**
666
+ * The token of the writer lock the restore holds on
667
+ * {@link storeTarget}, or null when it holds none. The lock is taken
668
+ * before the callback and kept through the swap, so a recovery point
669
+ * taken here sees every commit the swap replaces. A snapshot taken in
670
+ * the callback passes it as `heldStoreLock`, or its own acquire of the
671
+ * same lock refuses. The token stops counting once the restore
672
+ * releases the lock.
673
+ */
674
+ readonly heldStoreLock: StoreLockToken | null;
675
+ }
676
+
677
+ export interface RestoreSnapshotOptions extends SnapshotStoreOptions {
678
+ /**
679
+ * The write lane the restore is guarded on (default: content), as the
680
+ * recovery point taken before it is: a restore that passes `audit` on a
681
+ * frozen vault is not refused after its recovery point was taken.
682
+ */
683
+ readonly lane?: WriteLane;
684
+ /**
685
+ * Called once, AFTER the archive has been extracted into a temp
686
+ * directory and BEFORE the first live entry is removed. That ordering
687
+ * is the whole contract: extraction can fail on a corrupt or missing
688
+ * archive, and a rollback that never touched the tree must not leave a
689
+ * recovery point of it.
690
+ *
691
+ * Extraction being done is NOT the same as the restore being done with
692
+ * `.snapshots/`: the manifest sidecar and the derived-store archive are
693
+ * read after this callback returns, which is why a callback that prunes
694
+ * is checked rather than trusted - see the re-validation in
695
+ * {@link restoreSnapshot}.
696
+ *
697
+ * Return {@link RecoveryPointEvidence} to have the restore's
698
+ * recoverability verdict count the archive. Returning nothing is a
699
+ * legitimate answer and reads as `unproven`: the verdict is derived
700
+ * from an archive being on disk when the restore finishes, never from
701
+ * the fact that a callback was supplied.
702
+ *
703
+ * Injected rather than called directly because the recovery point is
704
+ * minted by `snapshot-gate.ts`, which composes THIS module - taking
705
+ * `takeSnapshot` from there would make the pair a cycle.
706
+ */
707
+ readonly beforeDiscard?: (ctx: BeforeDiscardContext) => RecoveryPointEvidence | void;
708
+ }
709
+
710
+ // ----- Tooling detection ---------------------------------------------------
711
+
712
+ interface ToolAvailability {
713
+ readonly tar: boolean;
714
+ readonly zstd: boolean;
715
+ }
716
+
717
+ /**
718
+ * Detect tool availability by walking `process.env.PATH` and checking
719
+ * the candidate binary exists. We deliberately avoid `spawnSync(cmd,
720
+ * ["--version"])` because the underlying Node/Bun runtime resolves
721
+ * commands against an internal PATH snapshot taken at process start
722
+ * — so tests that mutate `process.env.PATH` between calls would have
723
+ * no effect on a `spawnSync` probe. Reading the filesystem at probe
724
+ * time keeps the detection honest and test-controllable.
725
+ *
726
+ * The cost (a handful of `existsSync` calls) is dwarfed by the actual
727
+ * archive operation that follows.
728
+ */
729
+ function detectTooling(): ToolAvailability {
730
+ const pathEnv = process.env["PATH"] ?? "";
731
+ const dirs = pathEnv.split(process.platform === "win32" ? ";" : ":").filter((d) => d.length > 0);
732
+ const winExts =
733
+ process.platform === "win32"
734
+ ? (process.env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";")
735
+ : [];
736
+ const probe = (cmd: string): boolean => {
737
+ for (const d of dirs) {
738
+ if (existsSync(join(d, cmd))) return true;
739
+ for (const ext of winExts) {
740
+ if (existsSync(join(d, cmd + ext.toLowerCase()))) return true;
741
+ }
742
+ }
743
+ return false;
744
+ };
745
+ return {
746
+ tar: probe("tar"),
747
+ zstd: probe("zstd"),
748
+ };
749
+ }
750
+
751
+ /**
752
+ * A filesystem path spelled for a `tar` argument on this host.
753
+ *
754
+ * On Windows two tars answer to the name `tar`: bsdtar in `System32`, and
755
+ * the MSYS GNU tar that Git for Windows puts on PATH - ahead of `System32`
756
+ * inside Git Bash (where hooks run) and on GitHub's Windows runners. GNU
757
+ * tar under MSYS fails to extract into a backslashed `-C C:\...`
758
+ * ("Cannot open: No such file or directory"). Both tars accept the same
759
+ * path with forward slashes, which Windows itself treats as separators, so
760
+ * every path this module hands to tar goes through here. POSIX paths are
761
+ * returned unchanged.
762
+ *
763
+ * Archives are always passed through stdin/stdout (`-f -`), never by name:
764
+ * GNU tar reads the drive colon in `-f C:\...` as a remote host.
765
+ */
766
+ export function tarPathArg(path: string, platform: NodeJS.Platform = process.platform): string {
767
+ return platform === "win32" ? path.replaceAll("\\", "/") : path;
768
+ }
769
+
770
+ // ----- createSnapshot ------------------------------------------------------
771
+
772
+ /**
773
+ * `rel` (vault-relative, `/`-separated) followed by everything beneath it,
774
+ * depth-first with siblings in byte order. Symlinked directories are listed
775
+ * but not entered - the same as tar's own default. Exported for tests.
776
+ *
777
+ * Names are raw bytes (`Buffer`), not strings: a POSIX file name need not be
778
+ * UTF-8, and a latin1 `caf\xe9.md` decoded to a string comes back as
779
+ * `caf\uFFFD.md` - a name that does not exist, which GNU tar then refuses
780
+ * to archive. On Windows they are the UTF-8 of the UTF-16 name, which the
781
+ * in-process writer opens as a path (`tar.exe` would read them in the ANSI
782
+ * code page).
783
+ *
784
+ * The walk is exhaustive or it fails. tar is told not to recurse, so a
785
+ * directory this walk could not read would be archived EMPTY, and bsdtar
786
+ * (macOS, Windows `tar.exe`) reports success for that - a recovery point
787
+ * silently missing data. An entry that vanished mid-walk (ENOENT) is simply
788
+ * not in the tree any more and is left out; any other error is thrown as a
789
+ * {@link BrainSnapshotError} naming the path.
790
+ */
791
+ export function sortedMembers(
792
+ vault: string,
793
+ rel: Buffer,
794
+ runId: string,
795
+ emptyLocks?: Set<string>,
796
+ ): Buffer[] {
797
+ const abs = Buffer.concat([Buffer.from(vault), SLASH, rel]);
798
+ let entries: Buffer[];
799
+ try {
800
+ const stat = lstatSync(abs);
801
+ // A transient of the product itself (`snapshot-transient.ts`: a form no
802
+ // content has) is never archived, a lock directory included, which is
803
+ // judged before it is entered.
804
+ const name = memberName(rel);
805
+ const dir = Buffer.concat([Buffer.from(vault), SLASH, rel.subarray(0, rel.lastIndexOf(SLASH))]);
806
+ const beside = (original: string): boolean =>
807
+ existsSync(Buffer.concat([dir, SLASH, Buffer.from(original)]));
808
+ // Any answer but content leaves it out, `vanished` included: an entry
809
+ // gone between this `lstat` and the classifier's read is not in the tree.
810
+ if (productTransientKind(abs, name, stat, beside) !== null) return [];
811
+ if (!stat.isDirectory()) {
812
+ // An empty `<target>.lock` the rule above does not know: archived, and
813
+ // remembered, because a lock helper's file looks like this between its
814
+ // create and its stamp (`snapshotVanishedTolerable`).
815
+ if (emptyLocks !== undefined && stat.isFile() && stat.size === 0 && name.endsWith(".lock")) {
816
+ emptyLocks.add(rel.toString("hex"));
817
+ }
818
+ return [rel];
819
+ }
820
+ entries = readdirSync(abs, { encoding: "buffer" });
821
+ } catch (err) {
822
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
823
+ throw new BrainSnapshotError(
824
+ `cannot read ${rel.toString()} to archive it: ${(err as Error).message ?? String(err)}`,
825
+ runId,
826
+ { cause: err },
827
+ );
828
+ }
829
+ const out = [rel];
830
+ for (const name of entries.toSorted(Buffer.compare)) {
831
+ out.push(...sortedMembers(vault, Buffer.concat([rel, SLASH, name]), runId, emptyLocks));
832
+ }
833
+ return out;
834
+ }
835
+
836
+ const SLASH = Buffer.from("/");
837
+ const NUL = Buffer.from([0]);
838
+
839
+ /** The last `/`-separated segment of a member, as a name. */
840
+ function memberName(rel: Buffer): string {
841
+ return rel.subarray(rel.lastIndexOf(SLASH) + 1).toString("utf8");
842
+ }
843
+
844
+ /**
845
+ * Whether the listed members that vanished let a snapshot whose tar failed
846
+ * list the tree again and retry. Only a member that was, when listed, an
847
+ * EMPTY `<target>.lock` file qualifies: the form a lock of
848
+ * `sync-lockfile.ts` has between its exclusive create and its stamp (once
849
+ * stamped the listing leaves it out), and one that held no byte, so the
850
+ * new listing loses nothing. Any other vanished member, an unknown
851
+ * `.lock` with content or a `.tmp` file included, is a vanished content
852
+ * file and fails the snapshot.
853
+ */
854
+ function snapshotVanishedTolerable(
855
+ vanished: ReadonlyArray<Buffer>,
856
+ emptyLocks: ReadonlySet<string>,
857
+ ): boolean {
858
+ return vanished.length > 0 && vanished.every((m) => emptyLocks.has(m.toString("hex")));
859
+ }
860
+
861
+ /** How many times a snapshot lists and archives the tree when only transient files vanished. */
862
+ const SNAPSHOT_VANISHED_ATTEMPTS = 3;
863
+
864
+ /** The members of `members` no longer on disk (`lstat` finds nothing). */
865
+ function vanishedMembers(vault: string, members: ReadonlyArray<Buffer>): Buffer[] {
866
+ return members.filter((m) => {
867
+ try {
868
+ lstatSync(Buffer.concat([Buffer.from(vault), SLASH, m]));
869
+ return false;
870
+ } catch (err) {
871
+ const code = (err as NodeJS.ErrnoException).code;
872
+ return code === "ENOENT" || code === "ENOTDIR";
873
+ }
874
+ });
875
+ }
876
+
877
+ /**
878
+ * Make `Brain/.snapshots/` exist, or say what is there instead.
879
+ *
880
+ * This `mkdir` is the first disk touch of every snapshot, which makes it the
881
+ * first thing that can fail and the worst place to fail opaquely. It used to
882
+ * be a bare `mkdirSync`, so its errno left the module naming a syscall and a
883
+ * path and nothing else - and, worse, reached the run-id allocator in
884
+ * `snapshot-gate.ts`, which read the EEXIST as a lost race over the run id
885
+ * and reported an id exhaustion that had never happened (GitHub #167).
886
+ *
887
+ * `recursive: true` already tolerates the normal case of the directory
888
+ * existing, so a throw from here means the path is NOT a usable directory.
889
+ * Which of the several ways that can be true is the only question the
890
+ * operator has, and it is answerable on the spot: `lstat` the path and say
891
+ * what is really there. A regular file, a symlink, a socket left by some
892
+ * other tool, a parent that is not a directory, a permission fault - each has
893
+ * a different remedy and the errno alone distinguishes none of them.
894
+ *
895
+ * The errno is carried as `cause`, not folded away: the diagnosis explains
896
+ * the failure, it does not replace the evidence. A {@link BrainSnapshotError}
897
+ * rather than a bare throw so this leaves the module in the one shape every
898
+ * caller of {@link createSnapshot} already handles, run id included.
899
+ */
900
+ function ensureSnapshotsDirectory(path: string, runId: string): void {
901
+ try {
902
+ mkdirSync(path, { recursive: true });
903
+ return;
904
+ } catch (err) {
905
+ throw new BrainSnapshotError(
906
+ `cannot use the archive directory ${BRAIN_SNAPSHOTS_REL} at ${path}: ` +
907
+ `${describeExistingPath(path)} (${(err as Error).message ?? String(err)}); ` +
908
+ `no recovery point can be written until ${BRAIN_SNAPSHOTS_REL} is a writable directory`,
909
+ runId,
910
+ { cause: err },
911
+ );
912
+ }
913
+ }
914
+
915
+ /**
916
+ * What is actually at `path`, in one clause an operator can act on.
917
+ *
918
+ * `lstat` rather than `stat` because a dangling or looping symlink is one of
919
+ * the states that produces this failure, and `stat` would report the target's
920
+ * absence instead of the link's presence. Its own failure is reported rather
921
+ * than swallowed: "the path cannot even be inspected" is a different remedy
922
+ * (permissions on the parent) from "the path holds the wrong kind of thing".
923
+ */
924
+ function describeExistingPath(path: string): string {
925
+ let info: ReturnType<typeof lstatSync>;
926
+ try {
927
+ info = lstatSync(path);
928
+ } catch (err) {
929
+ const code = (err as NodeJS.ErrnoException).code;
930
+ if (code === "ENOENT") return "nothing is there, so the directory itself could not be created";
931
+ return `it could not be inspected either (${code ?? (err as Error).message})`;
932
+ }
933
+ if (info.isDirectory()) return "it is a directory, but it could not be created or opened as one";
934
+ if (info.isSymbolicLink()) {
935
+ return existsSync(path)
936
+ ? "it is a symbolic link to something that is not a usable directory"
937
+ : "it is a symbolic link whose target does not exist";
938
+ }
939
+ if (info.isFile()) return "it is a regular file";
940
+ if (info.isSocket()) return "it is a socket";
941
+ if (info.isFIFO()) return "it is a FIFO";
942
+ return "it is not a directory";
943
+ }
944
+
945
+ /**
946
+ * Archive `Brain/` (minus {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES}) into
947
+ * `Brain/.snapshots/<run_id>.tar.zst`, optionally beside a compressed
948
+ * copy of the derived store.
949
+ *
950
+ * Implementation:
951
+ *
952
+ * 1. Detect available tools. If `tar` is absent we throw.
953
+ * 2. Cover the derived store FIRST, so a refusal leaves no tar behind.
954
+ * 3. List the top-level entries under `Brain/`, drop the excluded ones.
955
+ * 4. `tar -c -C <vault> Brain/<entry> ...` streamed into `zstd -19`
956
+ * (or `gzip -9` fallback) → output file.
957
+ *
958
+ * Using `--exclude=Brain/.snapshots` is tempting, but tar's exclude
959
+ * pattern matching is shell-dependent and prone to subtle surprises
960
+ * on filenames containing whitespace. Enumerating the kept entries
961
+ * explicitly is byte-stable and easy to reason about.
962
+ */
963
+ export function createSnapshot(
964
+ vault: string,
965
+ runId: string,
966
+ opts: CreateSnapshotOptions,
967
+ ): CreateSnapshotResult {
968
+ // The log event names the caller's vault; the archive is of the state root.
969
+ const logVault = vault;
970
+ vault = machineStateRoot(vault);
971
+ validateRunId(runId);
972
+ const dirs = brainDirsForWrite(vault, undefined, opts.lane);
973
+ ensureSnapshotsDirectory(dirs.snapshots, runId);
974
+
975
+ const outPath = snapshotPath(vault, runId);
976
+ const tools = detectTooling();
977
+ if (!tools.tar) {
978
+ throw new BrainSnapshotToolingMissingError(
979
+ "tar",
980
+ "install GNU tar or BSD tar; both are supported.",
981
+ );
982
+ }
983
+
984
+ // The derived store goes first. It is the step that can REFUSE, and a
985
+ // refusal must leave nothing behind - running it before the tar is
986
+ // written is what makes "no partial archive" a property of the order
987
+ // rather than of a cleanup path that could be forgotten.
988
+ const derivedStore = coverDerivedStore(vault, logVault, runId, tools, opts);
989
+
990
+ // The top-level entries of Brain/ to capture, listed again at every
991
+ // attempt below (a temp file renamed onto its final name between two
992
+ // attempts is found under that name). Sorted so the archive's contents
993
+ // are deterministic across filesystems (readdirSync's order is
994
+ // FS-dependent).
995
+ const listTop = (): Buffer[] => {
996
+ try {
997
+ return readdirSync(dirs.brain, { encoding: "buffer" })
998
+ .filter((e) => !isSnapshotExcludedEntry(bufferEntryName(e)))
999
+ .toSorted(Buffer.compare);
1000
+ } catch (err) {
1001
+ throw new BrainSnapshotError(
1002
+ `failed to list Brain/: ${(err as Error).message ?? String(err)}`,
1003
+ runId,
1004
+ );
1005
+ }
1006
+ };
1007
+
1008
+ // Paths inside the archive start at `Brain/` — matching the rollback
1009
+ // contract that the archive is "the Brain/ tree". Every member is
1010
+ // listed explicitly, depth-first in sorted order, and tar is told not
1011
+ // to recurse: left to itself tar walks each directory in `readdir`
1012
+ // order, which differs between two copies of the same tree (ext4 hash
1013
+ // order, NTFS, APFS). The member ORDER is therefore deterministic; the
1014
+ // bytes are not (tar headers still carry mtime, owner and mode).
1015
+ // The list travels NUL-separated through a file (`--null -T`), which
1016
+ // GNU tar and macOS bsdtar accept and which survives any character a
1017
+ // filename can hold. Windows `tar.exe` reads that list in the ANSI code
1018
+ // page, so there the stream is written in process instead
1019
+ // (`writeArchiveInProcess`).
1020
+ const listDir = mkdtempSync(join(tmpdir(), `o2b-snapshot-list-${runId}-`));
1021
+ const listPath = join(listDir, "members");
1022
+
1023
+ try {
1024
+ const tarPath = join(listDir, "brain.tar");
1025
+ // A listed member another process removes before tar reads it fails
1026
+ // tar: GNU tar and macOS bsdtar say "<path>: Cannot stat: No such file
1027
+ // or directory", Windows tar.exe (bsdtar) has been seen saying
1028
+ // ": Couldn't visit directory" with no name. Each reads the same NUL
1029
+ // list, so the check below re-reads the disk rather than the tool's
1030
+ // words: when every member that vanished was an empty lock file
1031
+ // (`snapshotVanishedTolerable`), the tree is listed again and archived
1032
+ // again; anything else that vanished fails the snapshot.
1033
+ for (let attempt = 1; ; attempt++) {
1034
+ const emptyLocks = new Set<string>();
1035
+ const members = listTop().flatMap((e) =>
1036
+ sortedMembers(
1037
+ vault,
1038
+ Buffer.concat([Buffer.from(`${BRAIN_ROOT_REL}/`), e]),
1039
+ runId,
1040
+ emptyLocks,
1041
+ ),
1042
+ );
1043
+ rmSync(tarPath, { force: true });
1044
+ try {
1045
+ if (process.platform === "win32") {
1046
+ writeArchiveInProcess(vault, members, tarPath, runId);
1047
+ } else {
1048
+ writeFileSync(listPath, Buffer.concat(members.flatMap((m) => [m, NUL])));
1049
+ runTar(vault, listPath, tarPath, runId);
1050
+ }
1051
+ break;
1052
+ } catch (err) {
1053
+ const vanished = vanishedMembers(vault, members);
1054
+ const retry =
1055
+ attempt < SNAPSHOT_VANISHED_ATTEMPTS && snapshotVanishedTolerable(vanished, emptyLocks);
1056
+ if (!retry) throw err;
1057
+ }
1058
+ }
1059
+ compressInto({ kind: "file", path: tarPath }, outPath, tools, runId);
1060
+ if (!existsSync(outPath)) {
1061
+ throw new BrainSnapshotError(
1062
+ `archive write reported success but ${outPath} is absent`,
1063
+ runId,
1064
+ );
1065
+ }
1066
+ } catch (err) {
1067
+ // The store archive we just wrote belongs to a snapshot that does
1068
+ // not exist. Leaving it would make the run id look taken to the
1069
+ // collision resolver and would survive retention, which only prunes
1070
+ // archives it can list.
1071
+ discardStoreArchive(derivedStore, vault, runId);
1072
+ throw err;
1073
+ } finally {
1074
+ rmSync(listDir, { recursive: true, force: true });
1075
+ }
1076
+ return finishSnapshot(vault, logVault, runId, dirs, derivedStore, opts, outPath);
1077
+ }
1078
+
1079
+ /**
1080
+ * The tar stream of a snapshot on Windows, written in process
1081
+ * (`tar-writer.ts`). `tar.exe` there (bsdtar in `System32`) reads the
1082
+ * names of a `-T` list, and its `-C` directory, in the ANSI code page,
1083
+ * so a member named in Cyrillic, CJK or with an accent (a decision or topic
1084
+ * slug in any script) decoded to a name that does not exist, often an
1085
+ * empty one ("tar: : Couldn't visit directory"), and every snapshot of
1086
+ * such a tree failed. The writer takes the names as Node paths (UTF-16)
1087
+ * and stores them as UTF-8 pax records, which both tars extract under the
1088
+ * right name. A member that vanished fails like a tar run that missed it,
1089
+ * so the caller's vanished-member check decides the same way.
1090
+ */
1091
+ function writeArchiveInProcess(
1092
+ vault: string,
1093
+ members: ReadonlyArray<Buffer>,
1094
+ tarPath: string,
1095
+ runId: string,
1096
+ ): void {
1097
+ try {
1098
+ keepLeasesFreshInProcess(() => writeTarArchive(vault, members, tarPath));
1099
+ } catch (err) {
1100
+ throw new BrainSnapshotError(
1101
+ `archive write failed: ${(err as Error).message ?? String(err)}`,
1102
+ runId,
1103
+ { cause: err },
1104
+ );
1105
+ }
1106
+ }
1107
+
1108
+ /** The tar run of a snapshot: the NUL-separated member list `listPath`, no recursion, into `tarPath`. */
1109
+ function runTar(vault: string, listPath: string, tarPath: string, runId: string): void {
1110
+ const tarArgs = [
1111
+ "-c",
1112
+ "-f",
1113
+ "-",
1114
+ "-C",
1115
+ tarPathArg(vault),
1116
+ "--no-recursion",
1117
+ "--null",
1118
+ "-T",
1119
+ tarPathArg(listPath),
1120
+ ];
1121
+ // tar writes into a staging file beside the member list rather than
1122
+ // into a captured pipe, and the compressor reads that file: neither
1123
+ // the tar stream nor the compressed archive ever sits in this
1124
+ // process's memory, so the size of `Brain/` sets no ceiling here.
1125
+ runArchiveProducer("tar", tarArgs, tarPath, runId, {
1126
+ ...process.env,
1127
+ COPYFILE_DISABLE: "1",
1128
+ });
1129
+ }
1130
+
1131
+ /** The sidecar manifest and the log line of a snapshot whose archive is on disk. */
1132
+ function finishSnapshot(
1133
+ vault: string,
1134
+ logVault: string,
1135
+ runId: string,
1136
+ dirs: ReturnType<typeof brainDirsForWrite>,
1137
+ derivedStore: CreateSnapshotResult["derived_store"],
1138
+ opts: CreateSnapshotOptions,
1139
+ outPath: string,
1140
+ ): CreateSnapshotResult {
1141
+ // Sidecar manifest. Failure is non-fatal: the archive is the
1142
+ // load-bearing artifact, and a snapshot without a manifest just
1143
+ // degrades rollback's drift detection to a silent-overwrite path
1144
+ // (with a warning at rollback time). The alternative — failing
1145
+ // the whole snapshot because the sidecar could not be written —
1146
+ // would block dream from making any progress on a read-only
1147
+ // `.snapshots/` directory.
1148
+ try {
1149
+ writeManifestSidecar(
1150
+ vault,
1151
+ runId,
1152
+ buildManifest(dirs.brain, { derivedStore, snapshotReason: opts.reason }),
1153
+ opts.lane,
1154
+ );
1155
+ } catch (err) {
1156
+ process.stderr.write(
1157
+ `warning: manifest sidecar write failed for snapshot ` +
1158
+ `'${runId}': ${(err as Error).message ?? String(err)}; ` +
1159
+ `rollback drift detection will be skipped for this snapshot.\n`,
1160
+ );
1161
+ }
1162
+
1163
+ logSnapshotEvent(logVault, runId, opts.reason, outPath, opts.now ?? new Date());
1164
+ return { path: outPath, derived_store: derivedStore };
1165
+ }
1166
+
1167
+ /**
1168
+ * Record the recovery point in the Brain event log — the counterpart the
1169
+ * log has been missing since `rollback` was added, which recorded the
1170
+ * restore while the point it restores to left no trace but a filename.
1171
+ *
1172
+ * Best-effort, in the same shape the `rollback` verb already uses for its
1173
+ * own event, and for a stronger reason here: this function runs AFTER the
1174
+ * archive is on disk, and `createSnapshot` is called by the
1175
+ * destructive-snapshot gate before the mutation it protects. A throw would
1176
+ * therefore abort an operation whose recovery point already exists,
1177
+ * turning a lost audit line into a refused mutation. The archive is the
1178
+ * load-bearing artifact; the event is how it is found later.
1179
+ */
1180
+ function logSnapshotEvent(
1181
+ vault: string,
1182
+ runId: string,
1183
+ reason: BrainSnapshotReason,
1184
+ archivePath: string,
1185
+ now: Date,
1186
+ ): void {
1187
+ try {
1188
+ // Measured off the file rather than carried from the compressor, so
1189
+ // the number describes the archive an operator can `ls`. An
1190
+ // unmeasurable archive raises into the handler below and no event is
1191
+ // written: a `0` here would read as an empty archive, which is a real
1192
+ // and very different state.
1193
+ const sizeBytes = statSync(archivePath).size;
1194
+ appendLogEvent(vault, {
1195
+ timestamp: isoSecond(now),
1196
+ eventType: BRAIN_LOG_EVENT_KIND.snapshot,
1197
+ body: { run_id: runId, reason, size_bytes: String(sizeBytes) },
1198
+ });
1199
+ } catch (err) {
1200
+ process.stderr.write(
1201
+ `warning: append snapshot log event failed for '${runId}': ` +
1202
+ `${(err as Error).message ?? String(err)}; the archive itself is intact.\n`,
1203
+ );
1204
+ }
1205
+ }
1206
+
1207
+ /**
1208
+ * Decode one `readdirSync(..., { encoding: "buffer" })` entry to its UTF-8
1209
+ * name.
1210
+ *
1211
+ * The exclusion below is a string comparison, so it holds only while the
1212
+ * entry decodes to its name. Bun and Node document `Buffer` entries, whose
1213
+ * `toString()` is the name, but a runtime that hands back a bare
1214
+ * `Uint8Array` renders comma-joined byte values (`"46,100,..."`) instead:
1215
+ * nothing matches, and `.snapshots` - the archive home - is packed into
1216
+ * every archive, so each one carries its predecessors. `Buffer.from`
1217
+ * decodes either shape.
1218
+ */
1219
+ export function bufferEntryName(e: Uint8Array | Buffer): string {
1220
+ return Buffer.from(e).toString("utf8");
1221
+ }
1222
+
1223
+ /**
1224
+ * True for a top-level `Brain/` entry the snapshot family never touches:
1225
+ * the excluded entries, and a restore's staging directory left directly
1226
+ * under `Brain/` (see {@link BRAIN_RESTORE_STAGING_PREFIX}), which must
1227
+ * never be archived, nor moved aside and put back as Brain content.
1228
+ */
1229
+ export function isSnapshotExcludedEntry(name: string): boolean {
1230
+ return (
1231
+ BRAIN_SNAPSHOT_EXCLUDED_ENTRIES.includes(name) || name.startsWith(BRAIN_RESTORE_STAGING_PREFIX)
1232
+ );
1233
+ }
1234
+
1235
+ // ----- Derived-store coverage ----------------------------------------------
1236
+
1237
+ /**
1238
+ * Byte length of `path`, or `null` when it is not there to measure.
1239
+ * Never zero-as-absent: a freshly created SQLite file is legitimately
1240
+ * small, and an operator reading "0" needs it to mean zero bytes.
1241
+ */
1242
+ function fileSizeOrNull(path: string): number | null {
1243
+ try {
1244
+ const st = statSync(path);
1245
+ return st.isFile() ? st.size : null;
1246
+ } catch {
1247
+ return null;
1248
+ }
1249
+ }
1250
+
1251
+ /**
1252
+ * The live derived store, resolved the way the search layer resolves it.
1253
+ *
1254
+ * The resolver honours the `search_db_path` override; the bare path
1255
+ * helper answers only the default location. That distinction is the whole
1256
+ * point: on a vault carrying the override, an archive built from the
1257
+ * default would describe a file the search layer never reads, and if a
1258
+ * stale database happened to sit there it would have been archived and
1259
+ * reported as a success. It is imported from the resolver leaf rather
1260
+ * than the search barrel because the barrel is reachable from this module
1261
+ * and importing it back closes a cycle the architecture ratchet refuses.
1262
+ */
1263
+ function liveDerivedStorePath(vault: string): string {
1264
+ return resolveConfiguredIndexPath(vault);
1265
+ }
1266
+
1267
+ /**
1268
+ * Decide and, when asked, perform derived-store coverage for one
1269
+ * snapshot. Returns the record the manifest will carry; THROWS
1270
+ * {@link BrainSnapshotStoreError} when coverage was requested and any
1271
+ * step could not be completed.
1272
+ *
1273
+ * The refusal is the point. A snapshot that quietly dropped the store it
1274
+ * was asked to protect would report success, and the destructive
1275
+ * operation it guards would then run against a recovery point that is
1276
+ * not the one the operator configured.
1277
+ */
1278
+ function coverDerivedStore(
1279
+ vault: string,
1280
+ liveVault: string,
1281
+ runId: string,
1282
+ tools: ToolAvailability,
1283
+ opts: SnapshotStoreOptions & { readonly heldStoreLock?: StoreLockToken },
1284
+ ): BrainManifestDerivedStore {
1285
+ // The policy and the live store are the caller's vault's (the search
1286
+ // index is keyed by the real vault), never the mapped state root's; the
1287
+ // archive lands beside the tree it goes with (`vault`).
1288
+ const policy = opts.derivedStore ?? loadSnapshotDerivedStorePolicySafe(liveVault);
1289
+ // Resolved through the search layer's resolver, never re-derived here.
1290
+ const sourcePath = opts.derivedStorePath ?? liveDerivedStorePath(liveVault);
1291
+ const liveSize = fileSizeOrNull(sourcePath);
1292
+
1293
+ const excluded = (reason: SnapshotStoreExclusionReason): BrainManifestDerivedStore =>
1294
+ Object.freeze({
1295
+ included: false,
1296
+ source_path: sourcePath,
1297
+ archive_name: null,
1298
+ archive_sha256: null,
1299
+ archive_size: null,
1300
+ live_size: liveSize,
1301
+ exclusion_reason: reason,
1302
+ });
1303
+
1304
+ if (!policy.include) return excluded(SNAPSHOT_STORE_EXCLUSION.not_requested);
1305
+
1306
+ if (liveSize === null) {
1307
+ throw new BrainSnapshotStoreError(
1308
+ `no store file at ${sourcePath}`,
1309
+ runId,
1310
+ SNAPSHOT_STORE_EXCLUSION.absent,
1311
+ );
1312
+ }
1313
+
1314
+ const archivePath = snapshotStorePath(vault, runId);
1315
+ if (existsSync(archivePath)) {
1316
+ throw new BrainSnapshotError(
1317
+ `refusing to overwrite an existing archive: ${archivePath}`,
1318
+ runId,
1319
+ );
1320
+ }
1321
+
1322
+ // The writer lock on the LIVE store path, held across the integrity
1323
+ // scan and the copy, so an index run cannot mutate the file underneath
1324
+ // the snapshot. It is the same lock every other writer serialises on,
1325
+ // taken synchronously because this whole module is synchronous. A
1326
+ // caller that holds it on this exact path (the gated restore) hands
1327
+ // down the live token the acquisition minted, and the archive is
1328
+ // written under the caller's lock.
1329
+ const release = isLiveStoreLockToken(opts.heldStoreLock, sourcePath)
1330
+ ? (): void => {}
1331
+ : acquireWriterLockSync(sourcePath);
1332
+ try {
1333
+ // Everything under the lock blocks this thread - the integrity scan,
1334
+ // `VACUUM INTO`, the compressor - for minutes on a large store, so the
1335
+ // lock is kept fresh off the thread meanwhile, bounded by the scan and
1336
+ // copy budget plus the compressor's own timeout.
1337
+ let published = false;
1338
+ try {
1339
+ keepWriterLeasesFresh(
1340
+ WRITER_LEASE_BLOCKING_BUDGET_MS + resolveSnapshotToolTimeoutMs(),
1341
+ () => {
1342
+ assertStoreIsSound(sourcePath, runId);
1343
+
1344
+ // Measured against the LIVE size, which is what the operator's
1345
+ // ceiling is expressed in and what they can check with `ls`. The
1346
+ // compressed archive is smaller, but refusing on a number nobody can
1347
+ // predict before the work is done would be a worse contract.
1348
+ if (liveSize > policy.maxBytes) {
1349
+ throw new BrainSnapshotStoreError(
1350
+ `store is ${liveSize} bytes, over the ${policy.maxBytes}-byte ceiling ` +
1351
+ `(snapshots.derived_store_max_bytes)`,
1352
+ runId,
1353
+ SNAPSHOT_STORE_EXCLUSION.over_size_ceiling,
1354
+ );
1355
+ }
1356
+
1357
+ writeStoreArchive(sourcePath, archivePath, tools, runId);
1358
+ published = true;
1359
+ },
1360
+ );
1361
+ } catch (err) {
1362
+ // An archive published before the lock turned out lost (the region's
1363
+ // exit check) is this run's own: the name was free at the check above.
1364
+ // It is removed, so the run leaves nothing a retry under the same id
1365
+ // would be refused for.
1366
+ if (published) rmSync(archivePath, { force: true });
1367
+ if (err instanceof BrainSnapshotError) throw err;
1368
+ throw new BrainSnapshotError(
1369
+ `the derived store's writer lock was lost while its archive was written ` +
1370
+ `(${(err as Error).message ?? String(err)}); no store archive was kept`,
1371
+ runId,
1372
+ { cause: err },
1373
+ );
1374
+ }
1375
+ } finally {
1376
+ release();
1377
+ }
1378
+
1379
+ const archiveSize = fileSizeOrNull(archivePath);
1380
+ if (archiveSize === null) {
1381
+ throw new BrainSnapshotError(
1382
+ `store archive write reported success but ${archivePath} is absent`,
1383
+ runId,
1384
+ );
1385
+ }
1386
+ return Object.freeze({
1387
+ included: true,
1388
+ source_path: sourcePath,
1389
+ archive_name: basename(archivePath),
1390
+ archive_sha256: sha256HexOfFile(archivePath),
1391
+ archive_size: archiveSize,
1392
+ live_size: liveSize,
1393
+ exclusion_reason: null,
1394
+ });
1395
+ }
1396
+
1397
+ /**
1398
+ * Whether the live store at `path` holds data a recovery point must keep:
1399
+ * the file exists and passes the same integrity scan a snapshot runs. An
1400
+ * absent store has nothing to lose, and a condemned one is what a restore
1401
+ * replaces to heal it, so neither forces store coverage on a recovery
1402
+ * point.
1403
+ */
1404
+ export function liveStoreWorthPreserving(path: string): boolean {
1405
+ if (!existsSync(path)) return false;
1406
+ try {
1407
+ assertStoreIsSound(path, "recovery-point-probe");
1408
+ return true;
1409
+ } catch {
1410
+ return false;
1411
+ }
1412
+ }
1413
+
1414
+ /**
1415
+ * Refuse a condemned store rather than archiving it over a good
1416
+ * snapshot.
1417
+ *
1418
+ * This runs the integrity scanner the previous release already shipped -
1419
+ * `PRAGMA quick_check`, classified by {@link runIntegrityCheck} - rather
1420
+ * than inventing a second gate with its own opinion. A file that is not
1421
+ * a SQLite database at all fails here too: `new Database` is lazy, so
1422
+ * the first statement raises and the scanner classifies the raise as a
1423
+ * fault, which is the honest answer.
1424
+ */
1425
+ function assertStoreIsSound(sourcePath: string, runId: string): void {
1426
+ let db: Database;
1427
+ try {
1428
+ db = new Database(sourcePath, { readonly: true });
1429
+ } catch (err) {
1430
+ throw new BrainSnapshotStoreError(
1431
+ `cannot open ${sourcePath}: ${(err as Error).message ?? String(err)}`,
1432
+ runId,
1433
+ SNAPSHOT_STORE_EXCLUSION.integrity_fault,
1434
+ );
1435
+ }
1436
+ try {
1437
+ const verdict = runIntegrityCheck(db);
1438
+ if (!verdict.ok) {
1439
+ // A scan that could not complete vouches for nothing either: the
1440
+ // store is not archived, but it is not called damaged.
1441
+ throw new BrainSnapshotStoreError(
1442
+ verdict.inconclusive === true
1443
+ ? `${sourcePath} could not be checked for integrity: ${verdict.fault}`
1444
+ : `${sourcePath} failed a structural integrity check: ${verdict.fault}`,
1445
+ runId,
1446
+ SNAPSHOT_STORE_EXCLUSION.integrity_fault,
1447
+ );
1448
+ }
1449
+ } finally {
1450
+ closeDatabase(db);
1451
+ }
1452
+ }
1453
+
1454
+ /**
1455
+ * `VACUUM INTO` a private temp file, then compress that into
1456
+ * `archivePath`.
1457
+ *
1458
+ * `VACUUM INTO` rather than a file copy because the store runs in WAL
1459
+ * mode: the main file alone is not a consistent database, and the
1460
+ * runtime exposes no online-backup API. `VACUUM INTO` is read-only with
1461
+ * respect to the source, produces a single self-contained and compacted
1462
+ * file, and is the native answer to exactly this question.
1463
+ *
1464
+ * The temp file lives in the OS temp directory rather than beside the
1465
+ * store, so a crash between the vacuum and the compression leaves
1466
+ * nothing in the vault for the next reader to find.
1467
+ */
1468
+ function writeStoreArchive(
1469
+ sourcePath: string,
1470
+ archivePath: string,
1471
+ tools: ToolAvailability,
1472
+ runId: string,
1473
+ ): void {
1474
+ const tmp = mkdtempSync(join(tmpdir(), `o2b-store-vacuum-${runId}-`));
1475
+ const vacuumed = join(tmp, DERIVED_STORE_VACUUM_FILE);
1476
+ try {
1477
+ const db = new Database(sourcePath, { readonly: true });
1478
+ try {
1479
+ db.query("VACUUM INTO ?").run(vacuumed);
1480
+ } finally {
1481
+ closeDatabase(db);
1482
+ }
1483
+ compressInto({ kind: "file", path: vacuumed }, archivePath, tools, runId);
1484
+ } catch (err) {
1485
+ // Nothing to remove here: the compressor wrote a partial file that
1486
+ // `compressInto` discards, and the archive name is only ever created by
1487
+ // a successful publish. A failure on that name is a peer's archive,
1488
+ // which must survive the refusal.
1489
+ if (err instanceof BrainSnapshotError) throw err;
1490
+ throw new BrainSnapshotError(
1491
+ `failed to archive the derived store: ${(err as Error).message ?? String(err)}`,
1492
+ runId,
1493
+ );
1494
+ } finally {
1495
+ try {
1496
+ rmSync(tmp, { recursive: true, force: true });
1497
+ } catch {
1498
+ // tmp cleanup is best-effort; the OS will reclaim it eventually.
1499
+ }
1500
+ }
1501
+ }
1502
+
1503
+ /** Filename of the vacuumed copy inside its private temp directory. */
1504
+ const DERIVED_STORE_VACUUM_FILE = "store.sqlite";
1505
+
1506
+ /** Remove a store archive whose snapshot is being abandoned. */
1507
+ function discardStoreArchive(
1508
+ record: BrainManifestDerivedStore,
1509
+ vault: string,
1510
+ runId: string,
1511
+ ): void {
1512
+ if (!record.included) return;
1513
+ try {
1514
+ rmSync(snapshotStorePath(vault, runId), { force: true });
1515
+ } catch (err) {
1516
+ process.stderr.write(
1517
+ `warning: could not remove the orphaned derived-store archive for ` +
1518
+ `'${runId}': ${(err as Error).message ?? String(err)}\n`,
1519
+ );
1520
+ }
1521
+ }
1522
+
1523
+ /**
1524
+ * Compress the producer's stdout into `outPath`, choosing zstd when the
1525
+ * host has it and gzip otherwise.
1526
+ *
1527
+ * ## Both compressors refuse an existing target, and that is load-bearing
1528
+ *
1529
+ * `zstd -o` has always refused to overwrite. The gzip fallback wrote
1530
+ * through `writeFileSync`, which does not - so on a host without zstd
1531
+ * two concurrent destructive operations that landed on the same run id
1532
+ * would silently destroy each other's recovery point. That was not a
1533
+ * cosmetic asymmetry: `createUniqueSnapshot` in `snapshot-gate.ts`
1534
+ * resolves a run-id collision by RETRYING when the create fails and the
1535
+ * archive now exists, so on a gzip-only host the collision path had no
1536
+ * failure to retry on and the whole mechanism was inert.
1537
+ *
1538
+ * The refusal is therefore made explicit here, before either compressor
1539
+ * runs, so both paths fail with the same typed error and the same
1540
+ * message. Both compressors then write a partial file, and
1541
+ * {@link publishArchive} gives it the final name with an exclusive hard
1542
+ * link, which closes the window between the check and the publish that a
1543
+ * probe alone would leave open and means a killed compression never
1544
+ * leaves a truncated archive under a recovery point's name.
1545
+ *
1546
+ * The on-disk extension stays `.tar.zst` under gzip. The restore probes
1547
+ * the magic bytes rather than the name, and one suffix keeps listing and
1548
+ * retention a single comparison.
1549
+ */
1550
+ function compressInto(
1551
+ payload: CompressionSource,
1552
+ outPath: string,
1553
+ tools: ToolAvailability,
1554
+ runId: string,
1555
+ ): void {
1556
+ if (existsSync(outPath)) throw archiveCollision(outPath, runId);
1557
+ // The compressor writes a partial name beside the archive, and the
1558
+ // archive appears under its final name only once the compressor has
1559
+ // exited cleanly. A process killed part-way through compression (an
1560
+ // operator's kill, a host timeout, a power cut) used to leave a
1561
+ // truncated `<run_id>.tar.zst` with no manifest, which the listing,
1562
+ // retention and rollback all treat as a recovery point. A partial file
1563
+ // never ends in the archive suffix, so nothing lists it.
1564
+ const partial = `${outPath}${PARTIAL_ARCHIVE_INFIX}${process.pid}-${randomBytes(4).toString("hex")}`;
1565
+ try {
1566
+ if (tools.zstd) {
1567
+ runCompressor("zstd", ["-19", "-q", "-o", partial, payload.path], runId);
1568
+ } else {
1569
+ // No zstd: gzip in-process. `node:zlib` ships with every runtime this
1570
+ // tool supports, so a snapshot never depends on a `gzip` binary -
1571
+ // which native Windows does not have. Level 9 matches the `gzip -9`
1572
+ // this replaced, byte format included, so older readers restore it
1573
+ // unchanged.
1574
+ gzipFileExclusive(payload.path, partial, runId);
1575
+ }
1576
+ publishArchive(partial, outPath, runId);
1577
+ } finally {
1578
+ discardPartial(partial);
1579
+ }
1580
+ }
1581
+
1582
+ /**
1583
+ * Remove a partial archive this process wrote. Best-effort and never
1584
+ * throwing: it runs in a `finally`, where a throw would replace the real
1585
+ * outcome - turning a published archive into a failed snapshot, or hiding
1586
+ * the typed collision the run-id allocator ladders on. A partial left
1587
+ * behind is never listed, and {@link pruneSnapshots} removes stale ones.
1588
+ */
1589
+ function discardPartial(partial: string): void {
1590
+ try {
1591
+ unlinkWithRetry(partial);
1592
+ } catch (err) {
1593
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
1594
+ process.stderr.write(
1595
+ `warning: could not remove the partial snapshot archive ${partial}: ` +
1596
+ `${(err as Error).message ?? String(err)}\n`,
1597
+ );
1598
+ }
1599
+ }
1600
+
1601
+ /** Infix of a partial archive's name: `<archive>.partial-<pid>-<hex>`. */
1602
+ const PARTIAL_ARCHIVE_INFIX = ".partial-";
1603
+
1604
+ /**
1605
+ * A partial archive older than this is left over from a process that was
1606
+ * killed during compression. Generous against the longest compression a
1607
+ * live snapshot could still be running.
1608
+ */
1609
+ const STALE_PARTIAL_MS = 24 * 60 * 60 * 1000;
1610
+
1611
+ /**
1612
+ * Remove partial archives a killed snapshot left in `.snapshots/`. They are
1613
+ * this tool's own unfinished output, never a recovery point (nothing lists
1614
+ * them), and each can be as large as the whole Brain tar. Best-effort.
1615
+ */
1616
+ function removeStalePartials(snapshotsDirPath: string, now: number): void {
1617
+ let names: string[];
1618
+ try {
1619
+ names = readdirSync(snapshotsDirPath);
1620
+ } catch {
1621
+ return;
1622
+ }
1623
+ for (const name of names) {
1624
+ if (!name.includes(PARTIAL_ARCHIVE_INFIX)) continue;
1625
+ const full = join(snapshotsDirPath, name);
1626
+ try {
1627
+ const st = lstatSync(full);
1628
+ if (!st.isFile() || now - st.mtimeMs < STALE_PARTIAL_MS) continue;
1629
+ unlinkWithRetry(full);
1630
+ } catch {
1631
+ // gone already, or not ours to remove right now; the next prune retries
1632
+ }
1633
+ }
1634
+ }
1635
+
1636
+ /**
1637
+ * The typed "this name is taken" refusal. It carries an EEXIST-shaped
1638
+ * cause because the id allocator in `snapshot-gate.ts` ladders past a
1639
+ * taken name and needs to recognise this as the collision it is. Without
1640
+ * it the allocator sees an opaque snapshot failure, declines to retry, and
1641
+ * aborts the destructive operation the snapshot exists to protect.
1642
+ */
1643
+ function archiveCollision(outPath: string, runId: string): BrainSnapshotError {
1644
+ return new BrainSnapshotError(`refusing to overwrite an existing archive: ${outPath}`, runId, {
1645
+ cause: new FileAlreadyExistsError(outPath, { kind: "snapshot archive" }),
1646
+ });
1647
+ }
1648
+
1649
+ /**
1650
+ * errno values from the hard link that rule out the rename fallback too: the
1651
+ * partial file or the directory is gone, the volume is full or read-only.
1652
+ * Every other failure (a filesystem without hard links reports EPERM,
1653
+ * ENOTSUP, or on Windows FAT and exFAT an `ERROR_INVALID_FUNCTION` that
1654
+ * libuv maps to EISDIR) falls through to the checked rename.
1655
+ */
1656
+ const LINK_FATAL_CODES: ReadonlySet<string> = new Set(["ENOENT", "ENOSPC", "EROFS"]);
1657
+
1658
+ /**
1659
+ * Give the finished `partial` file its final archive name, refusing a name
1660
+ * that is already taken.
1661
+ *
1662
+ * A hard link is an exclusive create of the name with the content already
1663
+ * in place: it fails with EEXIST when a peer published first and never
1664
+ * replaces anything, on POSIX and on NTFS alike. `rename` would replace an
1665
+ * existing archive silently, so it is used only when the link fails for
1666
+ * another reason (typically a filesystem without hard links), behind an
1667
+ * existence check. That leaves a window between
1668
+ * the check and the rename on such a volume; the run id already carries
1669
+ * the second it was taken in, and the allocator probes the name first.
1670
+ * The partial file itself is removed by the caller.
1671
+ */
1672
+ function publishArchive(partial: string, outPath: string, runId: string): void {
1673
+ try {
1674
+ linkSync(partial, outPath);
1675
+ return;
1676
+ } catch (err) {
1677
+ const code = (err as NodeJS.ErrnoException).code ?? "";
1678
+ if (code === "EEXIST") throw archiveCollision(outPath, runId);
1679
+ if (LINK_FATAL_CODES.has(code)) {
1680
+ throw new BrainSnapshotError(
1681
+ `failed to publish ${outPath}: ${(err as Error).message ?? String(err)}`,
1682
+ runId,
1683
+ { cause: err },
1684
+ );
1685
+ }
1686
+ }
1687
+ if (existsSync(outPath)) throw archiveCollision(outPath, runId);
1688
+ try {
1689
+ renameWithRetry(partial, outPath);
1690
+ } catch (err) {
1691
+ throw new BrainSnapshotError(
1692
+ `failed to publish ${outPath}: ${(err as Error).message ?? String(err)}`,
1693
+ runId,
1694
+ { cause: err },
1695
+ );
1696
+ }
1697
+ }
1698
+
1699
+ /**
1700
+ * Input read per gzip member by {@link gzipFileExclusive}. Bounds the
1701
+ * memory the gzip fallback holds at once, whatever the archive's size.
1702
+ */
1703
+ const GZIP_MEMBER_INPUT_BYTES = 8 * 1024 * 1024;
1704
+
1705
+ /**
1706
+ * gzip `source` into `outPath` one bounded chunk at a time.
1707
+ *
1708
+ * `node:zlib` has no synchronous streaming API, and the snapshot path is
1709
+ * synchronous by contract (the destructive gate runs it inline before the
1710
+ * mutation it protects). So each chunk is compressed on its own and the
1711
+ * results are written back to back: a multi-member gzip file (RFC 1952,
1712
+ * section 2.2), which `gunzip`, `node:zlib` and every `tar -z` read as the
1713
+ * concatenation of the members. The restore path reads it unchanged.
1714
+ *
1715
+ * The destination is opened `wx`, so the exclusivity {@link compressInto}
1716
+ * relies on holds here exactly as it did for the single-buffer write. A
1717
+ * file this call created and could not finish is removed: it is ours, and
1718
+ * left behind it would read as a recovery point.
1719
+ */
1720
+ function gzipFileExclusive(source: string, outPath: string, runId: string): void {
1721
+ let out: number;
1722
+ try {
1723
+ out = openSync(outPath, "wx");
1724
+ } catch (err) {
1725
+ throw new BrainSnapshotError(
1726
+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,
1727
+ runId,
1728
+ { cause: err },
1729
+ );
1730
+ }
1731
+ let finished = false;
1732
+ try {
1733
+ const input = openSync(source, "r");
1734
+ try {
1735
+ const chunk = Buffer.allocUnsafe(GZIP_MEMBER_INPUT_BYTES);
1736
+ let wroteMember = false;
1737
+ for (;;) {
1738
+ const read = readSync(input, chunk, 0, chunk.length, null);
1739
+ if (read === 0) break;
1740
+ writeFully(out, gzipSync(chunk.subarray(0, read), { level: 9 }));
1741
+ wroteMember = true;
1742
+ }
1743
+ // An empty source still produces a valid (one-member) gzip file.
1744
+ if (!wroteMember) writeFully(out, gzipSync(Buffer.alloc(0), { level: 9 }));
1745
+ } finally {
1746
+ closeSync(input);
1747
+ }
1748
+ finished = true;
1749
+ } catch (err) {
1750
+ throw new BrainSnapshotError(
1751
+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,
1752
+ runId,
1753
+ { cause: err },
1754
+ );
1755
+ } finally {
1756
+ closeSync(out);
1757
+ if (!finished) rmSync(outPath, { force: true });
1758
+ }
1759
+ }
1760
+
1761
+ /** `writeSync` until every byte of `bytes` is on `fd`. */
1762
+ function writeFully(fd: number, bytes: Buffer): void {
1763
+ let offset = 0;
1764
+ while (offset < bytes.length) {
1765
+ offset += writeSync(fd, bytes, offset, bytes.length - offset);
1766
+ }
1767
+ }
1768
+
1769
+ /**
1770
+ * Exclusive create of a decompressed payload. `wx` refuses an existing
1771
+ * destination the way `zstd -o` does, so neither decompressor can replace
1772
+ * a file it did not create.
1773
+ */
1774
+ function writeArchiveExclusive(outPath: string, bytes: Buffer, runId: string): void {
1775
+ try {
1776
+ writeFileSync(outPath, bytes, { flag: "wx" });
1777
+ } catch (err) {
1778
+ throw new BrainSnapshotError(
1779
+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,
1780
+ runId,
1781
+ { cause: err },
1782
+ );
1783
+ }
1784
+ }
1785
+
1786
+ /**
1787
+ * What a compressor reads: a file, handed over by path - the staged tar
1788
+ * stream or the vacuumed store copy - so a multi-hundred-megabyte payload
1789
+ * never round-trips through memory.
1790
+ */
1791
+ type CompressionSource = { readonly kind: "file"; readonly path: string };
1792
+
1793
+ /**
1794
+ * Hard ceiling on any single CAPTURED subprocess stream. Only diagnostic
1795
+ * output (stderr) is captured on the archive path; archive bytes go
1796
+ * through files, so this never bounds the size of a snapshot.
1797
+ */
1798
+ const SUBPROCESS_MAX_BUFFER_BYTES = 256 * 1024 * 1024;
1799
+
1800
+ /** Environment variable that overrides {@link SNAPSHOT_TOOL_TIMEOUT_MS}. */
1801
+ export const SNAPSHOT_TOOL_TIMEOUT_ENV = "OPEN_SECOND_BRAIN_SNAPSHOT_TIMEOUT_MS";
1802
+
1803
+ /**
1804
+ * How long one `tar` or `zstd` run of a snapshot or a restore may take
1805
+ * before it is killed and the snapshot fails.
1806
+ *
1807
+ * The whole module is synchronous by contract, so a child that never
1808
+ * exits used to block the calling process forever: nothing else in the
1809
+ * process can run, not even a timer that would notice. Fifteen minutes is
1810
+ * far above what `zstd -19` needs for a `Brain/` tree of a few hundred
1811
+ * megabytes, and finite, so a wedged tool turns into a named failure
1812
+ * instead of a frozen hook, CLI or MCP call.
1813
+ */
1814
+ export const SNAPSHOT_TOOL_TIMEOUT_MS = 15 * 60 * 1000;
1815
+
1816
+ /**
1817
+ * The tool timeout in force: {@link SNAPSHOT_TOOL_TIMEOUT_ENV} when it is a
1818
+ * whole number of milliseconds above zero, {@link SNAPSHOT_TOOL_TIMEOUT_MS}
1819
+ * when it is unset or empty. Any other value is an error rather than a
1820
+ * silent fallback, so a typo cannot quietly change the bound.
1821
+ */
1822
+ export function resolveSnapshotToolTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {
1823
+ const raw = env[SNAPSHOT_TOOL_TIMEOUT_ENV];
1824
+ if (raw === undefined || raw.trim() === "") return SNAPSHOT_TOOL_TIMEOUT_MS;
1825
+ const text = raw.trim();
1826
+ const parsed = /^\d+$/.test(text) ? Number(text) : Number.NaN;
1827
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
1828
+ throw new Error(
1829
+ `${SNAPSHOT_TOOL_TIMEOUT_ENV}=${raw} is not a timeout; set it to a whole number of ` +
1830
+ `milliseconds > 0 (the default is ${SNAPSHOT_TOOL_TIMEOUT_MS}), or unset it`,
1831
+ );
1832
+ }
1833
+ return parsed;
1834
+ }
1835
+
1836
+ /**
1837
+ * The ceiling on the INFLATED size of a snapshot archive, in bytes.
1838
+ *
1839
+ * The gzip branch of a restore inflates in process, because native Windows
1840
+ * has no `gzip` binary, and the inflated bytes are held in memory: the
1841
+ * tar stream of `Brain/` (or the archived derived store) comes back as one
1842
+ * buffer. Without a ceiling an archive that inflates far past the tree it
1843
+ * claims to hold takes the process down with it, so the restore refuses one
1844
+ * by name instead.
1845
+ *
1846
+ * The default is half a gigabyte: twice the ceiling this tool's own
1847
+ * defaults put on the largest artifact it archives (the derived store,
1848
+ * `snapshots.derived_store_max_bytes`, 256 MiB by default) and far above
1849
+ * the Markdown tree of any vault this tool was built for. A vault past it
1850
+ * raises the bound - see {@link SNAPSHOT_MAX_INFLATED_BYTES_ENV}.
1851
+ */
1852
+ export const MAX_INFLATED_ARCHIVE_BYTES = 512 * 1024 * 1024;
1853
+
1854
+ /** Environment variable that overrides {@link MAX_INFLATED_ARCHIVE_BYTES}. */
1855
+ export const SNAPSHOT_MAX_INFLATED_BYTES_ENV = "OPEN_SECOND_BRAIN_SNAPSHOT_MAX_INFLATED_BYTES";
1856
+
1857
+ /**
1858
+ * The inflate ceiling in force: {@link SNAPSHOT_MAX_INFLATED_BYTES_ENV} when
1859
+ * it is a whole number of bytes above zero, {@link MAX_INFLATED_ARCHIVE_BYTES}
1860
+ * when it is unset or empty. Any other value is an error rather than a
1861
+ * silent fallback, so a typo cannot quietly change the bound.
1862
+ */
1863
+ export function resolveMaxInflatedBytes(env: NodeJS.ProcessEnv = process.env): number {
1864
+ const raw = env[SNAPSHOT_MAX_INFLATED_BYTES_ENV];
1865
+ if (raw === undefined || raw.trim() === "") return MAX_INFLATED_ARCHIVE_BYTES;
1866
+ const text = raw.trim();
1867
+ const parsed = /^\d+$/.test(text) ? Number(text) : Number.NaN;
1868
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
1869
+ throw new Error(
1870
+ `${SNAPSHOT_MAX_INFLATED_BYTES_ENV}=${raw} is not a byte count; set it to a whole number of ` +
1871
+ `bytes > 0 (the default is ${MAX_INFLATED_ARCHIVE_BYTES}), or unset it`,
1872
+ );
1873
+ }
1874
+ return parsed;
1875
+ }
1876
+
1877
+ /**
1878
+ * `spawnSync` with the snapshot tool timeout. A run that hits it is killed
1879
+ * (SIGKILL: a tool that ignored its input closing will not honour a polite
1880
+ * signal either) and reported as a {@link BrainSnapshotError} that names
1881
+ * the tool and the bound. Every other outcome is returned unchanged for
1882
+ * the caller's own status handling.
1883
+ */
1884
+ function spawnSnapshotTool(
1885
+ cmd: string,
1886
+ args: ReadonlyArray<string>,
1887
+ options: SpawnSyncOptions,
1888
+ runId: string,
1889
+ ): SpawnSyncReturns<Buffer> {
1890
+ const timeoutMs = resolveSnapshotToolTimeoutMs();
1891
+ // A writer lock held across this run (the restore's, a store archive's)
1892
+ // is kept fresh while the thread is blocked in the child, bounded by the
1893
+ // timeout the child is killed at plus one stale window for the kill.
1894
+ const r = keepWriterLeasesFresh(
1895
+ timeoutMs + resolveWriterLockStaleMs(),
1896
+ () =>
1897
+ spawnSync(cmd, [...args], {
1898
+ ...options,
1899
+ timeout: timeoutMs,
1900
+ killSignal: "SIGKILL",
1901
+ }) as SpawnSyncReturns<Buffer>,
1902
+ );
1903
+ if ((r.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT") {
1904
+ throw new BrainSnapshotError(
1905
+ `${cmd} did not finish within ${timeoutMs} ms and was stopped; ` +
1906
+ `no archive was published (raise ${SNAPSHOT_TOOL_TIMEOUT_ENV} for a very large tree)`,
1907
+ runId,
1908
+ { cause: r.error },
1909
+ );
1910
+ }
1911
+ return r;
1912
+ }
1913
+
1914
+ /**
1915
+ * Run one compressor that writes the destination named after its `-o`
1916
+ * itself, so only its stderr is captured. Every destination handed to it
1917
+ * is a name this process owns: a partial file with a random suffix, or a
1918
+ * file in a private temp directory. A collision on the published archive
1919
+ * name is detected by {@link publishArchive}, not here.
1920
+ */
1921
+ function runCompressor(cmd: string, args: ReadonlyArray<string>, runId: string): void {
1922
+ const r = spawnSnapshotTool(
1923
+ cmd,
1924
+ args,
1925
+ { stdio: ["ignore", "ignore", "pipe"], maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES },
1926
+ runId,
1927
+ );
1928
+ if (r.error) {
1929
+ throw new BrainSnapshotError(`${cmd} failed to start: ${r.error.message}`, runId);
1930
+ }
1931
+ if (r.status !== 0) {
1932
+ const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();
1933
+ throw new BrainSnapshotError(`${cmd} exited with status ${r.status}: ${stderr}`, runId);
1934
+ }
1935
+ }
1936
+
1937
+ /**
1938
+ * Run the archive producer with its stdout on `outFile`.
1939
+ *
1940
+ * No shell pipe (the old `sh -c "tar ... | zstd ..."` broke on quoting of
1941
+ * paths with whitespace, and native Windows has no `sh`), and no captured
1942
+ * pipe either: tar's stdout is a file descriptor opened here, so the
1943
+ * stream goes straight to disk. It used to be captured through
1944
+ * `spawnSync` with a 256 MB `maxBuffer`, which a `Brain/` tree past that
1945
+ * size overran with `ENOBUFS` after tar had already done all of its work.
1946
+ * Only stderr is captured, for the error message.
1947
+ *
1948
+ * `outFile` is opened `wx`: it lives in a private temp directory, so an
1949
+ * existing file there is a bug to surface rather than a file to reuse.
1950
+ *
1951
+ * Argument quoting: we deliberately do NOT shell-escape paths, because
1952
+ * `tar -C <vault>` already roots everything relative to the vault, and
1953
+ * the only user-supplied bytes in `tarArgs` are the run id (which
1954
+ * `validateRunId` constrains to `[A-Za-z0-9._-]`) and the member list,
1955
+ * which travels through a file.
1956
+ */
1957
+ function runArchiveProducer(
1958
+ cmd: string,
1959
+ args: ReadonlyArray<string>,
1960
+ outFile: string,
1961
+ runId: string,
1962
+ env?: NodeJS.ProcessEnv,
1963
+ ): void {
1964
+ const fd = openSync(outFile, "wx");
1965
+ let r: SpawnSyncReturns<Buffer>;
1966
+ try {
1967
+ r = spawnSnapshotTool(
1968
+ cmd,
1969
+ args,
1970
+ {
1971
+ maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES,
1972
+ stdio: ["ignore", fd, "pipe"],
1973
+ ...(env ? { env } : {}),
1974
+ },
1975
+ runId,
1976
+ );
1977
+ } finally {
1978
+ closeSync(fd);
1979
+ }
1980
+ if (r.error) {
1981
+ throw new BrainSnapshotError(`${cmd} failed to start: ${r.error.message}`, runId);
1982
+ }
1983
+ if (r.status !== 0) {
1984
+ const stderr = Buffer.from(r.stderr ?? "")
1985
+ .toString("utf8")
1986
+ .trim();
1987
+ throw new BrainSnapshotError(`${cmd} exited with status ${r.status}: ${stderr}`, runId);
1988
+ }
1989
+ if (statSync(outFile).size === 0) {
1990
+ throw new BrainSnapshotError(`${cmd} produced no stdout`, runId);
1991
+ }
1992
+ }
1993
+
1994
+ // ----- listSnapshots / pruneSnapshots --------------------------------------
1995
+
1996
+ /**
1997
+ * Enumerate `.snapshots/*.tar.zst` in newest-first order (by the
1998
+ * manifest's recorded creation time, see {@link SnapshotInfo.created_at}),
1999
+ * alongside the archive-shaped entries that could not be described.
2000
+ *
2001
+ * Files outside the canonical naming pattern are skipped and NOT reported:
2002
+ * a sidecar manifest, a store archive or a stray text file is not a
2003
+ * recovery point, so naming it would be noise.
2004
+ *
2005
+ * The three answers this returns are three different facts:
2006
+ *
2007
+ * - a directory that is not there is an empty history: no snapshot has
2008
+ * ever been taken, and both fields are empty.
2009
+ * - a directory that IS there and cannot be enumerated throws
2010
+ * {@link BrainSnapshotListingError}, because `[]` for that too is what
2011
+ * let the listing surfaces print "no snapshots available" over a read
2012
+ * that never happened.
2013
+ * - an archive that is named in the directory and cannot be turned into
2014
+ * a row - an unvalidatable run id, or a `stat` that failed - lands in
2015
+ * {@link SnapshotListing.skipped}. It used to be dropped with a bare
2016
+ * `continue`, which put a populated history nobody could stat and a
2017
+ * vault that never took one on the same wire; the caller decides what
2018
+ * to say about it, but it can no longer fail to know.
2019
+ */
2020
+ export function listSnapshots(vault: string): SnapshotListing {
2021
+ vault = machineStateRoot(vault);
2022
+ const dirs = brainDirs(vault);
2023
+ if (!existsSync(dirs.snapshots)) return { snapshots: [], skipped: [] };
2024
+ let entries: string[];
2025
+ try {
2026
+ entries = readdirSync(dirs.snapshots);
2027
+ } catch (err) {
2028
+ throw new BrainSnapshotListingError(dirs.snapshots, err);
2029
+ }
2030
+ const infos: SnapshotInfo[] = [];
2031
+ // Archive mtimes, kept beside the rows only to break a creation-time
2032
+ // tie: the manifest records whole seconds, so two archives taken in
2033
+ // the same second compare equal on `created_at`.
2034
+ const mtimes = new Map<string, number>();
2035
+ const skipped: SnapshotEntrySkip[] = [];
2036
+ const nowMs = Date.now();
2037
+ for (const name of entries) {
2038
+ if (!name.endsWith(SNAPSHOT_ARCHIVE_SUFFIX)) continue;
2039
+ const runId = name.slice(0, -SNAPSHOT_ARCHIVE_SUFFIX.length);
2040
+ const full = join(dirs.snapshots, name);
2041
+ // The `.snapshots/` dir is ours, so a malformed run_id here indicates
2042
+ // manual tampering — the listing stays tolerant and keeps describing
2043
+ // the archives it can, but the entry is carried out rather than
2044
+ // dropped: an operator hunting a recovery point they know they took
2045
+ // needs to be told the file is there under a name this build will not
2046
+ // accept.
2047
+ try {
2048
+ validateRunId(runId);
2049
+ } catch (err) {
2050
+ skipped.push({
2051
+ name,
2052
+ path: full,
2053
+ reason: SNAPSHOT_ENTRY_SKIP_REASON.runIdUnparseable,
2054
+ detail: err instanceof Error ? err.message : String(err),
2055
+ });
2056
+ continue;
2057
+ }
2058
+ let st;
2059
+ try {
2060
+ st = statSync(full);
2061
+ } catch (err) {
2062
+ skipped.push({
2063
+ name,
2064
+ path: full,
2065
+ reason: SNAPSHOT_ENTRY_SKIP_REASON.entryUnreadable,
2066
+ detail: err instanceof Error ? err.message : String(err),
2067
+ });
2068
+ continue;
2069
+ }
2070
+ const sidecar = manifestSidecarPath(vault, runId);
2071
+ const storeArchive = snapshotStorePath(vault, runId);
2072
+ // One read for both sidecar-derived columns: two calls would parse
2073
+ // the same file twice and could disagree if a peer rewrote it between
2074
+ // them.
2075
+ const manifest = readManifestSidecar(vault, runId);
2076
+ mtimes.set(runId, st.mtimeMs);
2077
+ const created = snapshotCreatedAt(manifest?.generated_at, st.mtimeMs, runId, nowMs);
2078
+ infos.push({
2079
+ run_id: runId,
2080
+ path: full,
2081
+ created_at: created.at,
2082
+ ...(created.untrusted !== null ? { created_at_untrusted: created.untrusted } : {}),
2083
+ size_bytes: st.size,
2084
+ manifest_path: existsSync(sidecar) ? sidecar : null,
2085
+ store_archive_path: existsSync(storeArchive) ? storeArchive : null,
2086
+ // `?? null` collapses "no sidecar", "unreadable sidecar" and
2087
+ // "sidecar predating the feature" into one answer, which is
2088
+ // correct: all three mean the coverage is UNKNOWN, and none of
2089
+ // them is evidence that the store was excluded.
2090
+ derived_store: manifest?.derived_store ?? null,
2091
+ // Same three states, same single answer, and the same refusal to
2092
+ // improve on it: the run id is not evidence of a reason.
2093
+ reason: manifest?.snapshot_reason ?? null,
2094
+ });
2095
+ }
2096
+ // Sort newest-first by recorded creation time, then by mtime within
2097
+ // the same second, then by run id so the order is total. We avoid a
2098
+ // lexicographic run_id sort as the primary key because manual rollback
2099
+ // runs might use a non-timestamped id and we still want them to land
2100
+ // where the operator's mental model expects (most recent first).
2101
+ infos.sort(
2102
+ (a, b) =>
2103
+ Date.parse(b.created_at) - Date.parse(a.created_at) ||
2104
+ (mtimes.get(b.run_id) ?? 0) - (mtimes.get(a.run_id) ?? 0) ||
2105
+ (a.run_id < b.run_id ? 1 : a.run_id > b.run_id ? -1 : 0),
2106
+ );
2107
+ return { snapshots: infos, skipped };
2108
+ }
2109
+
2110
+ /** How far ahead of now a sidecar stamp may be before it reads as a broken clock or an edit. */
2111
+ const SNAPSHOT_STAMP_FUTURE_SKEW_MS = 5 * 60 * 1000;
2112
+
2113
+ /** Slack below the run id's time: both are whole seconds, and the sidecar is written after. */
2114
+ const SNAPSHOT_STAMP_RUN_ID_SLACK_MS = 1000;
2115
+
2116
+ /**
2117
+ * The UTC time a run id carries (`<reason>-YYYY-MM-DD-HHMMSS`, with an
2118
+ * optional `-<n>` collision suffix), or `null` for an id without one.
2119
+ */
2120
+ function runIdStampMs(runId: string): number | null {
2121
+ const m = /-(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})(\d{2})(?:-\d+)?$/.exec(runId);
2122
+ if (m === null) return null;
2123
+ const [year, month, day, hour, minute, second] = m.slice(1).map(Number) as [
2124
+ number,
2125
+ number,
2126
+ number,
2127
+ number,
2128
+ number,
2129
+ number,
2130
+ ];
2131
+ const ms = Date.UTC(year, month - 1, day, hour, minute, second);
2132
+ return Number.isFinite(ms) ? ms : null;
2133
+ }
2134
+
2135
+ /**
2136
+ * The creation time retention orders by: the manifest's `generated_at`
2137
+ * when it parses as a date and is believable, else the archive's mtime.
2138
+ * An unparseable stamp falls back rather than sorting as `NaN`, which
2139
+ * would make the comparator inconsistent and the prune order undefined.
2140
+ * A stamp later than now (beyond a small skew) or earlier than the run
2141
+ * id's own time falls back too, and the reason is returned so the
2142
+ * listing can report it.
2143
+ */
2144
+ function snapshotCreatedAt(
2145
+ generatedAt: string | undefined,
2146
+ mtimeMs: number,
2147
+ runId: string,
2148
+ nowMs: number,
2149
+ ): { readonly at: string; readonly untrusted: string | null } {
2150
+ let untrusted: string | null = null;
2151
+ if (generatedAt !== undefined) {
2152
+ const ms = Date.parse(generatedAt);
2153
+ if (Number.isFinite(ms)) {
2154
+ const runMs = runIdStampMs(runId);
2155
+ // Quoted as JSON: the stamp is printed, and a parseable one can still
2156
+ // carry a newline or a terminal escape inside a `(...)` comment. JSON
2157
+ // leaves DEL and the C1 controls (U+009B is a one-character CSI) as
2158
+ // they are, so those are escaped too.
2159
+ const shown = JSON.stringify(generatedAt).replace(
2160
+ /[\u007f-\u009f]/g,
2161
+ (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,
2162
+ );
2163
+ if (ms > nowMs + SNAPSHOT_STAMP_FUTURE_SKEW_MS) {
2164
+ untrusted = `the manifest's generated_at ${shown} is later than now`;
2165
+ } else if (runMs !== null && ms < runMs - SNAPSHOT_STAMP_RUN_ID_SLACK_MS) {
2166
+ untrusted =
2167
+ `the manifest's generated_at ${shown} is earlier than the run id's own time ` +
2168
+ new Date(runMs).toISOString();
2169
+ } else {
2170
+ return { at: new Date(ms).toISOString(), untrusted: null };
2171
+ }
2172
+ }
2173
+ }
2174
+ return { at: new Date(mtimeMs).toISOString(), untrusted };
2175
+ }
2176
+
2177
+ /**
2178
+ * Delete all but the `retention_count` newest archives. Returns what it
2179
+ * removed, what resisted removal, how many archives survive, and - when
2180
+ * it declined to run at all - why. Idempotent: a second run on the same
2181
+ * directory removes nothing.
2182
+ *
2183
+ * This is the most destructive operation in the module, and it cannot be
2184
+ * gated on taking a recovery point: gating the thing that destroys
2185
+ * recovery points on making one is circular. It gets a floor and a named
2186
+ * refusal instead. Below {@link SNAPSHOT_RETENTION_FLOOR} nothing is
2187
+ * removed and the refusal travels back, because a configured retention of
2188
+ * zero asks this function to leave a vault with no way back, and it used
2189
+ * to comply on every snapshot and every dream without saying a word.
2190
+ *
2191
+ * A removal that fails is REPORTED rather than swallowed. It used to be
2192
+ * silently skipped, so a permission problem stopped retention working and
2193
+ * every prune still read as clean. A failure also STOPS the companion
2194
+ * removal for that archive: the sidecar manifest and the store archive go
2195
+ * only on the branch where the archive itself went, because an archive
2196
+ * left on disk without its manifest is worse than either - rollback
2197
+ * against it skips drift detection and silently never restores its
2198
+ * derived store.
2199
+ *
2200
+ * {@link PruneSnapshotsOptions.protectRunIds} is how a caller keeps the
2201
+ * archive it is standing on. See that field for why the ordering alone
2202
+ * was never enough.
2203
+ */
2204
+ export function pruneSnapshots(
2205
+ vault: string,
2206
+ retentionCount: number,
2207
+ opts: PruneSnapshotsOptions = {},
2208
+ ): PruneSnapshotsResult {
2209
+ vault = machineStateRoot(vault);
2210
+ // Vault-identity write guard (context-integrity-gates, Unit J). This is
2211
+ // the most destructive operation in the module - an `rmSync` over
2212
+ // archives - and it was the only one of the three without the guard
2213
+ // its `createSnapshot` and `restoreSnapshot` siblings carry.
2214
+ assertVaultIdentityForWrite(vault, undefined, opts.lane);
2215
+ if (!Number.isInteger(retentionCount)) {
2216
+ throw new Error(`pruneSnapshots: retentionCount must be an integer; got ${retentionCount}`);
2217
+ }
2218
+ removeStalePartials(brainDirs(vault).snapshots, Date.now());
2219
+ if (retentionCount < SNAPSHOT_RETENTION_FLOOR) {
2220
+ // Refused, not obeyed, and not thrown: see the docblock.
2221
+ return Object.freeze({
2222
+ deleted: Object.freeze([]),
2223
+ failed: Object.freeze([]),
2224
+ retained: listSnapshots(vault).snapshots.length,
2225
+ refusal: SNAPSHOT_PRUNE_REFUSAL.belowRetentionFloor,
2226
+ });
2227
+ }
2228
+ const all = listSnapshots(vault).snapshots;
2229
+ if (all.length <= retentionCount) {
2230
+ return Object.freeze({
2231
+ deleted: Object.freeze([]),
2232
+ failed: Object.freeze([]),
2233
+ retained: all.length,
2234
+ refusal: null,
2235
+ });
2236
+ }
2237
+ const protectedIds = new Set(opts.protectRunIds ?? []);
2238
+ // Protected archives are moved to the FRONT of the retention order and
2239
+ // then filtered out of the victim list a second time. Two mechanisms
2240
+ // for one guarantee, because they answer different failures: the
2241
+ // reordering keeps the retained count at exactly `retentionCount` in
2242
+ // the normal case, and the filter is what holds when a caller protects
2243
+ // more archives than the retention allows.
2244
+ const ordered = [
2245
+ ...all.filter((s) => protectedIds.has(s.run_id)),
2246
+ ...all.filter((s) => !protectedIds.has(s.run_id)),
2247
+ ];
2248
+ const victims = ordered.slice(retentionCount).filter((s) => !protectedIds.has(s.run_id));
2249
+ const deleted: string[] = [];
2250
+ const failed: string[] = [];
2251
+ for (const v of victims) {
2252
+ try {
2253
+ rmSync(v.path, { force: true });
2254
+ } catch {
2255
+ // The archive stays put and the caller is told which one, so a
2256
+ // recurring permission problem is visible instead of being
2257
+ // rediscovered when retention has quietly stopped working. The
2258
+ // companions below are deliberately NOT reached: an archive
2259
+ // without its manifest is an archive a rollback misreads.
2260
+ failed.push(v.path);
2261
+ continue;
2262
+ }
2263
+ deleted.push(v.path);
2264
+ // Remove the matching sidecar manifest and derived-store archive if
2265
+ // present. Independent try/catch per companion so a missing one (a
2266
+ // snapshot whose sidecar write failed at creation time, or one taken
2267
+ // without store coverage) must not abort the prune of subsequent
2268
+ // victims.
2269
+ for (const companion of [v.manifest_path, v.store_archive_path]) {
2270
+ if (companion === null) continue;
2271
+ try {
2272
+ rmSync(companion, { force: true });
2273
+ } catch {
2274
+ // Same rationale as above — best-effort.
2275
+ }
2276
+ }
2277
+ }
2278
+ return Object.freeze({
2279
+ deleted: Object.freeze(deleted),
2280
+ failed: Object.freeze(failed),
2281
+ retained: all.length - deleted.length,
2282
+ refusal: null,
2283
+ });
2284
+ }
2285
+
2286
+ // ----- restoreSnapshot -----------------------------------------------------
2287
+
2288
+ /**
2289
+ * Result of {@link extractSnapshotToTemp}. `brainRoot` is the
2290
+ * extracted `Brain/` directory (sibling to the live tree, inside a
2291
+ * private tmp dir); `tmpRoot` is the parent directory the caller
2292
+ * owns. {@link cleanup} removes the tmp dir best-effort.
2293
+ */
2294
+ export interface ExtractSnapshotResult {
2295
+ readonly tmpRoot: string;
2296
+ readonly brainRoot: string;
2297
+ readonly cleanup: () => void;
2298
+ }
2299
+
2300
+ /**
2301
+ * Extract a snapshot archive into a private tmp directory and return
2302
+ * pointers to the materialised tree. The caller is responsible for
2303
+ * invoking {@link ExtractSnapshotResult.cleanup} once the data is no
2304
+ * longer needed.
2305
+ *
2306
+ * Used by:
2307
+ * - {@link restoreSnapshot} — actually replaces the live tree.
2308
+ * - `o2b brain rollback --dry-run` — previews the restore plan.
2309
+ * - `o2b brain snapshot diff` — read-only inspector across two
2310
+ * snapshots or a snapshot and the live tree.
2311
+ *
2312
+ * Shared so the tar / zstd / gzip decompression logic stays in one
2313
+ * place. Throws {@link BrainSnapshotError} on archive corruption /
2314
+ * missing root, {@link BrainSnapshotToolingMissingError} when the
2315
+ * host lacks the required external tool.
2316
+ */
2317
+ export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnapshotResult {
2318
+ vault = machineStateRoot(vault);
2319
+ validateRunId(runId);
2320
+ const archive = snapshotPath(vault, runId);
2321
+ assertRegularFile(archive, runId, "archive");
2322
+ const tools = detectTooling();
2323
+
2324
+ const tmp = mkdtempSync(join(tmpdir(), `o2b-brain-extract-${runId}-`));
2325
+ const cleanup = (): void => {
2326
+ try {
2327
+ rmSync(tmp, { recursive: true, force: true });
2328
+ } catch {
2329
+ // tmp cleanup is best-effort; the OS will reclaim it eventually.
2330
+ }
2331
+ };
2332
+ try {
2333
+ // Probe the magic bytes to decide how to decompress. zstd starts
2334
+ // with `28 B5 2F FD`; gzip with `1F 8B`. Anything else is rejected
2335
+ // — we don't blindly try every decompressor.
2336
+ const decompressor = detectArchiveCompression(archive);
2337
+ if (decompressor === "zstd" && !tools.zstd) {
2338
+ throw new BrainSnapshotToolingMissingError(
2339
+ "zstd",
2340
+ "archive is zstd-compressed; install zstd to restore it.",
2341
+ );
2342
+ }
2343
+
2344
+ if (decompressor === "zstd") {
2345
+ // Decompressed to a staging file OUTSIDE the extraction root and read
2346
+ // from it in place: neither stream is held in memory, so an archive
2347
+ // whose tar stream is larger than any buffer restores as well as a
2348
+ // small one.
2349
+ const staging = mkdtempSync(join(tmpdir(), `o2b-brain-extract-tar-${runId}-`));
2350
+ try {
2351
+ const tarball = join(staging, "brain.tar");
2352
+ runCompressor("zstd", ["-d", "-q", "-o", tarball, archive], runId);
2353
+ const fd = openSync(tarball, "r");
2354
+ try {
2355
+ extractTarStream(
2356
+ (offset, length) => {
2357
+ const buf = Buffer.alloc(length);
2358
+ return buf.subarray(0, readSync(fd, buf, 0, length, offset));
2359
+ },
2360
+ tmp,
2361
+ runId,
2362
+ );
2363
+ } finally {
2364
+ closeSync(fd);
2365
+ }
2366
+ } finally {
2367
+ rmSync(staging, { recursive: true, force: true });
2368
+ }
2369
+ } else {
2370
+ // gzip is inflated in-process, like the tar stream is read in
2371
+ // process: no `gzip` binary needed (native Windows has none).
2372
+ // The inflate is bounded: the bytes it produces are held in memory.
2373
+ const tarball = inflateGzipArchive(archive, runId);
2374
+ extractTarStream((offset, length) => tarball.subarray(offset, offset + length), tmp, runId);
2375
+ }
2376
+
2377
+ const extractedBrain = join(tmp, BRAIN_ROOT_REL);
2378
+ if (lstatSync(extractedBrain, { throwIfNoEntry: false }) === undefined) {
2379
+ throw new BrainSnapshotError(`archive does not contain a ${BRAIN_ROOT_REL}/ root`, runId);
2380
+ }
2381
+ // The root itself is judged, not only what is inside it: an archive
2382
+ // whose `Brain/` member is a link is refused here, before anything
2383
+ // reads through it.
2384
+ refuseEscapingSymlinks(extractedBrain, runId);
2385
+ return Object.freeze({ tmpRoot: tmp, brainRoot: extractedBrain, cleanup });
2386
+ } catch (err) {
2387
+ cleanup();
2388
+ throw err;
2389
+ }
2390
+ }
2391
+
2392
+ /**
2393
+ * Extract the tar stream `read` gives into the empty folder `dir`, in
2394
+ * process (`tar-extract.ts`), after {@link refuseIndistinctMembers}. No
2395
+ * system tar is run: Windows `tar.exe` turned every UTF-8 name into the
2396
+ * ANSI code page and refused a name in Cyrillic, CJK or any script that
2397
+ * code page lacks ("Archive entry has empty or unreadable filename"), so a
2398
+ * snapshot of such a tree could be taken and never restored; macOS bsdtar
2399
+ * renamed every NFC name to NFD. Every name now comes back as the archive
2400
+ * stores it, on every platform. The thread blocks for the whole stream, so
2401
+ * a writer lock the caller holds (the gated restore's) is kept fresh
2402
+ * meanwhile, bounded like the tar run this replaces.
2403
+ */
2404
+ function extractTarStream(read: TarRead, dir: string, runId: string): void {
2405
+ refuseIndistinctMembers(read, dir, runId);
2406
+ keepLeasesFreshInProcess(() => {
2407
+ try {
2408
+ extractTarArchive(read, dir);
2409
+ } catch (err) {
2410
+ throw new BrainSnapshotError(
2411
+ `archive extract failed: ${(err as Error).message ?? String(err)}`,
2412
+ runId,
2413
+ { cause: err },
2414
+ );
2415
+ }
2416
+ });
2417
+ }
2418
+
2419
+ /**
2420
+ * Run in-process archive work (writing or reading a tar stream), which
2421
+ * blocks this thread and has no timeout of its own, with every writer lock
2422
+ * this process holds kept fresh for as long as a tar run doing the same
2423
+ * work could take ({@link resolveSnapshotToolTimeoutMs}, which an operator
2424
+ * raises for a very large tree) plus one stale window.
2425
+ */
2426
+ function keepLeasesFreshInProcess<T>(fn: () => T): T {
2427
+ return keepWriterLeasesFresh(resolveSnapshotToolTimeoutMs() + resolveWriterLockStaleMs(), fn);
2428
+ }
2429
+
2430
+ /**
2431
+ * Refuse, before anything is written, an archive with two members that
2432
+ * would land on one path of the extraction folder `dir`. APFS looks names
2433
+ * up without regard to normalization, so an NFC name and its NFD twin
2434
+ * ("café" typed on two machines) are one file there; APFS and NTFS look
2435
+ * names up without regard to case, so `Note.md` and `note.md` are too.
2436
+ * The second member would replace the first and a restore would lose the
2437
+ * other record; refused instead, naming both.
2438
+ * How this folder treats names is probed on the folder itself, so a
2439
+ * case-sensitive volume or a Linux filesystem that keeps both forms apart
2440
+ * restores both. Two directories that fold together merge, which loses
2441
+ * nothing: the files inside them are checked by their full paths.
2442
+ */
2443
+ function refuseIndistinctMembers(
2444
+ read: (offset: number, length: number) => Buffer,
2445
+ dir: string,
2446
+ runId: string,
2447
+ ): void {
2448
+ let members: TarMemberName[];
2449
+ try {
2450
+ members = readTarMemberNames(read);
2451
+ } catch (err) {
2452
+ throw new BrainSnapshotError(
2453
+ `the archive cannot be read: ${(err as Error).message ?? String(err)}`,
2454
+ runId,
2455
+ { cause: err },
2456
+ );
2457
+ }
2458
+ const folding = nameFolding(dir);
2459
+ if (!folding.normalization && !folding.caseFold) return;
2460
+ const keyOf = (name: string): string => {
2461
+ const trimmed = exactTarPath(name);
2462
+ const normalized = folding.normalization ? trimmed.normalize("NFD") : trimmed;
2463
+ return folding.caseFold ? normalized.toLowerCase() : normalized;
2464
+ };
2465
+ const seen = new Map<string, TarMemberName>();
2466
+ for (const member of members) {
2467
+ const key = keyOf(member.name);
2468
+ const other = seen.get(key);
2469
+ if (other === undefined) {
2470
+ seen.set(key, member);
2471
+ continue;
2472
+ }
2473
+ const same = exactTarPath(other.name) === exactTarPath(member.name);
2474
+ if (same || (other.directory && member.directory)) continue;
2475
+ throw new BrainSnapshotError(
2476
+ `the archive holds two names this machine's filesystem cannot keep apart: ` +
2477
+ `${JSON.stringify(other.name)} and ${JSON.stringify(member.name)}; a restore would keep ` +
2478
+ "only one of them, so nothing was restored. Restore it on a filesystem that keeps both " +
2479
+ "names apart, or rename one of the two files where the snapshot was taken and take a new snapshot.",
2480
+ runId,
2481
+ );
2482
+ }
2483
+ }
2484
+
2485
+ function exactTarPath(name: string): string {
2486
+ return name
2487
+ .split("/")
2488
+ .filter((part) => part !== "" && part !== ".")
2489
+ .join("/");
2490
+ }
2491
+
2492
+ /**
2493
+ * How the folder `dir` (empty, about to receive the extraction) treats
2494
+ * names: whether two Unicode forms of one name are one file there (APFS),
2495
+ * and whether two cases are (APFS, NTFS).
2496
+ */
2497
+ function nameFolding(dir: string): { normalization: boolean; caseFold: boolean } {
2498
+ const probe = join(dir, ".o2b-name-probe-\u00e9");
2499
+ writeFileSync(probe, "");
2500
+ try {
2501
+ return {
2502
+ normalization: existsSync(join(dir, ".o2b-name-probe-e\u0301")),
2503
+ caseFold: existsSync(join(dir, ".O2B-NAME-PROBE-\u00e9")),
2504
+ };
2505
+ } finally {
2506
+ rmSync(probe, { force: true });
2507
+ }
2508
+ }
2509
+
2510
+ /**
2511
+ * Refuse an extracted tree that carries a symlink pointing outside it.
2512
+ *
2513
+ * The archive is vault content - agent-writable, and in a peer-replicated
2514
+ * vault writable by every peer - so its members are untrusted input, and
2515
+ * the restore step after this sweep copies top-level entries into the
2516
+ * live tree with `dereference` off, which would re-plant such a link
2517
+ * verbatim into `Brain/`. Symlinks that stay INSIDE the extracted tree
2518
+ * are kept: the member walk that builds an archive lists symlinked files
2519
+ * and directories as members without following them, so a vault that
2520
+ * legitimately uses in-tree links produces archives carrying them, and a
2521
+ * restore must not break on its own output.
2522
+ *
2523
+ * Every link is checked twice. Its recorded target, read with
2524
+ * `readlink` and resolved against the link's own directory, must stay
2525
+ * inside the tree - this is the only check a DANGLING link can get, and
2526
+ * it is the one that matters for it: a link to a file that does not
2527
+ * exist yet outside the vault is restored verbatim into `Brain/` and
2528
+ * becomes a write-through escape the moment anything creates that file.
2529
+ * When the target does resolve, its real path must stay inside too, so
2530
+ * a chain through another link cannot leave the tree either.
2531
+ *
2532
+ * Both comparisons accept the tree under its resolved AND unresolved
2533
+ * root: the tmpdir this tree extracts into may itself sit behind a
2534
+ * platform symlink (macOS `/var`), and a compare against only one
2535
+ * spelling would refuse the tree's own honest links.
2536
+ *
2537
+ * The root is an entry of the tree like any other, and is judged first: it
2538
+ * must be a real directory. A link in its place is refused here rather than
2539
+ * followed, because every reader after this sweep - the staging copy into
2540
+ * the live tree, the diff, the store-migration rollback - reads through
2541
+ * the path it is given, and a root that is a link hands them whatever it
2542
+ * points at.
2543
+ */
2544
+ function refuseEscapingSymlinks(root: string, runId: string): void {
2545
+ const rootStat = lstatSync(root, { throwIfNoEntry: false });
2546
+ if (rootStat === undefined) {
2547
+ throw new BrainSnapshotError(`the extracted tree is not there: ${root}`, runId);
2548
+ }
2549
+ if (rootStat.isSymbolicLink()) {
2550
+ throw new BrainSnapshotError(
2551
+ `the extracted root is a symbolic link, not a directory: ${root}`,
2552
+ runId,
2553
+ );
2554
+ }
2555
+ if (!rootStat.isDirectory()) {
2556
+ throw new BrainSnapshotError(`the extracted root is not a directory: ${root}`, runId);
2557
+ }
2558
+ const realRoot = realpathSync(root);
2559
+ const lexicalRoot = resolve(root);
2560
+ const inside = (p: string): boolean =>
2561
+ p === realRoot ||
2562
+ p.startsWith(realRoot + sep) ||
2563
+ p === lexicalRoot ||
2564
+ p.startsWith(lexicalRoot + sep);
2565
+ const stack: string[] = [root];
2566
+ while (stack.length > 0) {
2567
+ const dir = stack.pop()!;
2568
+ let entries: Dirent[];
2569
+ try {
2570
+ entries = readdirSync(dir, { withFileTypes: true });
2571
+ } catch (err) {
2572
+ throw new BrainSnapshotError(
2573
+ `cannot inspect the extracted tree at ${dir}: ${(err as Error).message ?? String(err)}`,
2574
+ runId,
2575
+ { cause: err },
2576
+ );
2577
+ }
2578
+ for (const entry of entries) {
2579
+ const abs = join(dir, entry.name);
2580
+ if (entry.isSymbolicLink()) {
2581
+ const recorded = resolve(dirname(abs), readlinkSync(abs));
2582
+ let target: string | null;
2583
+ try {
2584
+ target = realpathSync(abs);
2585
+ } catch {
2586
+ // Dangling (or a loop): only the recorded target can be judged.
2587
+ target = null;
2588
+ }
2589
+ for (const candidate of target === null ? [recorded] : [recorded, target]) {
2590
+ if (!inside(candidate)) {
2591
+ throw new BrainSnapshotError(
2592
+ `snapshot contains a symlink that escapes the extracted tree: ` +
2593
+ `${relative(root, abs)} -> ${candidate}`,
2594
+ runId,
2595
+ );
2596
+ }
2597
+ }
2598
+ continue;
2599
+ }
2600
+ if (entry.isDirectory()) stack.push(abs);
2601
+ }
2602
+ }
2603
+ }
2604
+
2605
+ /**
2606
+ * A file the restore reads must be a real file. `existsSync` follows a
2607
+ * symbolic link, so an archive the vault holds as one would be read through
2608
+ * it - and the vault is agent-writable, and in a peer-replicated vault
2609
+ * writable by every peer. The link is refused by name instead.
2610
+ */
2611
+ function assertRegularFile(path: string, runId: string, what: string): void {
2612
+ const stat = lstatSync(path, { throwIfNoEntry: false });
2613
+ if (stat === undefined) {
2614
+ throw new BrainSnapshotError(`${what} does not exist: ${path}`, runId);
2615
+ }
2616
+ if (stat.isSymbolicLink()) {
2617
+ throw new BrainSnapshotError(`${what} is a symbolic link, not a file: ${path}`, runId);
2618
+ }
2619
+ if (!stat.isFile()) {
2620
+ throw new BrainSnapshotError(`${what} is not a regular file: ${path}`, runId);
2621
+ }
2622
+ }
2623
+
2624
+ /**
2625
+ * The inflated bytes of a gzip archive, refused when they pass the ceiling
2626
+ * {@link MAX_INFLATED_ARCHIVE_BYTES} names.
2627
+ *
2628
+ * The gzip branch of a restore inflates in process, because native Windows
2629
+ * has no `gzip` binary, and what it inflates is held in memory: the tar
2630
+ * stream of `Brain/`, or the archived derived store. An archive that
2631
+ * inflates far past the tree it claims to hold is refused by name, and the
2632
+ * operator who really has such a vault raises the ceiling through
2633
+ * {@link SNAPSHOT_MAX_INFLATED_BYTES_ENV}.
2634
+ */
2635
+ function inflateGzipArchive(archive: string, runId: string): Buffer {
2636
+ const limit = resolveMaxInflatedBytes();
2637
+ const compressed = readCompressedArchive(archive, runId, limit);
2638
+ try {
2639
+ return gunzipSync(compressed, { maxOutputLength: limit });
2640
+ } catch (err) {
2641
+ if ((err as NodeJS.ErrnoException).code === "ERR_BUFFER_TOO_LARGE") {
2642
+ throw new BrainSnapshotError(
2643
+ `the archive inflates to more than ${limit} bytes; refusing to restore it ` +
2644
+ `(raise ${SNAPSHOT_MAX_INFLATED_BYTES_ENV} for a larger vault)`,
2645
+ runId,
2646
+ { cause: err },
2647
+ );
2648
+ }
2649
+ throw new BrainSnapshotError(
2650
+ `gzip decompress failed: ${(err as Error).message ?? String(err)}`,
2651
+ runId,
2652
+ );
2653
+ }
2654
+ }
2655
+
2656
+ /**
2657
+ * The compressed bytes of an archive, refused before they are read when the
2658
+ * file is larger than the ceiling allows. Gzip output is never meaningfully
2659
+ * smaller than the bytes it holds, so a file this large cannot inflate to
2660
+ * less than the ceiling either - and reading it would cost the memory the
2661
+ * ceiling exists to bound.
2662
+ */
2663
+ function readCompressedArchive(archive: string, runId: string, limit: number): Buffer {
2664
+ const size = statSync(archive).size;
2665
+ if (size > limit + GZIP_OVERHEAD_SLACK_BYTES) {
2666
+ throw new BrainSnapshotError(
2667
+ `the archive is ${size} bytes, over the ${limit}-byte ceiling a restore allows ` +
2668
+ `(raise ${SNAPSHOT_MAX_INFLATED_BYTES_ENV} for a larger vault)`,
2669
+ runId,
2670
+ );
2671
+ }
2672
+ return readFileSync(archive);
2673
+ }
2674
+
2675
+ /**
2676
+ * What gzip may add to the bytes it holds: a header, a trailer, and a few
2677
+ * bytes per deflate block. A compressed archive of exactly the ceiling size
2678
+ * is therefore still an archive of the ceiling size.
2679
+ */
2680
+ const GZIP_OVERHEAD_SLACK_BYTES = 1024 * 1024;
2681
+
2682
+ /**
2683
+ * Restore the archive identified by `runId` over `Brain/`, and the
2684
+ * derived store alongside it when the snapshot recorded one. The current
2685
+ * `.snapshots/` directory is preserved verbatim so older rollbacks still
2686
+ * have a path back.
2687
+ *
2688
+ * Every step that can fail for a reason other than the swap itself runs
2689
+ * BEFORE anything live changes, so a failed restore leaves `Brain/` and
2690
+ * the derived store exactly as they were:
2691
+ *
2692
+ * 1. Pre-flight the derived-store records: refuse an unreadable record
2693
+ * or a recorded archive that is not on disk, and refuse a live store
2694
+ * nested inside a top-level `Brain/` directory the swap replaces.
2695
+ * 2. Extract the archive into a private temp dir and verify it has a
2696
+ * `Brain/` root with no symlink escaping it.
2697
+ * 3. Stage the extracted top-level entries (minus
2698
+ * {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES}, and minus the store's file
2699
+ * family when the store sits directly under `Brain/`) on the live
2700
+ * tree's own filesystem, and verify the staged copy holds every file.
2701
+ * 4. When the manifest says the snapshot included the derived store:
2702
+ * check the archive against the recorded digest, decompress it
2703
+ * beside the live store, and run the integrity check on the result.
2704
+ * 5. Take the derived store's writer lock (when it is being replaced),
2705
+ * so lock contention also refuses before anything is touched. It is
2706
+ * held from here through the swap.
2707
+ * 6. Run {@link RestoreSnapshotOptions.beforeDiscard}, the seam where a
2708
+ * recovery point of the state about to be discarded is taken, then
2709
+ * re-check that the derived-store records did not change under it.
2710
+ * The lock taken in step 5 means no write lands between the recovery
2711
+ * point and the swap, so the recovery point holds every commit the
2712
+ * swap replaces.
2713
+ * 7. Swap: move each live top-level entry aside and rename the staged
2714
+ * one into place, then rename the staged store over the live one.
2715
+ * Renames only, on one filesystem, so the window is short. If any
2716
+ * rename fails, the renames already done are undone in reverse.
2717
+ * 8. Remove the outgoing entries and every staging directory.
2718
+ *
2719
+ * Step 7 is a data-loss operation with the strongest confirmation ladder
2720
+ * in the codebase in front of it and, until step 5 existed, nothing at
2721
+ * all behind it: an operator who rolled back to the wrong run id had no
2722
+ * way back. Callers that want one use `restoreSnapshotWithRecoveryPoint`
2723
+ * in `snapshot-gate.ts`; callers that do not get a `recoverability`
2724
+ * verdict saying so rather than silence. When the swap fails AND its undo
2725
+ * fails too, the error names what was swapped, where the outgoing entries
2726
+ * were left, and the recovery point when one was taken. When the lock
2727
+ * cannot be released after the swap committed, the error says the restore
2728
+ * committed and names the recovery point; a release failure never
2729
+ * replaces an earlier error, it is added to it.
2730
+ */
2731
+ export function restoreSnapshot(
2732
+ vault: string,
2733
+ runId: string,
2734
+ opts: RestoreSnapshotOptions = {},
2735
+ ): RestoreSnapshotResult {
2736
+ const liveVault = vault;
2737
+ vault = machineStateRoot(vault);
2738
+ const dirs = brainDirsForWrite(vault, undefined, opts.lane);
2739
+
2740
+ // Everything a restore needs is checked before anything is replaced.
2741
+ //
2742
+ // The store step used to run after the Markdown tree had already been
2743
+ // deleted and re-copied, so a missing store archive threw over work
2744
+ // that had in fact completed: the caller reported a failed rollback,
2745
+ // logged nothing, and the vault was rolled back anyway. Reachable
2746
+ // whenever the sidecar survives without its companion archive - partial
2747
+ // replication, a sync rule excluding large binaries, or an operator
2748
+ // reclaiming disk. The create path already refuses before it writes;
2749
+ // this is the same ordering on the way back.
2750
+ assertDerivedStoreRestorable(vault, runId);
2751
+ // The records the pre-flight just validated, as one comparable value.
2752
+ const storeStateBefore = derivedStoreRestoreState(vault, runId);
2753
+
2754
+ // The live store target, resolved once: the store step writes to it,
2755
+ // and the Brain swap must keep out of its way when it sits inside
2756
+ // `Brain/`. The manifest's `source_path` is where the store WAS; the
2757
+ // live target is where it is now. They differ when the operator moved
2758
+ // the vault or set a `search_db_path` override after the snapshot, and
2759
+ // the live answer is the one a restore must write to.
2760
+ const storeTarget = opts.derivedStorePath ?? liveDerivedStorePath(liveVault);
2761
+ const placement = storePlacement(dirs.brain, storeTarget);
2762
+ refuseStoreTheSwapCannotWriteAround(placement, storeTarget, runId);
2763
+ // Names the Brain swap leaves alone in both directions, beyond the
2764
+ // excluded entries: with the store directly under `Brain/`, its file
2765
+ // family. The live store, its journals and lock, and the staged
2766
+ // replacement stay where the store swap expects them, and the raw copy
2767
+ // of the store the Brain archive carries (it archives every top-level
2768
+ // entry) is not restored over it, so the store is written once, by the
2769
+ // store swap, from the store archive - or not at all when the snapshot
2770
+ // did not cover it.
2771
+ const keptOutOfSwap = (name: string, isDirectory: boolean): boolean =>
2772
+ placement.kind === "top" && isStoreFamilyEntry(name, placement.base, isDirectory);
2773
+
2774
+ const ext = extractSnapshotToTemp(vault, runId);
2775
+ let staged: StagedBrainTree | null = null;
2776
+ let store: StagedDerivedStore | null = null;
2777
+ try {
2778
+ // Replace every top-level entry under Brain/, except the entries the
2779
+ // snapshot family never touches. The `.snapshots/` exclusion is the
2780
+ // load-bearing safety guarantee: rolling back an older state must
2781
+ // not erase newer snapshots, otherwise the operator is one click
2782
+ // away from losing their forward path. `.artifacts/` is excluded for
2783
+ // the opposite reason - it is not in the archive at all, so deleting
2784
+ // the live copy would restore nothing over it.
2785
+ //
2786
+ // `.snapshots/` is created first, as `createSnapshot` does: the
2787
+ // staging directory goes there when it shares `Brain/`'s device, and
2788
+ // a missing one would otherwise read as "another device" and send the
2789
+ // staging directory into `Brain/` itself.
2790
+ ensureSnapshotsDirectory(dirs.snapshots, runId);
2791
+ staged = stageBrainTree(ext.brainRoot, dirs.brain, dirs.snapshots, runId, keptOutOfSwap);
2792
+
2793
+ // The derived store is decompressed and verified here, before the
2794
+ // recovery point and before the Brain tree is touched. It used to be
2795
+ // decompressed only after the tree had been replaced, so a `zstd`
2796
+ // timeout, a corrupt payload or a full disk left a rolled-back tree
2797
+ // beside the store it was meant to replace.
2798
+ const plan = stageDerivedStore(vault, storeTarget, runId);
2799
+ store = plan.staged;
2800
+
2801
+ // The correct semantics are "live tree == snapshot tree minus the
2802
+ // excluded entries". Every live top-level entry except those is moved
2803
+ // out, and every staged one moved in. This makes restore
2804
+ // deterministic.
2805
+ const liveEntries = existsSync(dirs.brain)
2806
+ ? readdirSync(dirs.brain, { withFileTypes: true })
2807
+ .filter(
2808
+ (e) =>
2809
+ !isSnapshotExcludedEntry(e.name) &&
2810
+ e.name !== staged!.name &&
2811
+ !keptOutOfSwap(e.name, e.isDirectory()),
2812
+ )
2813
+ .map((e) => e.name)
2814
+ : [];
2815
+
2816
+ // The writer lock is taken before the recovery point, not inside the
2817
+ // store swap, and held through the swap. Taken before the recovery
2818
+ // point because a writer committing between the recovery point and
2819
+ // the swap would land a change the swap discards and the recovery
2820
+ // point never saw. Taken before the first rename because an index run
2821
+ // holding it is a refusal like any other, and it must arrive while
2822
+ // nothing has been replaced yet.
2823
+ const lock = store === null ? null : acquireStoreLockForRestore(store.target, runId);
2824
+ // A rebuild that died between the renames of its swap left the index
2825
+ // parked with no live file: it is put back before anything reads the
2826
+ // live store, so the recovery point archives it and the swap below
2827
+ // parks it, instead of treating it as an earlier `.bak` to replace.
2828
+ let evidence: RecoveryPointEvidence | null = null;
2829
+ let committed = false;
2830
+ let primary: { readonly err: unknown } | null = null;
2831
+ try {
2832
+ if (store !== null && lock !== null) restoreParkedIndexUnderLock(store.target, lock.lease);
2833
+ // The last moment at which the live state still exists. A throw
2834
+ // here propagates and nothing has been replaced yet, which is the
2835
+ // same abort-before-the-operation rule the destructive gate applies.
2836
+ //
2837
+ // The recovery point runs tar, zstd and a store archive synchronously
2838
+ // under the lock. Each of those keeps the lease fresh for its own
2839
+ // bound, and the rest of the callback (the manifest, the retention
2840
+ // pass) for this outer one; the bounds add up rather than nest, so a
2841
+ // wedged recovery point holds the lock at most for their sum and then
2842
+ // lets it go stale, never forever.
2843
+ try {
2844
+ evidence =
2845
+ keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () =>
2846
+ opts.beforeDiscard?.({
2847
+ storeTarget: store?.target ?? null,
2848
+ heldStoreLock: lock?.token ?? null,
2849
+ }),
2850
+ ) ?? null;
2851
+ } catch (err) {
2852
+ // A lease lost while the recovery point ran is reported as the
2853
+ // restore's own refusal, with nothing touched.
2854
+ if (lock !== null && lock.lease.lost) assertStoreLeaseHeld(lock.lease, runId);
2855
+ throw err;
2856
+ }
2857
+ if (store !== null && evidence !== null) {
2858
+ assertRecoveryPointCoversTarget(vault, evidence, store.target, runId);
2859
+ }
2860
+
2861
+ // The callback is the one step that can change `.snapshots/` between
2862
+ // the pre-flight and the store swap - it takes a recovery point, and
2863
+ // a retention pass rides behind that. `assertDerivedStoreRestorable`
2864
+ // above validated a state this callback may have invalidated, so the
2865
+ // pre-flight is re-run against the state that actually reaches the
2866
+ // rest of the restore, and the RECORD is compared rather than only
2867
+ // re-checked: a manifest that has been removed outright would pass a
2868
+ // fresh pre-flight while turning a covered store into "coverage
2869
+ // unknown, nothing restored".
2870
+ if (opts.beforeDiscard !== undefined) {
2871
+ assertDerivedStoreRestorable(vault, runId);
2872
+ const after = derivedStoreRestoreState(vault, runId);
2873
+ if (after !== storeStateBefore) {
2874
+ throw new BrainSnapshotError(
2875
+ "the derived-store records of this snapshot changed while the recovery point was " +
2876
+ `being taken (${storeStateBefore} -> ${after}); refusing before the Brain tree is ` +
2877
+ "touched, so nothing is half-restored",
2878
+ runId,
2879
+ );
2880
+ }
2881
+ }
2882
+
2883
+ // The lease is proven once more right before the first rename. One
2884
+ // that another writer took over (the recovery point stalled past the
2885
+ // stale window) excludes nothing any more, and the swap would discard
2886
+ // whatever that writer committed.
2887
+ if (lock !== null) assertStoreLeaseHeld(lock.lease, runId);
2888
+
2889
+ // The Brain/ renames run under the lease too, kept fresh off this
2890
+ // thread, and the lease is proven once more when they are done, right
2891
+ // before the store replacement: a lease lost during the renames
2892
+ // undoes them instead of replacing a store another writer now owns.
2893
+ const held: { swap?: ReturnType<typeof swapBrainTree> } = {};
2894
+ const tree = staged;
2895
+ const recovery = evidence;
2896
+ let swapStarted = false;
2897
+ const runSwap = (): void => {
2898
+ swapStarted = true;
2899
+ held.swap = swapBrainTree(tree, dirs.brain, liveEntries, runId, recovery);
2900
+ };
2901
+ try {
2902
+ if (lock === null) runSwap();
2903
+ else keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, runSwap);
2904
+ } catch (err) {
2905
+ // A failed rename has undone its own renames and says so, undo
2906
+ // result and recovery included; that error stands. Only when the
2907
+ // swap never started (the lease was found lost on entry) is this
2908
+ // the restore's own refusal, with nothing touched.
2909
+ if (held.swap === undefined) {
2910
+ if (!swapStarted && lock !== null && lock.lease.lost) {
2911
+ assertStoreLeaseHeld(lock.lease, runId);
2912
+ }
2913
+ throw err;
2914
+ }
2915
+ throw held.swap.fail(
2916
+ `the derived store's writer lock was lost during the Brain/ swap (${errorText(err)})`,
2917
+ err,
2918
+ { storeIntact: true },
2919
+ );
2920
+ }
2921
+ const swap = held.swap;
2922
+ if (swap === undefined)
2923
+ throw new BrainSnapshotError("restore: the Brain/ swap did not run", runId);
2924
+ let outgoingStore: string | null = null;
2925
+ if (store !== null) {
2926
+ const stagedStore = store;
2927
+ try {
2928
+ const commit = (): string => {
2929
+ if (lock !== null) assertStoreLeaseHeld(lock.lease, runId);
2930
+ return commitDerivedStoreSwap(stagedStore, () => {
2931
+ if (lock !== null) assertStoreLeaseHeld(lock.lease, runId);
2932
+ });
2933
+ };
2934
+ outgoingStore =
2935
+ lock === null
2936
+ ? commit()
2937
+ : keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, commit);
2938
+ } catch (err) {
2939
+ // Two failures here can come after the restored store was renamed
2940
+ // in: removing the park record (a file this swap just wrote) and
2941
+ // the lease check `keepWriterLeasesFresh` makes when `commit`
2942
+ // returns (a takeover needs the lock gone stale while the worker
2943
+ // refreshed it). Neither is reachable without outside tampering or
2944
+ // a suspended process, and either stays on the safe side: the
2945
+ // restore reports failure, the pre-restore store stays at its
2946
+ // parked name, nothing is deleted, and a recovery point taken for
2947
+ // this restore holds a copy of it.
2948
+ throw swap.fail(`the derived store swap failed (${errorText(err)})`, err, {
2949
+ storeIntact: !(err instanceof StoreSwapTornError),
2950
+ });
2951
+ }
2952
+ }
2953
+ committed = true;
2954
+ swap.finish();
2955
+ if (store !== null && evidence !== null && outgoingStore !== null) {
2956
+ const committedStore = store;
2957
+ const committedEvidence = evidence;
2958
+ const committedOutgoing = outgoingStore;
2959
+ const cleanup = (): void => {
2960
+ if (lock !== null) assertStoreLeaseHeld(lock.lease, runId);
2961
+ discardCoveredOutgoingStore(
2962
+ vault,
2963
+ committedEvidence,
2964
+ committedStore.target,
2965
+ committedOutgoing,
2966
+ () => {
2967
+ if (lock !== null) assertStoreLeaseHeld(lock.lease, runId);
2968
+ },
2969
+ );
2970
+ };
2971
+ if (lock === null) cleanup();
2972
+ else keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, cleanup);
2973
+ }
2974
+ } catch (err) {
2975
+ primary = { err };
2976
+ throw err;
2977
+ } finally {
2978
+ if (lock !== null)
2979
+ releaseStoreLockAfterRestore(lock.release, runId, committed, primary, evidence);
2980
+ }
2981
+
2982
+ const derivedStore = plan.result;
2983
+ return {
2984
+ restored_files: staged.files,
2985
+ derived_store: derivedStore,
2986
+ // What the DISCARDED tree was worth, not the archive's. The live
2987
+ // derived store is replaced only when the archive carried one, so
2988
+ // it joins the blast radius exactly when it was actually swapped.
2989
+ recoverability: classifyRecoverability({
2990
+ // An ARCHIVE, probed here at the end of the restore rather than
2991
+ // the presence of a callback. `beforeDiscard !== undefined` said
2992
+ // `covered` for any caller that supplied a function - including
2993
+ // one that took no snapshot, and including the case where the
2994
+ // recovery point was written and then evicted by the retention
2995
+ // pass behind it.
2996
+ recoveryPoint: evidence !== null && existsSync(evidence.path),
2997
+ blastRadius: { brainTopLevel: true, derivedStore: derivedStore.replaced },
2998
+ }),
2999
+ };
3000
+ } finally {
3001
+ store?.discard();
3002
+ staged?.cleanup();
3003
+ ext.cleanup();
3004
+ }
3005
+ }
3006
+
3007
+ /**
3008
+ * The extracted `Brain/` entries, copied onto the live tree's filesystem
3009
+ * so the swap is a run of renames rather than a delete-and-copy.
3010
+ *
3011
+ * `root` holds `incoming/` (the staged entries) and, once the swap has
3012
+ * started, `outgoing/` (the live entries moved aside). {@link cleanup}
3013
+ * removes it best-effort, and keeps it when {@link keep} has been called
3014
+ * because the outgoing entries are the only copy left.
3015
+ */
3016
+ interface StagedBrainTree {
3017
+ /** Top-level name of {@link root} inside its parent directory. */
3018
+ readonly name: string;
3019
+ readonly root: string;
3020
+ readonly incoming: string;
3021
+ readonly entries: ReadonlyArray<string>;
3022
+ /** Regular files under {@link incoming}. */
3023
+ readonly files: number;
3024
+ keep(): void;
3025
+ cleanup(): void;
3026
+ }
3027
+
3028
+ /**
3029
+ * Copy the extracted tree to a staging directory on the live tree's
3030
+ * filesystem and verify the copy.
3031
+ *
3032
+ * The staging directory goes under `.snapshots/` - excluded from every
3033
+ * archive, manifest walk and restore, and never listed as a snapshot
3034
+ * since it carries no archive suffix - when that directory shares a
3035
+ * device with `Brain/`. When it does not (a separately mounted snapshot
3036
+ * directory), a rename from it into `Brain/` would fail mid-swap with
3037
+ * EXDEV, so the staging directory goes directly under `Brain/` instead
3038
+ * and the swap leaves it alone.
3039
+ *
3040
+ * Entries `keptOut` names (the store's file family, when the store sits
3041
+ * directly under `Brain/`) are neither staged nor counted: the swap leaves
3042
+ * the live ones in place, and the store is restored by the store swap.
3043
+ */
3044
+ function stageBrainTree(
3045
+ extractedBrain: string,
3046
+ liveBrain: string,
3047
+ snapshotsDirPath: string,
3048
+ runId: string,
3049
+ keptOut: (name: string, isDirectory: boolean) => boolean,
3050
+ ): StagedBrainTree {
3051
+ mkdirSync(liveBrain, { recursive: true });
3052
+ const parent = sameDevice(snapshotsDirPath, liveBrain) ? snapshotsDirPath : liveBrain;
3053
+ let root: string;
3054
+ try {
3055
+ root = mkdtempSync(join(parent, `${BRAIN_RESTORE_STAGING_PREFIX}${runId}-`));
3056
+ } catch (err) {
3057
+ throw new BrainSnapshotError(
3058
+ `cannot create a restore staging directory under ${parent}: ${errorText(err)}`,
3059
+ runId,
3060
+ { cause: err },
3061
+ );
3062
+ }
3063
+ let kept = false;
3064
+ const cleanup = (): void => {
3065
+ if (kept) return;
3066
+ try {
3067
+ rmSync(root, { recursive: true, force: true });
3068
+ } catch (err) {
3069
+ console.error(
3070
+ `warning: could not remove the restore staging directory ${root}: ${errorText(err)}`,
3071
+ );
3072
+ }
3073
+ };
3074
+ try {
3075
+ const incoming = join(root, "incoming");
3076
+ mkdirSync(incoming);
3077
+ const entries = readdirSync(extractedBrain, { withFileTypes: true })
3078
+ .filter((e) => !isSnapshotExcludedEntry(e.name) && !keptOut(e.name, e.isDirectory()))
3079
+ .map((e) => e.name);
3080
+ let files = 0;
3081
+ let expected = 0;
3082
+ for (const name of entries) {
3083
+ // `verbatimSymlinks` is load-bearing: without it `cpSync` rewrites
3084
+ // every relative link to the ABSOLUTE path of its target inside the
3085
+ // temp extraction, which the cleanup deletes - the in-tree links the
3086
+ // containment sweep kept would all restore dangling, pointing outside
3087
+ // the vault. A relative link survives the later rename unchanged,
3088
+ // because the staged entry sits at the same depth as the live one.
3089
+ const from = join(extractedBrain, name);
3090
+ const to = join(incoming, name);
3091
+ cpSync(from, to, { recursive: true, verbatimSymlinks: true });
3092
+ }
3093
+ // Counted only once every entry is staged: a top-level link to another
3094
+ // top-level entry resolves in the staged copy only after its target is.
3095
+ for (const name of entries) {
3096
+ expected += countFiles(join(extractedBrain, name));
3097
+ files += countFiles(join(incoming, name));
3098
+ }
3099
+ if (files !== expected) {
3100
+ throw new BrainSnapshotError(
3101
+ `the staged Brain tree holds ${files} file(s) but the archive extracted ${expected}; ` +
3102
+ "refusing before the Brain tree is touched",
3103
+ runId,
3104
+ );
3105
+ }
3106
+ return {
3107
+ name: basename(root),
3108
+ root,
3109
+ incoming,
3110
+ entries,
3111
+ files,
3112
+ keep: () => {
3113
+ kept = true;
3114
+ },
3115
+ cleanup,
3116
+ };
3117
+ } catch (err) {
3118
+ cleanup();
3119
+ if (err instanceof BrainSnapshotError) throw err;
3120
+ throw new BrainSnapshotError(
3121
+ `failed to stage the extracted Brain tree under ${root}: ${errorText(err)}`,
3122
+ runId,
3123
+ { cause: err },
3124
+ );
3125
+ }
3126
+ }
3127
+
3128
+ /** Whether two existing paths live on the same device; false when unsure. */
3129
+ function sameDevice(a: string, b: string): boolean {
3130
+ try {
3131
+ return statSync(a).dev === statSync(b).dev;
3132
+ } catch {
3133
+ return false;
3134
+ }
3135
+ }
3136
+
3137
+ /** An in-progress Brain swap: {@link finish} it, or {@link fail} it. */
3138
+ interface BrainSwap {
3139
+ /** Remove the outgoing entries; the swap is complete. */
3140
+ finish(): void;
3141
+ /**
3142
+ * Undo the swap and return the error to throw, naming what failed,
3143
+ * whether the undo succeeded and how to recover when it did not.
3144
+ */
3145
+ fail(what: string, cause: unknown, opts?: { readonly storeIntact?: boolean }): BrainSnapshotError;
3146
+ }
3147
+
3148
+ /**
3149
+ * Move every live top-level entry into the staging directory's
3150
+ * `outgoing/`, then rename every staged entry into `Brain/`.
3151
+ *
3152
+ * Renames on one filesystem: each one either happens or does not, and
3153
+ * the outgoing entries stay on disk until {@link BrainSwap.finish}, so a
3154
+ * failure at any point - here, or in the store swap that follows - is
3155
+ * undone by renaming everything back in reverse order.
3156
+ */
3157
+ function swapBrainTree(
3158
+ staged: StagedBrainTree,
3159
+ liveBrain: string,
3160
+ liveEntries: ReadonlyArray<string>,
3161
+ runId: string,
3162
+ recoveryPoint: RecoveryPointEvidence | null,
3163
+ ): BrainSwap {
3164
+ const outgoing = join(staged.root, "outgoing");
3165
+ const movedOut: string[] = [];
3166
+ const movedIn: string[] = [];
3167
+
3168
+ const undo = (): string[] => {
3169
+ const failures: string[] = [];
3170
+ for (const name of movedIn.toReversed()) {
3171
+ try {
3172
+ renameWithRetry(join(liveBrain, name), join(staged.incoming, name));
3173
+ } catch (err) {
3174
+ failures.push(`could not move the restored ${name} back out: ${errorText(err)}`);
3175
+ }
3176
+ }
3177
+ for (const name of movedOut.toReversed()) {
3178
+ try {
3179
+ renameWithRetry(join(outgoing, name), join(liveBrain, name));
3180
+ } catch (err) {
3181
+ failures.push(`could not move the live ${name} back: ${errorText(err)}`);
3182
+ }
3183
+ }
3184
+ return failures;
3185
+ };
3186
+
3187
+ const fail = (
3188
+ what: string,
3189
+ cause: unknown,
3190
+ opts: { readonly storeIntact?: boolean } = {},
3191
+ ): BrainSnapshotError => {
3192
+ const storeIntact = opts.storeIntact ?? true;
3193
+ const swapped =
3194
+ `${movedOut.length} of ${liveEntries.length} live Brain/ top-level entries had been moved ` +
3195
+ `aside and ${movedIn.length} of ${staged.entries.length} restored ones moved in`;
3196
+ const failures = undo();
3197
+ const recovery =
3198
+ recoveryPoint === null
3199
+ ? "no recovery point was taken for this restore"
3200
+ : `the recovery point ${recoveryPoint.runId} (${recoveryPoint.path}) holds the ` +
3201
+ `pre-restore state; \`o2b brain rollback ${recoveryPoint.runId}\` puts it back`;
3202
+ if (failures.length === 0) {
3203
+ const state = storeIntact
3204
+ ? "Brain/ and the derived store are as they were before the restore"
3205
+ : `Brain/ is as it was before the restore, but the derived store is not (see above); ${recovery}`;
3206
+ return new BrainSnapshotError(
3207
+ `restore failed during the swap: ${what}. ${swapped}; every Brain/ rename was undone, so ${state}`,
3208
+ runId,
3209
+ { cause },
3210
+ );
3211
+ }
3212
+ // The outgoing entries are now the only copy of what did not make it
3213
+ // back: the staging directory must outlive this restore.
3214
+ staged.keep();
3215
+ return new BrainSnapshotError(
3216
+ `restore failed during the swap: ${what}. ${swapped}; undoing it also failed ` +
3217
+ `(${failures.join("; ")}), so Brain/ is a mix of the restored and the pre-restore ` +
3218
+ `tree. The pre-restore entries that were moved aside are kept under ${outgoing} and ` +
3219
+ `the restored ones not yet moved in under ${staged.incoming}; ${recovery}`,
3220
+ runId,
3221
+ { cause },
3222
+ );
3223
+ };
3224
+
3225
+ try {
3226
+ mkdirSync(outgoing);
3227
+ for (const name of liveEntries) {
3228
+ renameWithRetry(join(liveBrain, name), join(outgoing, name));
3229
+ movedOut.push(name);
3230
+ }
3231
+ for (const name of staged.entries) {
3232
+ renameWithRetry(join(staged.incoming, name), join(liveBrain, name));
3233
+ movedIn.push(name);
3234
+ }
3235
+ } catch (err) {
3236
+ throw fail(`a Brain/ rename failed (${errorText(err)})`, err);
3237
+ }
3238
+
3239
+ return {
3240
+ finish: () => {
3241
+ try {
3242
+ rmSync(outgoing, { recursive: true, force: true });
3243
+ } catch (err) {
3244
+ // The restore itself is complete; what is left is the discarded
3245
+ // tree, which the staging cleanup retries.
3246
+ console.error(
3247
+ `warning: could not remove the pre-restore Brain entries under ${outgoing}: ` +
3248
+ errorText(err),
3249
+ );
3250
+ }
3251
+ },
3252
+ fail,
3253
+ };
3254
+ }
3255
+
3256
+ /** An error's message, or its string form. */
3257
+ function errorText(err: unknown): string {
3258
+ return err instanceof Error ? err.message : String(err);
3259
+ }
3260
+
3261
+ /**
3262
+ * Refuse a restore that cannot be completed, before it starts.
3263
+ *
3264
+ * Two conditions, both of which used to surface only after the Markdown
3265
+ * tree had been replaced. A derived-store record this build cannot read
3266
+ * means coverage is indeterminate, so neither replacing the live store
3267
+ * nor leaving it can be justified; a record that names an archive which
3268
+ * is not on disk means the restore is already incomplete. Either way the
3269
+ * honest answer is to touch nothing and say why.
3270
+ */
3271
+ /**
3272
+ * The three facts a restore's store step depends on, as one comparable
3273
+ * token: whether the sidecar is readable, what it says about coverage,
3274
+ * and whether the store archive is on disk.
3275
+ *
3276
+ * Compared rather than re-checked because the failure this exists to
3277
+ * catch REMOVES a record: a fresh pre-flight over a vanished manifest
3278
+ * passes (no record, nothing to validate) and the restore then reports
3279
+ * coverage as unknown over a store it was asked to put back.
3280
+ */
3281
+ function derivedStoreRestoreState(vault: string, runId: string): string {
3282
+ const manifest = readManifestSidecar(vault, runId);
3283
+ const record = manifest?.derived_store ?? null;
3284
+ return [
3285
+ manifest === null ? 0 : 1,
3286
+ manifest?.derived_store_unreadable === true ? 1 : 0,
3287
+ record === null ? 0 : record.included ? 1 : 2,
3288
+ record?.archive_sha256 ?? "",
3289
+ existsSync(snapshotStorePath(vault, runId)) ? 1 : 0,
3290
+ ].join("/");
3291
+ }
3292
+
3293
+ function assertDerivedStoreRestorable(vault: string, runId: string): void {
3294
+ const manifest = readManifestSidecar(vault, runId);
3295
+ if (manifest === null) return;
3296
+ if (manifest.derived_store_unreadable === true) {
3297
+ throw new BrainSnapshotError(
3298
+ "the manifest carries a derived-store record this build cannot read, so whether the " +
3299
+ "snapshot covered the store is indeterminate; refusing to restore rather than " +
3300
+ "guessing at the live store",
3301
+ runId,
3302
+ );
3303
+ }
3304
+ const record = manifest.derived_store ?? null;
3305
+ if (record === null || !record.included) return;
3306
+ const archive = snapshotStorePath(vault, runId);
3307
+ if (!existsSync(archive)) {
3308
+ throw new BrainSnapshotError(
3309
+ `manifest records a derived-store archive but ${archive} is absent; refusing before the ` +
3310
+ "Brain tree is touched, so nothing is half-restored",
3311
+ runId,
3312
+ );
3313
+ }
3314
+ // The archive is read as a file, so it has to be one: `existsSync`
3315
+ // follows a link, and a vault that holds the archive as one would
3316
+ // otherwise have the restore read through it.
3317
+ assertRegularFile(archive, runId, "the derived-store archive");
3318
+ }
3319
+
3320
+ /**
3321
+ * Where the derived store sits relative to `Brain/`, which decides how the
3322
+ * Brain swap must treat it.
3323
+ *
3324
+ * - `outside`: the swap and the store never meet.
3325
+ * - `top`: the store is a direct child of `Brain/`. The swap leaves its
3326
+ * file family (see {@link isStoreFamilyEntry}) where it is, in both
3327
+ * directions; the store is written only by the store swap.
3328
+ * - `nested`: the store is deeper inside a top-level `Brain/` entry the
3329
+ * swap replaces wholesale; `top` names that entry.
3330
+ * - `brain`: the store path is the `Brain/` directory itself.
3331
+ */
3332
+ export type StorePlacement =
3333
+ | { readonly kind: "outside" }
3334
+ | { readonly kind: "top"; readonly base: string }
3335
+ | { readonly kind: "nested"; readonly top: string }
3336
+ | { readonly kind: "brain" };
3337
+
3338
+ /**
3339
+ * A path with every existing ancestor resolved through symlinks. Where the
3340
+ * platform folds case, an absent component takes the spelling of the one
3341
+ * entry of its parent that matches it without case, so a store configured
3342
+ * as `Index.sqlite` is recognised as the `index.sqlite` on disk and in the
3343
+ * archive.
3344
+ */
3345
+ function canonicalPath(path: string, platform: NodeJS.Platform): string {
3346
+ const abs = resolve(path);
3347
+ try {
3348
+ return realpathSync.native(abs);
3349
+ } catch {
3350
+ const parent = dirname(abs);
3351
+ if (parent === abs) return abs;
3352
+ const canonicalParent = canonicalPath(parent, platform);
3353
+ return join(canonicalParent, existingSpelling(canonicalParent, basename(abs), platform));
3354
+ }
3355
+ }
3356
+
3357
+ /** The spelling of `name` among `dir`'s entries where case is folded. */
3358
+ function existingSpelling(dir: string, name: string, platform: NodeJS.Platform): string {
3359
+ if (!foldsCase(platform)) return name;
3360
+ let entries: string[];
3361
+ try {
3362
+ entries = readdirSync(dir);
3363
+ } catch {
3364
+ return name;
3365
+ }
3366
+ if (entries.includes(name)) return name;
3367
+ const key = compareKey(name, platform);
3368
+ const matches = entries.filter((e) => compareKey(e, platform) === key);
3369
+ return matches.length === 1 ? matches[0]! : name;
3370
+ }
3371
+
3372
+ /**
3373
+ * The directory entry a rename of `path` acts on: every ancestor resolved
3374
+ * through symlinks, the last component itself not followed. Where the
3375
+ * platform folds case, an existing entry takes its on-disk spelling.
3376
+ */
3377
+ function entryPath(path: string, platform: NodeJS.Platform): string {
3378
+ const abs = resolve(path);
3379
+ const parent = dirname(abs);
3380
+ if (parent === abs) return canonicalPath(abs, platform);
3381
+ const canonicalParent = canonicalPath(parent, platform);
3382
+ return join(canonicalParent, existingSpelling(canonicalParent, basename(abs), platform));
3383
+ }
3384
+
3385
+ /**
3386
+ * Classify the store target against the live `Brain/` directory. The
3387
+ * containment test compares case-folded paths where the platform folds
3388
+ * case; the names it returns keep the target's canonical spelling.
3389
+ *
3390
+ * What is classified is the directory entry at the target path, not the
3391
+ * file a symlink there points to: the store swap renames that entry (it
3392
+ * stages `<target>.restore-*` beside it, moves it aside to `<target>.bak`
3393
+ * and renames the staged file over it), so the Brain swap must judge the
3394
+ * same entry. A `Brain/index.sqlite` that links to a database outside
3395
+ * `Brain/` is a store directly under `Brain/`: the link and the staged
3396
+ * file beside it stay out of the tree swap, and the store swap replaces
3397
+ * the link with the restored database. Classifying the link's target
3398
+ * instead called it `outside`, and the tree swap then moved the staged
3399
+ * file away before the store swap could rename it.
3400
+ */
3401
+ export function storePlacement(
3402
+ liveBrain: string,
3403
+ target: string,
3404
+ platform: NodeJS.Platform = process.platform,
3405
+ ): StorePlacement {
3406
+ const brain = canonicalPath(liveBrain, platform);
3407
+ // A path that resolves to `Brain/` itself is refused whatever its last
3408
+ // component is: a link to the directory is still the directory.
3409
+ if (compareKey(canonicalPath(target, platform), platform) === compareKey(brain, platform)) {
3410
+ return { kind: "brain" };
3411
+ }
3412
+ const store = entryPath(target, platform);
3413
+ const rel = relative(compareKey(brain, platform), compareKey(store, platform));
3414
+ if (rel === "") return { kind: "brain" };
3415
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return { kind: "outside" };
3416
+ // The relative path's components, in the target's own spelling.
3417
+ const parts = store.split(sep).slice(-rel.split(sep).length);
3418
+ // An entry the swap never touches (`.snapshots/`, `.artifacts/`) keeps
3419
+ // whatever it holds, so a store inside one does not meet the swap.
3420
+ if (isSnapshotExcludedEntry(parts[0]!)) return { kind: "outside" };
3421
+ return parts.length === 1 ? { kind: "top", base: parts[0]! } : { kind: "nested", top: parts[0]! };
3422
+ }
3423
+
3424
+ /**
3425
+ * Refuse a restore whose store target the swap cannot write around, before
3426
+ * anything is extracted or touched.
3427
+ *
3428
+ * A store inside a top-level `Brain/` entry: the Brain swap renames whole
3429
+ * top-level entries; the store swap renames one file. A store nested
3430
+ * inside a renamed directory would be moved out with the live directory,
3431
+ * its staged replacement with it, and the restored directory may not even
3432
+ * contain the store's parent. Carving the store out of that rename would
3433
+ * add a third set of renames, each with its own undo, to a swap whose
3434
+ * whole contract is that every step can be reversed; refusing up front
3435
+ * keeps that contract and loses nothing.
3436
+ *
3437
+ * A store target that is `Brain/` itself: the store swap would rename a
3438
+ * database file over the directory the tree swap is restoring into.
3439
+ */
3440
+ function refuseStoreTheSwapCannotWriteAround(
3441
+ placement: StorePlacement,
3442
+ target: string,
3443
+ runId: string,
3444
+ ): void {
3445
+ if (placement.kind === "brain") {
3446
+ throw new BrainSnapshotError(
3447
+ `the derived store path ${target} is the Brain/ directory itself; refusing before ` +
3448
+ "anything is touched. Point search_db_path at a file, directly under Brain/ or " +
3449
+ "outside it, then restore again",
3450
+ runId,
3451
+ );
3452
+ }
3453
+ if (placement.kind !== "nested") return;
3454
+ throw new BrainSnapshotError(
3455
+ `the derived store ${target} is inside Brain/${placement.top}, which a restore replaces ` +
3456
+ "as a whole; refusing before anything is touched. Move the store (search_db_path) " +
3457
+ "directly under Brain/ or outside it, then restore again",
3458
+ runId,
3459
+ );
3460
+ }
3461
+
3462
+ /** A decompressed and verified store, waiting beside its live target. */
3463
+ interface StagedDerivedStore {
3464
+ /** The live store path the staged file is renamed over. */
3465
+ readonly target: string;
3466
+ /** The staged file, on the target's filesystem. */
3467
+ readonly incoming: string;
3468
+ /** Remove the staged file if it is still there. Best-effort. */
3469
+ discard(): void;
3470
+ }
3471
+
3472
+ /**
3473
+ * Decide what the restore does with the derived store, and when the
3474
+ * manifest says the snapshot carried one, decompress and verify it next
3475
+ * to the live store - without touching the live store.
3476
+ *
3477
+ * Three answers, and the caller reports whichever it gets rather than
3478
+ * leaving any of them implicit:
3479
+ *
3480
+ * - the manifest records inclusion: decompress and verify here, swap
3481
+ * later in {@link commitDerivedStoreSwap};
3482
+ * - the manifest records an exclusion: nothing is touched, and the
3483
+ * named reason travels back;
3484
+ * - there is no record at all: coverage is UNKNOWN, and whether a
3485
+ * sibling archive is on disk travels back with it. A restore must not
3486
+ * guess in either direction here - replacing a live store on a hunch
3487
+ * destroys embeddings the archive never held, and reporting
3488
+ * "excluded" would claim a check that never ran. The archive probe is
3489
+ * what lets the caller say WHY the record is missing instead of
3490
+ * asserting the snapshot is older than the feature.
3491
+ *
3492
+ * Runs without the writer lock: the staged file has a name of its own
3493
+ * beside the store, and the lock is held only across the renames. The
3494
+ * recovery point the caller takes after this step snapshots the live
3495
+ * store under that same lock, so holding it here would deadlock.
3496
+ */
3497
+ function stageDerivedStore(
3498
+ vault: string,
3499
+ target: string,
3500
+ runId: string,
3501
+ ): { readonly result: RestoreDerivedStoreResult; readonly staged: StagedDerivedStore | null } {
3502
+ const record = readManifestSidecar(vault, runId)?.derived_store ?? null;
3503
+ // Probed once, for every branch, and deliberately independent of the
3504
+ // record: it is the only evidence that separates a snapshot with no
3505
+ // record from a snapshot whose record was lost after the archive landed.
3506
+ const storeArchivePresent = existsSync(snapshotStorePath(vault, runId));
3507
+ if (record === null) {
3508
+ return {
3509
+ result: Object.freeze({
3510
+ replaced: false,
3511
+ coverage_known: false,
3512
+ path: null,
3513
+ exclusion_reason: null,
3514
+ store_archive_present: storeArchivePresent,
3515
+ }),
3516
+ staged: null,
3517
+ };
3518
+ }
3519
+ if (!record.included) {
3520
+ return {
3521
+ result: Object.freeze({
3522
+ replaced: false,
3523
+ coverage_known: true,
3524
+ path: null,
3525
+ exclusion_reason: record.exclusion_reason,
3526
+ store_archive_present: storeArchivePresent,
3527
+ }),
3528
+ staged: null,
3529
+ };
3530
+ }
3531
+
3532
+ const archive = snapshotStorePath(vault, runId);
3533
+ // An absent archive is unreachable through `restoreSnapshot`, which
3534
+ // refuses it in its pre-flight; kept because a store swap must never
3535
+ // begin against an archive that is not there.
3536
+ // The archive must be a real file before anything reads it, the digest
3537
+ // check below included.
3538
+ if (lstatSync(archive, { throwIfNoEntry: false }) !== undefined) {
3539
+ assertRegularFile(archive, runId, "the derived-store archive");
3540
+ }
3541
+ const archiveProblem = derivedStoreArchiveProblem(vault, runId, record);
3542
+ if (archiveProblem !== null) {
3543
+ throw new BrainSnapshotError(
3544
+ `${archiveProblem}; refusing before the Brain tree is touched`,
3545
+ runId,
3546
+ );
3547
+ }
3548
+ mkdirSync(dirname(target), { recursive: true });
3549
+ // A name of this process's own: two restores staging at once must not
3550
+ // write into one file, and neither is under the lock yet.
3551
+ const incoming = `${target}${RESTORE_STAGING_SUFFIX}-${process.pid}-${randomBytes(4).toString("hex")}`;
3552
+ const discard = (): void => {
3553
+ for (const path of [incoming, ...WAL_SIBLING_SUFFIXES.map((s) => `${incoming}${s}`)]) {
3554
+ try {
3555
+ rmSync(path, { force: true });
3556
+ } catch {
3557
+ // best-effort: a leftover staged file is never opened as the store
3558
+ }
3559
+ }
3560
+ };
3561
+ try {
3562
+ decompressArchiveTo(archive, incoming, runId);
3563
+ try {
3564
+ assertStoreIsSound(incoming, runId);
3565
+ } catch (err) {
3566
+ throw new BrainSnapshotError(
3567
+ `the archived derived store failed verification after decompression: ${errorText(err)}`,
3568
+ runId,
3569
+ { cause: err },
3570
+ );
3571
+ }
3572
+ // Opening it for the check must not leave journal siblings to travel
3573
+ // with the rename; the decompressed file is complete on its own.
3574
+ for (const sidecar of WAL_SIBLING_SUFFIXES) rmSync(`${incoming}${sidecar}`, { force: true });
3575
+ } catch (err) {
3576
+ discard();
3577
+ if (err instanceof BrainSnapshotError || err instanceof BrainSnapshotToolingMissingError) {
3578
+ throw err;
3579
+ }
3580
+ throw new BrainSnapshotError(
3581
+ `failed to stage the derived store beside ${target}: ${errorText(err)}`,
3582
+ runId,
3583
+ { cause: err },
3584
+ );
3585
+ }
3586
+ return {
3587
+ result: Object.freeze({
3588
+ replaced: true,
3589
+ coverage_known: true,
3590
+ path: target,
3591
+ exclusion_reason: null,
3592
+ store_archive_present: true,
3593
+ }),
3594
+ staged: Object.freeze({ target, incoming, discard }),
3595
+ };
3596
+ }
3597
+
3598
+ /**
3599
+ * The store's writer lock, taken before the Brain swap starts. Holding it
3600
+ * across the renames is what stops an index run from writing into the
3601
+ * file being replaced; taking it BEFORE the first rename is what turns
3602
+ * contention into a refusal rather than a half-finished restore.
3603
+ *
3604
+ * The acquisition is the only place a {@link StoreLockToken} is minted:
3605
+ * the recovery point skips its own acquire for that token, live and on
3606
+ * the same path, and for nothing that merely names the path. The token
3607
+ * stops counting before the lock is released, so a reference kept past
3608
+ * the restore never stands in for a lock nobody holds.
3609
+ */
3610
+ function acquireStoreLockForRestore(
3611
+ target: string,
3612
+ runId: string,
3613
+ ): {
3614
+ readonly token: StoreLockToken;
3615
+ readonly lease: WriterLease;
3616
+ readonly release: () => void;
3617
+ } {
3618
+ let lease: WriterLease;
3619
+ try {
3620
+ lease = acquireWriterLeaseSync(target);
3621
+ } catch (err) {
3622
+ throw new BrainSnapshotError(
3623
+ `cannot take the derived store's writer lock (${errorText(err)}); refusing before the ` +
3624
+ "Brain tree is touched",
3625
+ runId,
3626
+ { cause: err },
3627
+ );
3628
+ }
3629
+ const token = new StoreLockToken(STORE_LOCK_TOKEN_MINT, target);
3630
+ liveStoreLockTokens.set(token, target);
3631
+ return {
3632
+ token,
3633
+ lease,
3634
+ release: (): void => {
3635
+ liveStoreLockTokens.delete(token);
3636
+ lease.release();
3637
+ },
3638
+ };
3639
+ }
3640
+
3641
+ /** Refuse the swap, with nothing touched, when the restore's lease was lost. */
3642
+ function assertStoreLeaseHeld(lease: WriterLease, runId: string): void {
3643
+ try {
3644
+ lease.assertHeld();
3645
+ } catch (err) {
3646
+ throw new BrainSnapshotError(
3647
+ `the derived store's writer lock was lost before the swap (${errorText(err)}); ` +
3648
+ "refusing before the Brain tree is touched",
3649
+ runId,
3650
+ { cause: err },
3651
+ );
3652
+ }
3653
+ }
3654
+
3655
+ /**
3656
+ * Refuse a swap whose recovery point archived a different store than the
3657
+ * one the swap replaces.
3658
+ *
3659
+ * The restore writes the snapshot's store to the live target it resolved
3660
+ * (an explicit `derivedStorePath`, or the search layer's answer). A
3661
+ * recovery point that resolved its own source - the configured store
3662
+ * rather than the override - would archive one file while the swap
3663
+ * discards another, and the discarded store would have no copy anywhere.
3664
+ * The manifest's `source_path` is what the recovery point actually
3665
+ * archived (or declined to), so that is what is compared. A recovery
3666
+ * point with no readable manifest is left to the recoverability verdict,
3667
+ * which already reads it as unproven.
3668
+ */
3669
+ function assertRecoveryPointCoversTarget(
3670
+ vault: string,
3671
+ evidence: RecoveryPointEvidence,
3672
+ target: string,
3673
+ runId: string,
3674
+ ): void {
3675
+ const record = readManifestSidecar(vault, evidence.runId)?.derived_store ?? null;
3676
+ if (record === null) return;
3677
+ if (record.source_path !== target) {
3678
+ throw new BrainSnapshotError(
3679
+ `the recovery point ${evidence.runId} recorded the derived store at ${record.source_path}, ` +
3680
+ `but this restore replaces ${target}; refusing before the Brain tree is touched, so the ` +
3681
+ "store being discarded is not left without a copy",
3682
+ runId,
3683
+ );
3684
+ }
3685
+ if (!record.included && liveStoreWorthPreserving(target)) {
3686
+ throw new BrainSnapshotError(
3687
+ `the recovery point ${evidence.runId} did not include the derived store at ${target}, ` +
3688
+ "which this restore replaces; refusing before the Brain tree is touched, so the store " +
3689
+ "being discarded is not left without a copy",
3690
+ runId,
3691
+ );
3692
+ }
3693
+ }
3694
+
3695
+ /**
3696
+ * Remove the outgoing store a committed restore parked at `.bak` when the
3697
+ * recovery point holds a copy of it: the manifest records the store as
3698
+ * included, from this very path, and the archive is on disk and matches
3699
+ * its recorded digest (`derivedStoreArchiveProblem`). The `.bak`
3700
+ * is then a second copy of an index that can be the size of the vault's
3701
+ * whole brain store, and the recovery point is the one that restores it
3702
+ * together with the `Brain/` tree it belongs to. Without such a recovery
3703
+ * point the `.bak` is the only copy, and it stays. Best effort: the
3704
+ * restore has committed, and a file that cannot be removed now (a reader
3705
+ * holding it on Windows) is removed by the next rebuild of the index.
3706
+ */
3707
+ function discardCoveredOutgoingStore(
3708
+ vault: string,
3709
+ evidence: RecoveryPointEvidence,
3710
+ target: string,
3711
+ outgoing: string,
3712
+ assertOwnership: () => void,
3713
+ ): void {
3714
+ const record = readManifestSidecar(vault, evidence.runId)?.derived_store ?? null;
3715
+ if (record === null || !record.included || record.source_path !== target) return;
3716
+ if (!existsSync(evidence.path)) return;
3717
+ // The copy is the derived-store archive, checked as a restore of the
3718
+ // recovery point would check it; one that is missing or does not match
3719
+ // its digest is no copy, and the outgoing store stays.
3720
+ if (derivedStoreArchiveProblem(vault, evidence.runId, record) !== null) return;
3721
+ for (const suffix of [...SQLITE_SIBLING_SUFFIXES, ""]) {
3722
+ try {
3723
+ assertOwnership();
3724
+ rmSync(outgoing + suffix, { force: true });
3725
+ } catch {
3726
+ // Left for the next rebuild, which removes a `.bak` it does not need.
3727
+ // A sibling left here without its main file is never adopted: every
3728
+ // swap removes the siblings at a free parked name before it parks
3729
+ // there, and refuses when it cannot.
3730
+ }
3731
+ }
3732
+ }
3733
+
3734
+ /**
3735
+ * Why the derived-store archive of `runId` cannot stand for the store its
3736
+ * manifest record names, or null when it can: the archive is on disk and,
3737
+ * when the record carries a digest, matches it. The one check both a
3738
+ * restore (before it swaps the archive in) and a committed restore (before
3739
+ * it removes the outgoing store the archive copies) rely on.
3740
+ */
3741
+ function derivedStoreArchiveProblem(
3742
+ vault: string,
3743
+ runId: string,
3744
+ record: { readonly archive_sha256: string | null },
3745
+ ): string | null {
3746
+ const archive = snapshotStorePath(vault, runId);
3747
+ if (!existsSync(archive)) {
3748
+ return `manifest records a derived-store archive but ${archive} is absent`;
3749
+ }
3750
+ if (record.archive_sha256 === null) return null;
3751
+ let actual: string;
3752
+ try {
3753
+ actual = sha256HexOfFile(archive);
3754
+ } catch (err) {
3755
+ return `the derived-store archive ${archive} could not be read (${errorText(err)})`;
3756
+ }
3757
+ if (actual === record.archive_sha256) return null;
3758
+ return (
3759
+ `the derived-store archive ${archive} does not match the digest its manifest recorded ` +
3760
+ `(${record.archive_sha256}, found ${actual})`
3761
+ );
3762
+ }
3763
+
3764
+ /**
3765
+ * Release the writer lock {@link acquireStoreLockForRestore} took.
3766
+ *
3767
+ * A failed release must not hide what happened before it. When the
3768
+ * restore already failed, that error stays the one thrown and the
3769
+ * release failure is appended to its message as a second line. When the
3770
+ * swap committed, the live tree and store are the snapshot's now, and the
3771
+ * error says so and names the recovery point, rather than reading like a
3772
+ * restore that changed nothing.
3773
+ */
3774
+ function releaseStoreLockAfterRestore(
3775
+ release: () => void,
3776
+ runId: string,
3777
+ committed: boolean,
3778
+ primary: { readonly err: unknown } | null,
3779
+ recoveryPoint: RecoveryPointEvidence | null,
3780
+ ): void {
3781
+ try {
3782
+ release();
3783
+ return;
3784
+ } catch (releaseErr) {
3785
+ const what = `releasing the derived store's writer lock failed (${errorText(releaseErr)})`;
3786
+ if (primary !== null) {
3787
+ // The primary error is rethrown by the caller's catch once this
3788
+ // finally returns; it only gains the release failure as a line.
3789
+ if (primary.err instanceof Error) {
3790
+ primary.err.message += `\nalso: ${what}`;
3791
+ } else {
3792
+ // A non-Error throw has no message to extend; the release failure
3793
+ // still must not vanish.
3794
+ console.error(`warning: ${what}`);
3795
+ }
3796
+ return;
3797
+ }
3798
+ if (committed) {
3799
+ const recovery =
3800
+ recoveryPoint === null
3801
+ ? "no recovery point was taken for this restore"
3802
+ : `the recovery point ${recoveryPoint.runId} (${recoveryPoint.path}) holds the ` +
3803
+ `pre-restore state; \`o2b brain rollback ${recoveryPoint.runId}\` puts it back`;
3804
+ throw new BrainSnapshotError(
3805
+ `the restore committed: Brain/ and the derived store now hold snapshot ${runId}, but ` +
3806
+ `${what}; the lock is stale-released after ${resolveWriterLockStaleMs()} ms; ${recovery}`,
3807
+ runId,
3808
+ { cause: releaseErr },
3809
+ );
3810
+ }
3811
+ // Unreachable: nothing failed and nothing committed means the try
3812
+ // block did not finish, which is a throw, which is `primary`.
3813
+ throw new BrainSnapshotError(`restore: ${what}`, runId, { cause: releaseErr });
3814
+ }
3815
+ }
3816
+
3817
+ /**
3818
+ * A store swap that failed between its two renames and could not put the
3819
+ * outgoing store back: the live path has no store, and the pre-restore
3820
+ * one is at the `.bak` path.
3821
+ */
3822
+ class StoreSwapTornError extends Error {
3823
+ constructor(message: string, options?: { readonly cause?: unknown }) {
3824
+ super(message, options);
3825
+ this.name = "StoreSwapTornError";
3826
+ }
3827
+ }
3828
+
3829
+ /**
3830
+ * Rename the staged store over the live one. The caller holds the writer
3831
+ * lock.
3832
+ *
3833
+ * The swap discipline every rename of one SQLite database over another
3834
+ * follows (`sqlite-file-set.ts`, shared with `reindexVault`): the live
3835
+ * store moves aside to `.bak` as a set - main file, then its `-wal`,
3836
+ * `-shm` and `-journal` - and the replacement is renamed in only over a
3837
+ * live path that has no sibling left. A sibling belongs to the database
3838
+ * whose name it carries: an outgoing `-wal` with committed frames, or a
3839
+ * hot rollback journal (DELETE journal mode, which the store uses on
3840
+ * remote filesystems), left at the live path would be replayed or rolled
3841
+ * back over the replacement on its next open, which corrupts it. Moved
3842
+ * with the store instead, the `.bak` keeps its own last commits. A
3843
+ * sibling with no live store beside it moves the same way. Any step that
3844
+ * fails undoes the swap, so the live store is untouched and the caller
3845
+ * undoes the Brain/ renames too; a {@link StoreSwapTornError} means even
3846
+ * the undo failed.
3847
+ */
3848
+ function commitDerivedStoreSwap(store: StagedDerivedStore, assertOwnership: () => void): string {
3849
+ const { target, incoming } = store;
3850
+ const outgoing = outgoingStorePath(target);
3851
+ // A free parked name holds no main file; journals of nothing found there
3852
+ // would be adopted by the store moved aside now, so they go first. An
3853
+ // earlier parked index is never replaced: it may be the only copy of
3854
+ // stored embeddings a rebuild could not recompute.
3855
+ for (const path of SQLITE_SIBLING_SUFFIXES.map((s) => outgoing + s)) {
3856
+ assertOwnership();
3857
+ rmSync(path, { force: true });
3858
+ }
3859
+ const hadStore = existsSync(target);
3860
+ // The same durable park record the reindex swap writes: a stop between
3861
+ // the renames below is reunited by it, not by parked-name order.
3862
+ assertOwnership();
3863
+ writeParkMarker(target, outgoing);
3864
+ try {
3865
+ parkSqliteFileSet(target, outgoing, undefined, assertOwnership);
3866
+ } catch (err) {
3867
+ const stranded = err instanceof SqliteFileSetMoveError ? err.stranded : [];
3868
+ if (stranded.length === 0) clearParkMarker(target);
3869
+ if (stranded.length > 0) {
3870
+ // The undo of the park failed too: the live store is not whole.
3871
+ throw new StoreSwapTornError(
3872
+ `${parkFailureMessage(err, target, outgoing)}; moving it back failed too, and ` +
3873
+ `${stranded.join(", ")} stays at ${stranded.length === 1 ? "that path" : "those paths"}` +
3874
+ (stranded.includes(outgoing)
3875
+ ? `: the pre-restore store stays at ${outgoing}, where the next store open restores it`
3876
+ : ""),
3877
+ { cause: err },
3878
+ );
3879
+ }
3880
+ throw new Error(parkFailureMessage(err, target, outgoing), { cause: err });
3881
+ }
3882
+ try {
3883
+ const stray = sqliteJournalsPresent(target);
3884
+ if (stray.length > 0) {
3885
+ throw new Error(
3886
+ `${stray.join(", ")} appeared beside the live store after it was moved aside; ` +
3887
+ "the restored store must not open beside it",
3888
+ );
3889
+ }
3890
+ assertOwnership();
3891
+ renameWithRetry(incoming, target);
3892
+ } catch (err) {
3893
+ putBackOutgoingStore(target, outgoing, hadStore, errorText(err), err, assertOwnership);
3894
+ clearParkMarker(target);
3895
+ throw err;
3896
+ }
3897
+ clearParkMarker(target);
3898
+ return outgoing;
3899
+ }
3900
+
3901
+ /**
3902
+ * Where the restore parks the live store: `.bak`, or `.old` when an
3903
+ * earlier parked index holds `.bak` (the rebuild's naming, which its crash
3904
+ * restore reads newest first). Both taken refuses before anything moves.
3905
+ */
3906
+ function outgoingStorePath(target: string): string {
3907
+ for (const suffix of [RESTORE_BACKUP_SUFFIX, ".old"]) {
3908
+ if (!existsSync(target + suffix)) return target + suffix;
3909
+ }
3910
+ throw new Error(
3911
+ `could not move the live store ${target} aside: earlier indexes are parked at both ` +
3912
+ `${target}${RESTORE_BACKUP_SUFFIX} and ${target}.old; the live store was not touched`,
3913
+ );
3914
+ }
3915
+
3916
+ /**
3917
+ * The message of a live store set that could not be moved aside: which
3918
+ * file failed and why. The caller adds what an undo that failed too left
3919
+ * moved ({@link SqliteFileSetMoveError.stranded}).
3920
+ */
3921
+ function parkFailureMessage(err: unknown, target: string, outgoing: string): string {
3922
+ const failed = err instanceof SqliteFileSetMoveError ? err.failedPath : target;
3923
+ const cause = errorText(err instanceof Error && err.cause !== undefined ? err.cause : err);
3924
+ if (failed === target) {
3925
+ return (
3926
+ `could not move the live store ${target} aside to ${outgoing}: ${cause}; ` +
3927
+ "the live store was not touched"
3928
+ );
3929
+ }
3930
+ const suffix = failed.slice(target.length);
3931
+ const what =
3932
+ suffix === ROLLBACK_JOURNAL_SUFFIX ? "the rollback journal" : "the write-ahead log file";
3933
+ return (
3934
+ `could not move ${what} ${failed} aside to ${outgoing}${suffix}: ${cause}; ` +
3935
+ "the restored store must not open beside it"
3936
+ );
3937
+ }
3938
+
3939
+ /**
3940
+ * Put the store set a failed swap step moved aside back at the live path
3941
+ * (siblings first, main file last, so the live path never holds the store
3942
+ * without its journal), or throw a {@link StoreSwapTornError} naming
3943
+ * where it was left.
3944
+ */
3945
+ function putBackOutgoingStore(
3946
+ target: string,
3947
+ outgoing: string,
3948
+ hadStore: boolean,
3949
+ what: string,
3950
+ cause: unknown,
3951
+ assertOwnership: () => void,
3952
+ ): void {
3953
+ try {
3954
+ unparkSqliteFileSet(outgoing, target, undefined, assertOwnership);
3955
+ } catch (backErr) {
3956
+ const moveError = backErr instanceof SqliteFileSetMoveError ? backErr : null;
3957
+ const failed = moveError?.failedPath ?? outgoing;
3958
+ const stranded = moveError?.stranded ?? [];
3959
+ const reason = errorText(
3960
+ backErr instanceof Error && backErr.cause !== undefined ? backErr.cause : backErr,
3961
+ );
3962
+ if (failed === outgoing) {
3963
+ throw new StoreSwapTornError(
3964
+ `${what}; the pre-restore store could not be renamed back either ` +
3965
+ `(${reason}) and is at ${outgoing}, where the next store open restores it` +
3966
+ (stranded.length > 0 ? `; stranded paths: ${stranded.join(", ")}` : ""),
3967
+ { cause },
3968
+ );
3969
+ }
3970
+ const kind = failed.endsWith(ROLLBACK_JOURNAL_SUFFIX)
3971
+ ? "the rollback journal"
3972
+ : "the write-ahead log file";
3973
+ throw new StoreSwapTornError(
3974
+ `${what}; ${kind} of the pre-restore store could not be renamed back ` +
3975
+ `(${reason}) and is at ${failed}` +
3976
+ (hadStore ? `; the pre-restore store is at ${outgoing}` : "") +
3977
+ (stranded.length > 0 ? `; stranded paths: ${stranded.join(", ")}` : ""),
3978
+ { cause },
3979
+ );
3980
+ }
3981
+ }
3982
+
3983
+ /** Staging name of the store being restored, beside its destination. */
3984
+ const RESTORE_STAGING_SUFFIX = ".restore";
3985
+ /**
3986
+ * The outgoing store, kept under the SAME `.bak` name the reindex swap
3987
+ * uses - so the crash-recovery preamble every `Store.open` runs restores
3988
+ * it if a rollback dies between the two renames.
3989
+ */
3990
+ const RESTORE_BACKUP_SUFFIX = ".bak";
3991
+ /** SQLite's rollback journal of a database file (DELETE journal mode). */
3992
+ const ROLLBACK_JOURNAL_SUFFIX = "-journal";
3993
+ /** SQLite's write-ahead-log siblings of a database file. */
3994
+ const WAL_SIBLING_SUFFIXES: ReadonlyArray<string> = Object.freeze(["-wal", "-shm"]);
3995
+
3996
+ /** Decompress a snapshot archive to `outPath`, probing the magic bytes. */
3997
+ function decompressArchiveTo(archive: string, outPath: string, runId: string): void {
3998
+ const tools = detectTooling();
3999
+ const compressor = detectArchiveCompression(archive);
4000
+ if (compressor === "zstd" && !tools.zstd) {
4001
+ throw new BrainSnapshotToolingMissingError(
4002
+ "zstd",
4003
+ "archive is zstd-compressed; install zstd to restore it.",
4004
+ );
4005
+ }
4006
+ if (compressor === "zstd") {
4007
+ // `zstd -o` opens the destination itself and refuses an existing one.
4008
+ runCompressor("zstd", ["-d", "-q", "-o", outPath, archive], runId);
4009
+ return;
4010
+ }
4011
+ // gzip is inflated in-process (no `gzip` binary on native Windows);
4012
+ // `wx` keeps the destination exclusive. The inflate is bounded: its
4013
+ // bytes are held in memory.
4014
+ const bytes = inflateGzipArchive(archive, runId);
4015
+ writeArchiveExclusive(outPath, bytes, runId);
4016
+ }
4017
+
4018
+ // ----- Helpers -------------------------------------------------------------
4019
+
4020
+ function detectArchiveCompression(archive: string): "zstd" | "gzip" {
4021
+ const buf = Buffer.alloc(4);
4022
+ const fd = openSync(archive, "r");
4023
+ try {
4024
+ readSync(fd, buf, 0, 4, 0);
4025
+ } finally {
4026
+ closeSync(fd);
4027
+ }
4028
+ // zstd magic: 0x28 0xB5 0x2F 0xFD (little-endian view of 0xFD2FB528).
4029
+ if (buf[0] === 0x28 && buf[1] === 0xb5 && buf[2] === 0x2f && buf[3] === 0xfd) {
4030
+ return "zstd";
4031
+ }
4032
+ // gzip magic: 0x1F 0x8B
4033
+ if (buf[0] === 0x1f && buf[1] === 0x8b) {
4034
+ return "gzip";
4035
+ }
4036
+ // Default to zstd since that's our preferred writer — restore will
4037
+ // fail loudly through the zstd subprocess if the bytes don't match.
4038
+ return "zstd";
4039
+ }
4040
+
4041
+ function countFiles(path: string): number {
4042
+ try {
4043
+ const st = statSync(path);
4044
+ if (st.isFile()) return 1;
4045
+ if (!st.isDirectory()) return 0;
4046
+ } catch {
4047
+ return 0;
4048
+ }
4049
+ let count = 0;
4050
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
4051
+ const sub = join(path, entry.name);
4052
+ if (entry.isDirectory()) {
4053
+ count += countFiles(sub);
4054
+ } else if (entry.isFile()) {
4055
+ count++;
4056
+ }
4057
+ }
4058
+ return count;
4059
+ }