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,3405 @@
1
+ /**
2
+ * Index lifecycle orchestrator.
3
+ *
4
+ * `indexVault` is the incremental path: walk → diff against stored
5
+ * documents → upsert/replace/delete. `reindexVault` is the atomic
6
+ * rebuild: write to `brain.sqlite.new`, then a same-file rename swap
7
+ * that parks the previous index at `.bak` until the new one is verified.
8
+ *
9
+ * `indexStatus`, `indexCheck`, `indexRootCoverage` and
10
+ * `indexBehindCount` are the read-side diagnostics that power
11
+ * `o2b search status|check`, the MCP status enrichment and the recall
12
+ * gate's coverage receipt.
13
+ *
14
+ * Anchored in docs/plans/2026-05-16-brain-search-design.md §6, §8,
15
+ * §13, §15.
16
+ */
17
+
18
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
19
+ import { basename, dirname } from "node:path";
20
+ import { Database } from "bun:sqlite";
21
+
22
+ import {
23
+ resolveSemanticCapability,
24
+ SEMANTIC_CAPABILITY_CODE,
25
+ SEMANTIC_CAPABILITY_TIER,
26
+ semanticCapabilityIsBlocked,
27
+ semanticCapabilityLabel,
28
+ SEMANTIC_VECTOR_CODE,
29
+ } from "./capability-tier.ts";
30
+ import { sha256Hex } from "../integrity/digest.ts";
31
+ import { parseAuthoredAtSeconds } from "./authored-at.ts";
32
+ import { CHUNKER_VERSION, chunkMarkdown } from "./chunker.ts";
33
+ import { expandTextForCjkFts } from "./cjk-tokenizer.ts";
34
+ import { effectiveInputWindowTokens, passagePrefixSentByProvider } from "./embeddings/presets.ts";
35
+ import {
36
+ activeEmbeddingModel,
37
+ activeSpendQuote,
38
+ chunkHoldExclusion,
39
+ COST_GATE_KEY,
40
+ EMBEDDING_GATE_REASON,
41
+ type EmbeddingGateReason,
42
+ type EmbeddingSpendPlan,
43
+ FORCE_COST_FLAG,
44
+ formatEstimatedUsd,
45
+ planEmbeddingSpend,
46
+ priceSpendPlan,
47
+ unpricedRefusalMessage,
48
+ } from "./embedding-spend.ts";
49
+ import { embeddingPriceRecommendations } from "./price-recommendations.ts";
50
+ import type { EmbeddingPriceSource } from "./embeddings/pricing.ts";
51
+ import { makeProvider } from "./embeddings/provider.ts";
52
+ import { resolveProviderConsent, providerConsentIsDeclined } from "./provider-consent.ts";
53
+ import {
54
+ embeddingSignature,
55
+ isStaleSignature,
56
+ MODEL_NATIVE_DIMENSION,
57
+ textExtent,
58
+ tokenHoldFloor,
59
+ type EmbeddingIdentity,
60
+ } from "./embeddings/signature.ts";
61
+ import { LOCAL_DEFAULT_DIMENSION } from "./embeddings/local-provider.ts";
62
+ import {
63
+ describeCredentialSources,
64
+ type CredentialSourceContext,
65
+ } from "./embeddings/credential-report.ts";
66
+ import { resolveEventAnchor } from "./event-anchor.ts";
67
+ import { extractLinks } from "./links.ts";
68
+ import { resolveDocumentEventTimeWindow } from "./pipeline/event-time.ts";
69
+ import {
70
+ probeProvider,
71
+ PROVIDER_PROBE,
72
+ PROVIDER_PROBE_NOT_CONFIGURED,
73
+ PROVIDER_PROBE_SKIPPED,
74
+ type ProviderProbeState,
75
+ } from "./provider-probe.ts";
76
+ import { extractFrontmatterRelations } from "../graph/frontmatter-relations.ts";
77
+ import { loadSchemaPack, type SchemaPack } from "../brain/schema-pack.ts";
78
+ import { tieredFieldsForKind } from "../brain/frontmatter-tiers.ts";
79
+ import { parsePinned } from "../brain/preference.ts";
80
+ import { normalizeSchemaToken } from "../brain/schema-vocab.ts";
81
+ import type { DegradationNotice } from "../integrity/degradation.ts";
82
+ import { parseFrontmatterTextWithNotices } from "../vault.ts";
83
+ import { appendMetric } from "../brain/metrics.ts";
84
+ import type { MaintenanceSpendReceipt } from "../brain/maintenance/journal.ts";
85
+ import {
86
+ OPERATION,
87
+ progressCounter,
88
+ withProgressAsync,
89
+ type ProgressCounter,
90
+ } from "../brain/progress.ts";
91
+ import { throwIfAborted } from "../brain/safeguard.ts";
92
+ import { extractEntities } from "./entities.ts";
93
+ import { compareStamps, formatStampMismatch, type StampMismatch } from "../integrity/stamp.ts";
94
+ import { pathCovers } from "../vault-scope/defaults.ts";
95
+
96
+ import {
97
+ acquireWriterLease,
98
+ type WriterLease,
99
+ keepWriterLeasesFresh,
100
+ WRITER_LEASE_BLOCKING_BUDGET_MS,
101
+ writerLeaseCheckIn,
102
+ } from "./store/writer-lock.ts";
103
+ import {
104
+ describeUnreadableIndex,
105
+ embeddingAbiFixCommand,
106
+ formatEmbedderRecordContradiction,
107
+ formatEmbeddingAbiDrift,
108
+ peekPendingVectorsSync,
109
+ peekVisibilityColumnCensus,
110
+ readEmbedderRecordCensusSync,
111
+ readEmbeddingAbiSync,
112
+ runtimeEmbeddingAbi,
113
+ indexedSnapshotStale,
114
+ Store,
115
+ CHUNKER_VERSION_STATE_KEY,
116
+ EMBEDDING_PREFIX_QUERY_STATE_KEY,
117
+ EMBEDDING_PREFIX_PASSAGE_STATE_KEY,
118
+ LAST_FULL_INDEX_AT_STATE_KEY,
119
+ LAST_INDEXED_AT_STATE_KEY,
120
+ LINK_RESOLUTION_PENDING_STATE_KEY,
121
+ } from "./store.ts";
122
+ import {
123
+ LATEST_SCHEMA_VERSION,
124
+ REINDEX_COMMAND,
125
+ documentAttributesFromFrontmatter,
126
+ readSchemaVersion,
127
+ } from "./schema.ts";
128
+ import { chunkWindowDiagnosticCode, CHUNK_HOLD_REASON, SearchError } from "./types.ts";
129
+ import { walkVault } from "./walker.ts";
130
+ import {
131
+ dropForgottenRecords,
132
+ forgetCatchUpState,
133
+ ingestStoreInto,
134
+ } from "./brain-store/catch-up.ts";
135
+ import {
136
+ IndexBuildRecorder,
137
+ stagingIndexPath,
138
+ sweepStagingClaims,
139
+ waitForStagingReaders,
140
+ } from "./build-progress.ts";
141
+ import { purgeStoreRecords } from "./brain-store/ingest.ts";
142
+ import { STORE_INDEX_GENERATION_KEY, STORE_RECORD_PATH_PREFIX } from "./brain-store/constants.ts";
143
+ import {
144
+ callableVisibilitySurfaces,
145
+ excludedCallableVisibilitySurfaces,
146
+ } from "./visibility-surface-registry.ts";
147
+ import type { ChunkInput, LinkInput } from "./store.ts";
148
+ import type { ChunkHoldExclusion, PendingVectorScope } from "./store/chunks.ts";
149
+ import type {
150
+ ChunkWindowCensus,
151
+ EmbedderRecordCensus,
152
+ HeldChunkRecord,
153
+ HeldChunkReport,
154
+ HeldChunkReportItem,
155
+ IndexCheckReport,
156
+ IndexStats,
157
+ IndexStatusSnapshot,
158
+ PendingVectorCensus,
159
+ ResolvedEmbeddingConfig,
160
+ ResolvedSearchConfig,
161
+ VisibilityHonestyFinding,
162
+ } from "./types.ts";
163
+ import type { ValidityWindow } from "./validity.ts";
164
+ import { REMOTE_DENY_VISIBILITY_TOKEN } from "../graph/visibility.ts";
165
+ import { remoteDenyVisibilityTokens } from "../graph/privacy-markers.ts";
166
+ import { closeDatabase } from "../sqlite-close.ts";
167
+ import { renameWithRetry, unlinkWithRetry } from "../fs-atomic.ts";
168
+ import {
169
+ discardSqliteFileSet,
170
+ parkSqliteFileSet,
171
+ sqliteJournalsPresent,
172
+ sqliteSiblingsPresent,
173
+ unparkSqliteFileSet,
174
+ } from "../sqlite-file-set.ts";
175
+ import {
176
+ clearParkMarker,
177
+ restoreParkedIndexUnderLock,
178
+ runIntegrityCheck,
179
+ writeParkMarker,
180
+ } from "./store/lifecycle.ts";
181
+ import {
182
+ countStoredEmbeddings,
183
+ keptParkedIndexes,
184
+ keptParkedReasons,
185
+ parkedIndexPaths,
186
+ parkedIndexReleaseStep,
187
+ parkedIndexStates,
188
+ plainParkedTarget,
189
+ unreadableParkedRefusal,
190
+ type KeptParkedIndex,
191
+ type ParkedIndexTarget,
192
+ } from "./parked-index.ts";
193
+ import { finishInterruptedSetAsides } from "./parked-set-aside.ts";
194
+ import { INTEGRITY_CHECKED_AT_STATE_KEY } from "./store/state.ts";
195
+
196
+ export { countStoredEmbeddings } from "./parked-index.ts";
197
+
198
+ // ─────────────────────────────────────────────────────────────────────────────
199
+
200
+ export interface IndexProgressEvent {
201
+ readonly path: string;
202
+ readonly kind: "added" | "updated" | "unchanged" | "deleted" | "error";
203
+ readonly message?: string;
204
+ }
205
+
206
+ export interface IndexVaultOptions {
207
+ readonly embeddings?: boolean;
208
+ /** When true, every file is reindexed even if hash + mtime match. */
209
+ readonly force?: boolean;
210
+ /** When true, bypass the embedding cost gate for this run. */
211
+ readonly forceCost?: boolean;
212
+ readonly onFile?: (event: IndexProgressEvent) => void;
213
+ /**
214
+ * Cooperative deadline (t_06784b8d): checkpointed once per walked
215
+ * file, so a tripped guard aborts between files - never mid-write.
216
+ */
217
+ readonly safeguard?: import("../brain/safeguard.ts").Safeguard;
218
+ /**
219
+ * On-demand cancellation (Indexer Durability suite). Checked at the
220
+ * same boundaries the deadline uses - between files and between embed
221
+ * batches, never mid-write. An aborted signal throws
222
+ * `SafeguardAbortError`; the deletion sweep runs only on full
223
+ * completion, so an aborted run leaves a consistent partial index.
224
+ */
225
+ readonly signal?: AbortSignal;
226
+ /**
227
+ * Live progress observer (nothing-runs-unwatched, U1). Distinct from
228
+ * {@link IndexVaultOptions.onFile}, which reports WHAT happened to each
229
+ * file for the `--verbose` human stream; this reports HOW FAR the run
230
+ * has got, in the one shape every long operation here uses.
231
+ *
232
+ * The walk phase carries no denominator and cannot: `walkVault` is a
233
+ * generator, and counting first costs a second full traversal. The
234
+ * embed phase carries one, because its pending list is an array.
235
+ */
236
+ readonly onProgress?: import("../brain/progress.ts").ProgressSink;
237
+ /**
238
+ * The index this run acts on, and the target a plain command acts on:
239
+ * the release step a run prints names the index the run names. Carried
240
+ * in by the caller (the command line, which knows the flags); a run
241
+ * without one names the plain command.
242
+ */
243
+ readonly target?: ParkedIndexTarget;
244
+ }
245
+
246
+ /** Site recorded on the frontmatter notices an index run collects. */
247
+ const INDEX_FRONTMATTER_SITE = "search.indexVault";
248
+
249
+ interface MutableStats {
250
+ added: number;
251
+ updated: number;
252
+ unchanged: number;
253
+ deleted: number;
254
+ chunksTotal: number;
255
+ embeddingsComputed: number;
256
+ embeddingsReused: number;
257
+ embeddingsRetries: number;
258
+ /** Held-back-over-window chunks (F2); frozen out of the stats when zero. */
259
+ embeddingsHeld: number;
260
+ heldChunks: HeldChunkRecord[];
261
+ errors: Array<{ readonly path: string; readonly message: string }>;
262
+ frontmatterNotices: DegradationNotice[];
263
+ relationViolations: IndexStats["relationViolations"];
264
+ tierDrift: IndexStats["tierDrift"];
265
+ aliasResolved: number;
266
+ linkResolutionSkipped: boolean;
267
+ eventAnchorsPending: number;
268
+ backend: IndexStats["backend"];
269
+ deferredReason: IndexStats["deferredReason"];
270
+ /** Null until the census runs, and null whenever it has nothing to report. */
271
+ chunkWindow: ChunkWindowCensus | null;
272
+ /**
273
+ * The embedding phase's own cost-gate result, set when that phase ran
274
+ * its census (t_9d155d0e). Undefined when nothing was pending or the
275
+ * phase never engaged; a phase that throws mid-spend leaves the run
276
+ * throwing, so a receipt can only ever be read off a completed pass.
277
+ */
278
+ spend: MaintenanceSpendReceipt | undefined;
279
+ }
280
+
281
+ function newStats(): MutableStats {
282
+ return {
283
+ added: 0,
284
+ updated: 0,
285
+ unchanged: 0,
286
+ deleted: 0,
287
+ chunksTotal: 0,
288
+ embeddingsComputed: 0,
289
+ embeddingsReused: 0,
290
+ embeddingsRetries: 0,
291
+ // Filled by the embedding phase only when it holds a chunk back;
292
+ // zero means the frozen stats carry neither hold field at all.
293
+ embeddingsHeld: 0,
294
+ heldChunks: [],
295
+ errors: [],
296
+ frontmatterNotices: [],
297
+ relationViolations: [],
298
+ tierDrift: [],
299
+ aliasResolved: 0,
300
+ linkResolutionSkipped: false,
301
+ // Counted at the end of the run, once every changed document has
302
+ // been upserted: what is left is what this run did not reach.
303
+ eventAnchorsPending: 0,
304
+ // Resolved lazily at the end of the run, after content detection.
305
+ // Defaults to the deterministic offline backend.
306
+ backend: "offline",
307
+ deferredReason: null,
308
+ // Taken at the end of the run, over the index the run left behind.
309
+ chunkWindow: null,
310
+ // Set by the embedding phase when it ran its census; absent otherwise.
311
+ spend: undefined,
312
+ };
313
+ }
314
+
315
+ /**
316
+ * The spend receipt an index run's embedding phase recorded, if any.
317
+ * Present only when a phase ran over a non-empty pending census and the
318
+ * run completed - a run that threw has no stats to read, and the lane
319
+ * journaling the receipt must not price a pass it cannot vouch for.
320
+ * The field's declared home is `IndexStats.spend`; this accessor keeps
321
+ * the "completed run only" reading in one named place.
322
+ */
323
+ export function embeddingSpendOf(stats: IndexStats): MaintenanceSpendReceipt | undefined {
324
+ return stats.spend;
325
+ }
326
+
327
+ function freezeStats(s: MutableStats, durationMs: number): IndexStats {
328
+ return Object.freeze({
329
+ added: s.added,
330
+ updated: s.updated,
331
+ unchanged: s.unchanged,
332
+ deleted: s.deleted,
333
+ chunksTotal: s.chunksTotal,
334
+ embeddingsComputed: s.embeddingsComputed,
335
+ embeddingsReused: s.embeddingsReused,
336
+ embeddingsRetries: s.embeddingsRetries,
337
+ // Absent together, never one without the other: a run that held
338
+ // nothing emits the statistics it emitted before the hold existed.
339
+ ...(s.embeddingsHeld === 0
340
+ ? {}
341
+ : { embeddingsHeld: s.embeddingsHeld, heldChunks: Object.freeze([...s.heldChunks]) }),
342
+ errors: Object.freeze([...s.errors]),
343
+ frontmatterNotices: Object.freeze([...s.frontmatterNotices]),
344
+ relationViolations: Object.freeze([...s.relationViolations]),
345
+ tierDrift: Object.freeze([...s.tierDrift]),
346
+ aliasResolved: s.aliasResolved,
347
+ linkResolutionSkipped: s.linkResolutionSkipped,
348
+ eventAnchorsPending: s.eventAnchorsPending,
349
+ backend: s.backend,
350
+ deferredReason: s.deferredReason,
351
+ // Absent, not null, when the census has nothing to report: a run
352
+ // with no oversize chunks and a declared window produces the exact
353
+ // statistics object it produced before this field existed.
354
+ ...(s.chunkWindow === null ? {} : { chunkWindow: s.chunkWindow }),
355
+ // Same additive-absent convention: a run whose embedding phase did
356
+ // not engage carries no receipt.
357
+ ...(s.spend === undefined ? {} : { spend: s.spend }),
358
+ durationMs,
359
+ });
360
+ }
361
+
362
+ /**
363
+ * Explain why the semantic backend was not engaged, inspecting only the
364
+ * already-resolved config (never `process.env`).
365
+ *
366
+ * The sentence is the diagnostics registry's, resolved from a REGISTERED
367
+ * code through the advisory rail (provenance-at-the-boundary, F1). It
368
+ * used to be assembled here from four hand-written branches, which is the
369
+ * one thing the v1.40.0 rail exists to stop.
370
+ *
371
+ * Two of those branches are now the shared capability tier. The third -
372
+ * a fully configured vault that simply was not asked for embeddings this
373
+ * run - is an INDEX state rather than a capability fault and carries its
374
+ * own code, whose registered exit is the vector backfill verb. The
375
+ * fourth was unreachable: the only call site passed a constant `false`
376
+ * for `embeddingsRequested`, because the caller reaches this function
377
+ * exclusively on the else-arm of `if (opts?.embeddings)`. The parameter
378
+ * and the branch are gone rather than kept as a shape that could never
379
+ * be observed.
380
+ */
381
+ async function offlineDeferredReason(config: ResolvedSearchConfig): Promise<string> {
382
+ const capability = resolveSemanticCapability(config.semantic);
383
+ return semanticCapabilityLabel(
384
+ semanticCapabilityIsBlocked(capability) ? capability.code : SEMANTIC_VECTOR_CODE.deferred,
385
+ );
386
+ }
387
+
388
+ /** Deep-ish equality for frontmatter scalar/array values. */
389
+ function tierValueEquals(left: unknown, right: unknown): boolean {
390
+ if (Array.isArray(left) && Array.isArray(right)) {
391
+ return left.length === right.length && left.every((v, i) => tierValueEquals(v, right[i]));
392
+ }
393
+ return left === right;
394
+ }
395
+
396
+ /**
397
+ * The page's declared frontmatter `type` as a normalized token, or
398
+ * null when undeclared or not a usable scalar. Tolerant by design:
399
+ * a malformed `type` value never fails indexing, it just leaves the
400
+ * page untyped for constraint purposes.
401
+ */
402
+ function pageTypeFromFrontmatter(frontmatter: Record<string, unknown>): string | null {
403
+ const raw = frontmatter["type"];
404
+ if (typeof raw !== "string") return null;
405
+ const normalized = normalizeSchemaToken(raw);
406
+ return normalized.length > 0 ? normalized : null;
407
+ }
408
+
409
+ /**
410
+ * The page's declared frontmatter `aliases` as raw strings (the store
411
+ * normalises). Tolerant by design: a non-array value or non-string
412
+ * entries never fail indexing, they are simply skipped.
413
+ */
414
+ function aliasesFromFrontmatter(frontmatter: Record<string, unknown>): string[] {
415
+ const raw = frontmatter["aliases"];
416
+ if (!Array.isArray(raw)) return [];
417
+ return raw.filter((v): v is string => typeof v === "string");
418
+ }
419
+
420
+ /**
421
+ * The persisted half of the shared event-time resolution (v13,
422
+ * t_9e1a4b3f): the two column bounds for the window
423
+ * `resolveDocumentEventTimeWindow` resolved under the rung order the
424
+ * query side applies.
425
+ *
426
+ * A null window (nothing declared anywhere) and an INVALID declared
427
+ * window (a `valid_from`/`valid_until` that failed to parse) both persist
428
+ * null/null - the unmeasured state, because that is exactly how
429
+ * `eventTimeInRange` judges both: by storage mtime. Persisting anything
430
+ * else for a broken declaration would make the census disagree with what
431
+ * queries actually apply. A null SIDE on a valid window is a declared
432
+ * open one, and is persisted as the null it is.
433
+ */
434
+ function persistedEventTimeBounds(window: ValidityWindow | null): {
435
+ eventTimeMinMs: number | null;
436
+ eventTimeMaxMs: number | null;
437
+ } {
438
+ if (window === null || window.invalid) {
439
+ return { eventTimeMinMs: null, eventTimeMaxMs: null };
440
+ }
441
+ return { eventTimeMinMs: window.validFromMs, eventTimeMaxMs: window.validUntilMs };
442
+ }
443
+
444
+ /**
445
+ * The note's `authored_at` frontmatter instant as unix seconds, or null
446
+ * when undeclared, unparseable, or not usable as an authoring instant
447
+ * (conversation chronology, S1). Tolerant by design: a malformed value never
448
+ * fails indexing, it just leaves the document with no turn instant so it
449
+ * ranks byte-identically.
450
+ *
451
+ * This key is read off EVERY indexed markdown file - not only the artifacts
452
+ * session import and the inbox backfill write - so the rule that decides
453
+ * what counts as an authoring instant lives in `authored-at.ts` and is
454
+ * enforced HERE, at the boundary that fills the column, rather than being
455
+ * re-derived by each consumer of it. See {@link usableAuthoredAtSeconds} for
456
+ * the two refusals (pre-epoch sentinel, and an instant later than the moment
457
+ * the indexer read the file).
458
+ */
459
+ function authoredAtFromFrontmatter(
460
+ frontmatter: Record<string, unknown>,
461
+ nowMs: number,
462
+ ): number | null {
463
+ return parseAuthoredAtSeconds(frontmatter["authored_at"], nowMs);
464
+ }
465
+
466
+ const UTF8_FATAL = new TextDecoder("utf-8", { fatal: true });
467
+
468
+ function readUtf8(absPath: string): string {
469
+ const buf = readFileSync(absPath);
470
+ try {
471
+ return UTF8_FATAL.decode(buf);
472
+ } catch (e) {
473
+ const msg = e instanceof Error ? e.message : String(e);
474
+ throw new SearchError("INVALID_INPUT", `file is not valid UTF-8: ${absPath} (${msg})`);
475
+ }
476
+ }
477
+
478
+ // ─────────────────────────────────────────────────────────────────────────────
479
+ // indexVault — incremental
480
+ // ─────────────────────────────────────────────────────────────────────────────
481
+
482
+ /**
483
+ * Refuse a vault root that is not an existing directory.
484
+ *
485
+ * Both builds create the index directory under the vault (`mkdir -p` on
486
+ * `dirname(dbPath)`) and write metrics rows into `Brain/metrics`. Without
487
+ * this check a build pointed at a vault that is not there - a mistyped
488
+ * `--vault`, or a vault moved or deleted while a detached self-heal
489
+ * reindex was starting up - recreated the vault directory, filled it with
490
+ * an empty index and reported "added: 0 files" with exit 0.
491
+ */
492
+ function assertVaultDirectory(vault: string | null): void {
493
+ // No vault: the index holds the brain store only, and there is nothing to check.
494
+ if (vault === null) return;
495
+ let isDir = false;
496
+ try {
497
+ isDir = statSync(vault).isDirectory();
498
+ } catch (err) {
499
+ // Only a failed look that proves the path absent is "not found"; a
500
+ // permission or I/O fault is named, so the operator fixes the fault
501
+ // instead of looking for a moved vault.
502
+ const code = (err as NodeJS.ErrnoException).code;
503
+ if (code === "ENOENT" || code === "ENOTDIR") {
504
+ throw new SearchError("INVALID_INPUT", `vault not found: ${vault}`);
505
+ }
506
+ throw new SearchError(
507
+ "INVALID_INPUT",
508
+ `vault cannot be examined (${code ?? (err as Error).message}): ${vault}`,
509
+ );
510
+ }
511
+ if (!isDir) {
512
+ throw new SearchError("INVALID_INPUT", `vault path is not a directory: ${vault}`);
513
+ }
514
+ }
515
+
516
+ export async function indexVault(
517
+ config: ResolvedSearchConfig,
518
+ opts?: IndexVaultOptions,
519
+ ): Promise<IndexStats> {
520
+ return indexInto(config, opts);
521
+ }
522
+
523
+ /**
524
+ * @param outerProgress The RUN's counter when the caller owns it.
525
+ * `reindexVault` does, because its run is not over when this build is:
526
+ * the rebuild only becomes real at the swap. A build reporting into a
527
+ * borrowed counter must not terminate it - the owner does that, on the
528
+ * far side of the work this build does not know about.
529
+ */
530
+ async function indexInto(
531
+ config: ResolvedSearchConfig,
532
+ opts?: IndexVaultOptions,
533
+ storeOverride?: Store,
534
+ outerProgress?: ProgressCounter,
535
+ ): Promise<IndexStats> {
536
+ if (outerProgress !== undefined) {
537
+ outerProgress.start(INDEX_STAGE.walk);
538
+ return await indexIntoRun(config, outerProgress, opts, storeOverride);
539
+ }
540
+ const progress = progressCounter(OPERATION.reindex, opts?.onProgress);
541
+ progress.start(INDEX_STAGE.walk);
542
+ return await withProgressAsync(progress, () =>
543
+ indexIntoRun(config, progress, opts, storeOverride),
544
+ );
545
+ }
546
+
547
+ async function indexIntoRun(
548
+ config: ResolvedSearchConfig,
549
+ progress: ProgressCounter,
550
+ opts?: IndexVaultOptions,
551
+ storeOverride?: Store,
552
+ ): Promise<IndexStats> {
553
+ assertVaultDirectory(config.vault);
554
+ const t0 = Date.now();
555
+ const ownsStore = !storeOverride;
556
+ const store = storeOverride ?? (await Store.open(config, { mode: "write" }));
557
+ const stats = newStats();
558
+ let linkResolutionMarked = false;
559
+ const markLinkResolutionPending = (): void => {
560
+ if (linkResolutionMarked) return;
561
+ linkResolutionMarked = true;
562
+ store.setState(LINK_RESOLUTION_PENDING_STATE_KEY, "1");
563
+ };
564
+
565
+ try {
566
+ const existing = store.listDocuments();
567
+ // An empty index holds nothing cut by older chunking rules, and every
568
+ // chunk this run writes is cut by the current ones: stamp it now, so
569
+ // an interrupted build that is resumed later is not mistaken for a
570
+ // stale one. See CHUNKER_VERSION_STATE_KEY for when else it is written.
571
+ if (existing.size === 0) {
572
+ store.setState(CHUNKER_VERSION_STATE_KEY, String(CHUNKER_VERSION));
573
+ }
574
+ const seen = new Set<string>();
575
+ // Changed docs declaring a frontmatter `kind`, for the tier-guard
576
+ // post-pass (write-time-integrity-governance).
577
+ const tieredDocs: Array<{
578
+ docId: number;
579
+ relPath: string;
580
+ frontmatter: Record<string, unknown>;
581
+ }> = [];
582
+
583
+ for (const file of walkVault(config)) {
584
+ // Cooperative deadline: abort between files, never mid-write.
585
+ // Per-file document upserts are transactional, so a tripped
586
+ // guard leaves a consistent (partially refreshed) index.
587
+ opts?.safeguard?.checkpoint();
588
+ // The walk is synchronous between embed batches, so the lock's
589
+ // event-loop heartbeat cannot fire during it; this beats instead.
590
+ writerLeaseCheckIn();
591
+ progress.advance(INDEX_STAGE.walk);
592
+ // On-demand cancellation, same boundary as the deadline.
593
+ throwIfAborted(opts?.signal, "index");
594
+ // Mark seen FIRST. If anything downstream throws (read fault,
595
+ // chunker bug, transient FS error), the file must not look
596
+ // "missing" to the deletion sweep below — that would wipe a
597
+ // present file from the index just because a single read failed.
598
+ seen.add(file.relPath);
599
+ try {
600
+ const mtimeSec = Math.floor(file.stat.mtimeMs / 1000);
601
+ const size = file.stat.size;
602
+ const prev = existing.get(file.relPath);
603
+
604
+ // Fastpath: if mtime and size both match, skip the full
605
+ // content read + SHA256 hash. This is the same trade-off
606
+ // as `make`, with git's racily clean rule on top: a row
607
+ // indexed within the racy window of the file's mtime does not
608
+ // vouch for the bytes (a same-size edit in the same second
609
+ // keeps both), so that file is read and hashed again
610
+ // (`indexedSnapshotStale`).
611
+ if (!opts?.force && prev && !indexedSnapshotStale(prev, file.stat)) {
612
+ stats.unchanged++;
613
+ opts?.onFile?.({ path: file.relPath, kind: "unchanged" });
614
+ continue;
615
+ }
616
+
617
+ const content = readUtf8(file.absPath);
618
+ // Reading (and below, chunking) one large note can take a while:
619
+ // the lease is checked again before this file's first write, so a
620
+ // write store that lost its lock meanwhile stops here.
621
+ writerLeaseCheckIn();
622
+ const contentHash = sha256Hex(content);
623
+
624
+ // Fallback: fastpath missed (mtime or size changed). If
625
+ // the content hash still matches, the file is logically
626
+ // unchanged — update stored mtime/size to re-arm the
627
+ // fastpath on the next run, but skip chunk/link work.
628
+ if (!opts?.force && prev && prev.contentHash === contentHash) {
629
+ stats.unchanged++;
630
+ // Re-arm the fastpath: store the current stat so next
631
+ // run can skip the read entirely.
632
+ store.touchDocument(file.relPath, mtimeSec, size, file.observedAtMs);
633
+ opts?.onFile?.({ path: file.relPath, kind: "unchanged" });
634
+ continue;
635
+ }
636
+
637
+ markLinkResolutionPending();
638
+ const filenameBase = basename(file.relPath, ".md");
639
+ const chunkResult = chunkMarkdown(content, filenameBase, {
640
+ maxTokens: config.chunkSize,
641
+ minTokens: config.chunkMinSize,
642
+ overlapTokens: config.chunkOverlap,
643
+ });
644
+ for (const w of chunkResult.warnings) {
645
+ stats.errors.push({ path: file.relPath, message: w });
646
+ }
647
+
648
+ // The document's declared frontmatter `type` is persisted so
649
+ // the link-constraint post-pass can join endpoint types
650
+ // without re-reading files (v6).
651
+ // Unit F: the scanner drops a line it cannot express instead of
652
+ // failing, so a note keeps indexing while a field silently
653
+ // vanishes. Collect what it dropped; the run reports it and
654
+ // nothing about the indexing changes.
655
+ const [frontmatter, body, fmNotices] = parseFrontmatterTextWithNotices(content, {
656
+ site: INDEX_FRONTMATTER_SITE,
657
+ path: file.relPath,
658
+ });
659
+ for (const n of fmNotices) stats.frontmatterNotices.push(n);
660
+ // Resolved once, consumed twice: the materialised anchor column
661
+ // and the resolved event-time window below must come from the
662
+ // same anchor answer.
663
+ const eventAnchor = resolveEventAnchor(frontmatter, body);
664
+ writerLeaseCheckIn();
665
+ const docId = store.upsertDocument({
666
+ path: file.relPath,
667
+ title: chunkResult.title,
668
+ contentHash,
669
+ mtime: mtimeSec,
670
+ size: file.stat.size,
671
+ // When the walk observed the file (before its stat): the row
672
+ // proves the fingerprint only as of then (`indexedSnapshotStale`).
673
+ observedAtMs: file.observedAtMs,
674
+ pageType: pageTypeFromFrontmatter(frontmatter),
675
+ // `t0` - the instant this run started - is the reading clock the
676
+ // "not later than the read" refusal measures against. One clock
677
+ // for the whole run, so two files with the same declared instant
678
+ // resolve identically however long the run takes.
679
+ authoredAt: authoredAtFromFrontmatter(frontmatter, t0),
680
+ // The event anchor is materialised HERE, on the same pass that
681
+ // already holds the parsed frontmatter and the body, so the
682
+ // query side never re-scans a candidate's body. It is a pure
683
+ // function of this file's content, which is exactly what makes
684
+ // it safe to store behind the two content-identity fastpaths
685
+ // above: unchanged content can only ever resolve to the same
686
+ // anchor, so declining to recompute it cannot stale it.
687
+ eventAnchor,
688
+ // The document's RESOLVED event-time window (v13,
689
+ // t_9e1a4b3f), resolved from the already-parsed frontmatter
690
+ // and the materialised anchor above through the SHARED
691
+ // per-document resolver - the query side's own rung order, so
692
+ // the persisted bounds and the filter that consumes them
693
+ // cannot drift. Like the anchor, a pure function of this
694
+ // file's content, safe behind the same fastpaths; bounds
695
+ // refresh on each document's next content change, which is
696
+ // the lazy backfill the migration plans for.
697
+ ...persistedEventTimeBounds(resolveDocumentEventTimeWindow(frontmatter, eventAnchor)),
698
+ // What this run MEASURED of the page's `pinned` frontmatter
699
+ // flag (t_f7bef96a), coerced by the preference parser's own
700
+ // rule so ranking and the preference flows read one
701
+ // spelling. Every upserted document is measured; the column's
702
+ // NULL state is reserved for rows the v13 migration carried
703
+ // over and no run has re-examined yet.
704
+ pinned: parsePinned(frontmatter),
705
+ // What this run MEASURED of the page's visibility declaration,
706
+ // from the frontmatter already parsed above (v12). The indexer
707
+ // marks; it never skips. A `continue` here would be a live
708
+ // defect: `seen.add` runs BEFORE the content is read, so the
709
+ // deletion sweep would not purge a skipped page's stale rows and
710
+ // the page would keep whatever chunks it already had.
711
+ //
712
+ // The measurement is the UNION of the declared `visibility:`
713
+ // tokens and any informal privacy marker's reservation
714
+ // (`graph/privacy-markers.ts`), because the column is what a read
715
+ // root consults for bytes already captured: stamping the
716
+ // declaration alone would let a page reserved by
717
+ // `access: private` serve its snippet remotely after the file
718
+ // changed.
719
+ visibility: remoteDenyVisibilityTokens(frontmatter),
720
+ });
721
+ // Framework-kind files feed the tier-guard post-pass: keep the
722
+ // parsed frontmatter of this run's changed docs that declare a
723
+ // `kind` (bounded - only Brain artifacts carry one).
724
+ if (typeof frontmatter["kind"] === "string" && frontmatter["kind"].length > 0) {
725
+ tieredDocs.push({ docId, relPath: file.relPath, frontmatter });
726
+ }
727
+ // Vault-wide alias resolution (v7): replace this document's
728
+ // declared aliases so the post-pass can materialize alias
729
+ // wikilink targets.
730
+ store.replaceDocAliases(docId, aliasesFromFrontmatter(frontmatter));
731
+ // Bounded frontmatter attributes (v14, t_82851eda): replace this
732
+ // document's side-table rows from the SAME parsed frontmatter
733
+ // above - the parse that already fed the degradation notices, so
734
+ // an unterminated block yields no attributes and records no new
735
+ // notice. The extractor owns the promoted-key skips and the
736
+ // bounds; this call is a pure writer. Only a content change
737
+ // reaches this line, so the write cost rides the same lazy
738
+ // refresh every other materialized column pays.
739
+ store.replaceDocumentAttributes(docId, documentAttributesFromFrontmatter(frontmatter));
740
+
741
+ const chunkInputs: ChunkInput[] = chunkResult.chunks.map((c) => ({
742
+ chunkIndex: c.chunkIndex,
743
+ content: c.content,
744
+ ftsContent: expandTextForCjkFts(c.content),
745
+ contentHash: sha256Hex(c.content),
746
+ startLine: c.startLine,
747
+ endLine: c.endLine,
748
+ tokenCount: c.tokenCount,
749
+ headingPath: c.headingPath,
750
+ }));
751
+ // An unchanged chunk is kept in place, and a moved one carries its
752
+ // stored vector, so the embedding phase below never re-pays for it.
753
+ const replaced = store.replaceDocumentChunks(docId, chunkInputs);
754
+ const chunkIds = replaced.chunkIds;
755
+ stats.embeddingsReused += replaced.embeddingsReused;
756
+
757
+ const links: LinkInput[] = [];
758
+ for (let i = 0; i < chunkResult.chunks.length; i++) {
759
+ const cid = chunkIds[i]!;
760
+ const content = chunkResult.chunks[i]!.content;
761
+ const extracted = extractLinks(content);
762
+ for (const l of extracted) {
763
+ links.push({
764
+ sourceChunkId: cid,
765
+ targetPath: l.targetPath,
766
+ linkText: l.linkText,
767
+ linkType: l.linkType,
768
+ });
769
+ }
770
+ // Entity-boosted retrieval (v0.13.0): persist the chunk's
771
+ // deterministic entity set alongside its links. A chunk kept in
772
+ // place has the entities of the content it still holds - so a
773
+ // release that changes `extractEntities` must bump CHUNKER_VERSION,
774
+ // which rebuilds every chunk, or kept rows keep the old entities.
775
+ if (!replaced.keptChunkIds.has(cid)) store.replaceEntities(cid, extractEntities(content));
776
+ }
777
+ // Typed graph semantics (v3): frontmatter relation fields
778
+ // (related / extends / contradicts / superseded_by) become typed
779
+ // edges. They belong to the document, not a chunk, so anchor them
780
+ // on the first chunk (or null when the doc produced no chunks).
781
+ const relationChunkId = chunkIds[0] ?? null;
782
+ for (const edge of extractFrontmatterRelations(frontmatter)) {
783
+ links.push({
784
+ sourceChunkId: relationChunkId,
785
+ targetPath: edge.target,
786
+ linkText: null,
787
+ linkType: "wikilink",
788
+ relation: edge.relation,
789
+ });
790
+ }
791
+ store.replaceLinks(docId, links);
792
+
793
+ stats.chunksTotal += chunkInputs.length;
794
+ if (!prev) {
795
+ stats.added++;
796
+ opts?.onFile?.({ path: file.relPath, kind: "added" });
797
+ } else {
798
+ stats.updated++;
799
+ opts?.onFile?.({ path: file.relPath, kind: "updated" });
800
+ }
801
+ } catch (e) {
802
+ // A lost writer lock is the run's end, not this file's error.
803
+ if (e instanceof SearchError && e.code === "INDEX_LOCKED") throw e;
804
+ const msg = e instanceof Error ? e.message : String(e);
805
+ stats.errors.push({ path: file.relPath, message: msg });
806
+ opts?.onFile?.({ path: file.relPath, kind: "error", message: msg });
807
+ }
808
+ }
809
+
810
+ for (const [path] of existing) {
811
+ writerLeaseCheckIn();
812
+ if (!seen.has(path)) {
813
+ markLinkResolutionPending();
814
+ store.deleteDocument(path);
815
+ stats.deleted++;
816
+ opts?.onFile?.({ path, kind: "deleted" });
817
+ }
818
+ }
819
+ // Store records are left out of the sweep above; an index whose vault
820
+ // reads no store any more drops them here (design D5). A run that
821
+ // could not tell whether a store is in use keeps them: a store.json a
822
+ // sync tool is rewriting would otherwise cost a re-read of every shard.
823
+ if (!config.brainStore && config.brainStoreUnknown !== true) {
824
+ const purged = purgeStoreRecords(store);
825
+ if (purged !== null) {
826
+ forgetCatchUpState(config.dbPath);
827
+ if (purged > 0) markLinkResolutionPending();
828
+ stats.deleted += purged;
829
+ }
830
+ }
831
+
832
+ // Link and alias resolution are a pure function of the documents and
833
+ // their links. A run that changed no document (and was not forced)
834
+ // would only rewrite every link row to the value it already holds -
835
+ // the alias pass resets and re-sets each alias-resolved link - which
836
+ // is what made a no-change run write to disk. Skipped then; the
837
+ // constraint and tier passes below still run.
838
+ // A run killed between its document writes and this point leaves the
839
+ // pending marker set, and the next run resolves even if it changes
840
+ // nothing itself.
841
+ if (
842
+ stats.added + stats.updated + stats.deleted === 0 &&
843
+ opts?.force !== true &&
844
+ store.getState(LINK_RESOLUTION_PENDING_STATE_KEY) !== "1"
845
+ ) {
846
+ stats.linkResolutionSkipped = true;
847
+ } else {
848
+ // Whole-table statements that block for as long as the index is
849
+ // large: the writer lock is kept fresh off this thread meanwhile.
850
+ stats.aliasResolved = keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () => {
851
+ store.resolveLinkTargets();
852
+ // Alias post-pass (v7): exact path matches above always win; this
853
+ // only fills still-unresolved slash-free targets from doc_aliases.
854
+ return store.resolveAliasTargets();
855
+ });
856
+ store.setState(LINK_RESOLUTION_PENDING_STATE_KEY, "0");
857
+ }
858
+
859
+ // Link-constraint materialization post-pass
860
+ // (write-time-integrity-governance): recompute every typed edge's
861
+ // blocked flag from the current schema pack. Runs every pass - with
862
+ // no constraints declared it only resets stale flags, so removing a
863
+ // constraint restores edges without touching files. Fail-soft: an
864
+ // unparseable pack indexes as if no constraints were declared.
865
+ let pack: SchemaPack | null = null;
866
+ try {
867
+ pack = loadSchemaPack(config.vault);
868
+ } catch (e) {
869
+ const msg = e instanceof Error ? e.message : String(e);
870
+ stats.errors.push({ path: "Brain/_brain.yaml", message: `schema pack unreadable: ${msg}` });
871
+ }
872
+ stats.relationViolations = Object.freeze(
873
+ keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () =>
874
+ store.recomputeRelationConstraintFlags(pack?.link_constraints ?? {}),
875
+ ),
876
+ );
877
+
878
+ // Tier-guard post-pass: for each changed framework-kind doc,
879
+ // compare the new identity-field values against the stored
880
+ // snapshot. A changed identity value stages a tier_drift finding
881
+ // (ask_user via `o2b brain tiers check|restore|accept`) and the
882
+ // snapshot keeps the expected value so repeated reindexes never
883
+ // absorb the hand-edit; system/business fields update silently -
884
+ // framework writers mutate them legitimately on every pass.
885
+ if (pack !== null) {
886
+ const detectedAt = new Date().toISOString();
887
+ for (const doc of tieredDocs) {
888
+ const kind = doc.frontmatter["kind"];
889
+ if (typeof kind !== "string") continue;
890
+ const fields = tieredFieldsForKind(pack, kind);
891
+ if (Object.keys(fields).length === 0) continue;
892
+ const prev = store.getTierSnapshot(doc.docId);
893
+ const next: Record<string, unknown> = {};
894
+ for (const [field, tier] of Object.entries(fields)) {
895
+ const current = doc.frontmatter[field];
896
+ if (prev === null || !(field in prev)) {
897
+ if (current !== undefined) next[field] = current;
898
+ continue;
899
+ }
900
+ const expected = prev[field];
901
+ // Deleting an identity field is as much a hand-edit as
902
+ // changing it: `current === undefined` stages drift with a
903
+ // null actual instead of silently dropping the snapshot.
904
+ if (tier === "identity" && !tierValueEquals(expected, current)) {
905
+ const actual = current === undefined ? null : current;
906
+ store.upsertTierDrift({
907
+ documentId: doc.docId,
908
+ field,
909
+ expected,
910
+ actual,
911
+ detectedAt,
912
+ });
913
+ stats.tierDrift = [...stats.tierDrift, { path: doc.relPath, field, expected, actual }];
914
+ next[field] = expected; // the snapshot keeps the truth
915
+ continue;
916
+ }
917
+ store.clearTierDrift(doc.docId, field);
918
+ if (current !== undefined) next[field] = current;
919
+ }
920
+ store.setTierSnapshot(doc.docId, next);
921
+ }
922
+ }
923
+
924
+ // Lazy backend resolution (offline code-only extraction, t_85252236).
925
+ // The credential-gated embedding path runs only when explicitly
926
+ // requested; reaching past populateEmbeddings without throwing means a
927
+ // credential was resolved (or the local provider needs none), so the
928
+ // semantic backend is genuinely active. Otherwise the run is offline
929
+ // and we record why the semantic backend was deferred.
930
+ if (opts?.embeddings) {
931
+ await runEmbeddingPhase(store, config, stats, {
932
+ forceCost: opts?.forceCost === true,
933
+ ...(opts?.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),
934
+ ...(opts?.signal !== undefined ? { signal: opts.signal } : {}),
935
+ progress,
936
+ });
937
+ stats.backend = "semantic";
938
+ stats.deferredReason = null;
939
+ } else {
940
+ stats.backend = "offline";
941
+ stats.deferredReason = await offlineDeferredReason(config);
942
+ }
943
+
944
+ // Documents this run left with no event anchor RESOLVED - not
945
+ // documents that declare no date. A schema bump migrates in place
946
+ // and reindexes nothing, and both fastpaths above correctly decline
947
+ // to recompute an anchor for content that did not change, so a
948
+ // document carried over from a pre-anchor binary is never examined
949
+ // by any number of index runs. Reported here because this run is the
950
+ // surface an upgrading operator reaches first, and because a hard
951
+ // `since` / `until` filter now depends on the answer.
952
+ stats.eventAnchorsPending = store.countUnexaminedEventAnchors();
953
+
954
+ // Oversize-chunk census. Taken here, over the index this run just
955
+ // wrote, because the chunk boundaries the run produced are exactly
956
+ // what the configured model's declared window has to hold - and the
957
+ // configured chunk size is expressed in the chunker's units (words,
958
+ // or characters for unspaced scripts such as Han) while a
959
+ // window is expressed in tokens, so the two settings can only be
960
+ // compared through what they actually produced. The stored model
961
+ // fills in a config that leaves `embedding_model` unset.
962
+ stats.chunkWindow = censusChunkWindow(store, config, store.getState("embedding_model"));
963
+
964
+ const now = new Date().toISOString();
965
+ store.setState(LAST_INDEXED_AT_STATE_KEY, now);
966
+ // The SAME instant on a forced run: their equality is the
967
+ // "this index resolved the whole vault" predicate the broken-link
968
+ // ratchet verifies before it trusts a count (unit G).
969
+ if (opts?.force) store.setState(LAST_FULL_INDEX_AT_STATE_KEY, now);
970
+ // A completed forced run re-chunked every document it kept.
971
+ if (opts?.force) store.setState(CHUNKER_VERSION_STATE_KEY, String(CHUNKER_VERSION));
972
+
973
+ // Bump the corpus-generation revision whenever the index actually
974
+ // changed, so the persistent query cache (v0.20.0) is invalidated
975
+ // after a content reindex even though the embedding model/dimension
976
+ // and schema are unchanged.
977
+ if (stats.added + stats.updated + stats.deleted > 0) {
978
+ store.bumpIndexRevision();
979
+ // Dashboard contract (link-recall-intelligence): one run-level
980
+ // record per non-empty index run. Fail-soft - a metrics-layer
981
+ // problem never fails the index.
982
+ try {
983
+ appendMetric(config.vault, {
984
+ surface: "index",
985
+ runAt: now,
986
+ payload: {
987
+ added: stats.added,
988
+ updated: stats.updated,
989
+ deleted: stats.deleted,
990
+ alias_resolved: stats.aliasResolved,
991
+ relation_violations: stats.relationViolations.length,
992
+ tier_drift: stats.tierDrift.length,
993
+ },
994
+ });
995
+ } catch {
996
+ // Metrics are observability, not correctness.
997
+ }
998
+ }
999
+
1000
+ return freezeStats(stats, Date.now() - t0);
1001
+ } finally {
1002
+ if (ownsStore) await store.close();
1003
+ }
1004
+ }
1005
+
1006
+ /**
1007
+ * Canonical signature of the ACTIVE embedding configuration for status
1008
+ * reporting. Null when semantic search is disabled. Stored model and
1009
+ * dimension fill in fields the config leaves unset (e.g. an
1010
+ * auto-detected dimension or the local provider's implicit model).
1011
+ */
1012
+ function activeEmbeddingSignature(
1013
+ config: ResolvedSearchConfig,
1014
+ storedModel: string | null = null,
1015
+ storedDim: number | null = null,
1016
+ ): string | null {
1017
+ if (!config.semantic.enabled) return null;
1018
+ return embeddingSignature({
1019
+ provider: config.semantic.provider,
1020
+ model: activeEmbeddingModel(config, storedModel),
1021
+ dimension: config.semantic.dimension ?? storedDim,
1022
+ });
1023
+ }
1024
+
1025
+ /**
1026
+ * The config key whose value produced the chunk boundaries under census.
1027
+ * Named once so the warning and any future surface cannot spell it
1028
+ * differently from `resolveSearchConfig`.
1029
+ */
1030
+ const CHUNK_SIZE_CONFIG_KEY = "search_chunk_size";
1031
+
1032
+ /**
1033
+ * Take the oversize-chunk census over an open index.
1034
+ *
1035
+ * Returns `null` when there is nothing to report, which covers three
1036
+ * genuinely different silences, all of them states in which no chunk can
1037
+ * overflow a window:
1038
+ *
1039
+ * - semantic search is off, so nothing is ever embedded;
1040
+ * - the provider is the offline local embedder, which hashes n-gram
1041
+ * features over the whole text - no encoder, no positional limit,
1042
+ * nothing to truncate. A provably absent window, not an unknown one;
1043
+ * - the census ran against a declared window and every chunk fits.
1044
+ *
1045
+ * The silences it does NOT produce are the two states the estimate
1046
+ * cannot back: a model with no declared window (`window-undeclared`),
1047
+ * and chunks the census cannot place inside a declared one
1048
+ * (`estimate-undecided`). A check that could not run and a check that
1049
+ * passed are not the same statement.
1050
+ */
1051
+ function censusChunkWindow(
1052
+ store: Store,
1053
+ config: ResolvedSearchConfig,
1054
+ storedModel: string | null,
1055
+ ): ChunkWindowCensus | null {
1056
+ if (!config.semantic.enabled) return null;
1057
+ if (config.semantic.provider === "local") return null;
1058
+ const chunksMeasured = store.chunkCount();
1059
+ if (chunksMeasured === 0) return null;
1060
+
1061
+ const model = activeEmbeddingModel(config, storedModel);
1062
+ // The one resolver the query fit reads too: an operator-declared window
1063
+ // enables the census for an uncurated model.
1064
+ const windowTokens = effectiveInputWindowTokens(config.semantic, model);
1065
+ if (model === null || windowTokens === null) {
1066
+ return Object.freeze({ verdict: "window-undeclared" as const, model, chunksMeasured });
1067
+ }
1068
+ // The prefix the CONFIGURED backend prepends, not the one the config
1069
+ // asks for: only `openai-compat` implements the instruction-prefix
1070
+ // contract, and subtracting a prefix a backend never sends would
1071
+ // report an overflow nobody can hit.
1072
+ const tally = store.chunkWindowTally(
1073
+ windowTokens,
1074
+ passagePrefixSentByProvider(config.semantic.provider, config.semantic.passagePrefix),
1075
+ );
1076
+ if (tally.overWindow > 0) {
1077
+ return Object.freeze({
1078
+ verdict: "over-window" as const,
1079
+ model,
1080
+ windowTokens,
1081
+ chunksOverWindow: tally.overWindow,
1082
+ // Absent, never zero: an all-ASCII index has no undecided band and
1083
+ // carries the record it carried before this field existed.
1084
+ ...(tally.undecided > 0 ? { chunksUndecided: tally.undecided } : {}),
1085
+ chunksMeasured,
1086
+ });
1087
+ }
1088
+ if (tally.undecided > 0) {
1089
+ return Object.freeze({
1090
+ verdict: "estimate-undecided" as const,
1091
+ model,
1092
+ windowTokens,
1093
+ chunksUndecided: tally.undecided,
1094
+ chunksMeasured,
1095
+ });
1096
+ }
1097
+ return null;
1098
+ }
1099
+
1100
+ /**
1101
+ * The operator-facing warning line for a census that MEASURED something
1102
+ * - chunks proved over the window, or chunks its estimates cannot place
1103
+ * inside one - ending in the command its REGISTERED diagnostic names.
1104
+ * The command is resolved from the registry rather than written here, so
1105
+ * this sentence cannot name an exit the registry does not hold; an
1106
+ * unregistered code throws at the point the sentence is built rather
1107
+ * than shipping a dead end.
1108
+ *
1109
+ * Typed to the two measured members, so the undeclared verdict cannot
1110
+ * reach the warning channel by accident - it is a snapshot field, and
1111
+ * the type is what enforces that rather than a branch nobody calls.
1112
+ *
1113
+ * The undecided line says in words that it is not a pass, because that
1114
+ * is the whole content of the state: the operator is being told the
1115
+ * check ran and could not clear these chunks, not that they are broken.
1116
+ */
1117
+ async function formatChunkWindowMeasured(
1118
+ census: Extract<ChunkWindowCensus, { verdict: "over-window" | "estimate-undecided" }>,
1119
+ ): Promise<string> {
1120
+ const { requireNextStep } = await import("../brain/next-step.ts");
1121
+ const step = requireNextStep(chunkWindowDiagnosticCode(census));
1122
+ const levers =
1123
+ `Two levers change the outcome: split the source by lowering ` +
1124
+ `${CHUNK_SIZE_CONFIG_KEY}, or exclude the page from embedding. Then run: ${step.nextCommand}`;
1125
+ if (census.verdict === "estimate-undecided") {
1126
+ return (
1127
+ `${census.chunksUndecided} of ${census.chunksMeasured} indexed chunk(s) cannot be ` +
1128
+ `placed inside the ${census.windowTokens}-token input window declared for ` +
1129
+ `${census.model}: the census cannot bound a token window with character counts - the ` +
1130
+ `average-rate estimate reads high on ordinary prose, and non-Latin scripts and dense ` +
1131
+ `symbols cost far more than four characters per token - so this is not a pass. ` +
1132
+ `Undecided chunks are still sent, and whatever does not fit is truncated by the ` +
1133
+ `provider, silently - ${levers}`
1134
+ );
1135
+ }
1136
+ const undecided =
1137
+ census.chunksUndecided === undefined
1138
+ ? ""
1139
+ : ` A further ${census.chunksUndecided} chunk(s) the census cannot place either way.`;
1140
+ return (
1141
+ `${census.chunksOverWindow} of ${census.chunksMeasured} indexed chunk(s) cannot fit the ` +
1142
+ `${census.windowTokens}-token input window declared for ${census.model} even at a ` +
1143
+ `conservative estimate; chunks proved over the window are held back from embedding ` +
1144
+ `rather than sent and truncated, and \`o2b search status\` names the held ones in its ` +
1145
+ `held-chunks report. ${levers}${undecided}`
1146
+ );
1147
+ }
1148
+
1149
+ /**
1150
+ * The two counters the vector phase writes back. Declared as its own
1151
+ * shape so the phase can serve the index run's `MutableStats` and the
1152
+ * standalone vector backfill without either knowing about the other;
1153
+ * `MutableStats` satisfies it structurally.
1154
+ */
1155
+ /**
1156
+ * The spans an index run has. `walk` cannot carry a denominator -
1157
+ * `walkVault` is a generator and counting first costs a second full
1158
+ * traversal - while `embed` always can, because its pending list is an
1159
+ * array before the loop starts. One event shape carries all of them.
1160
+ *
1161
+ * `lock` and `swap` belong to a REBUILD only, and both exist because a
1162
+ * rebuild is not over when its build is. `lock` covers the wait on
1163
+ * `acquireWriterLock`, which can be the length of a competing reindex and
1164
+ * which used to emit nothing at all - the silence this release calls
1165
+ * indistinguishable from a hang. `swap` covers the two renames that make
1166
+ * the staging build real; before it, the stream reported `finished` while
1167
+ * the live index was still the old one.
1168
+ */
1169
+ const INDEX_STAGE = Object.freeze({
1170
+ lock: "lock",
1171
+ walk: "walk",
1172
+ embed: "embed",
1173
+ swap: "swap",
1174
+ } as const);
1175
+
1176
+ export interface EmbeddingPhaseTally {
1177
+ embeddingsComputed: number;
1178
+ embeddingsRetries: number;
1179
+ /**
1180
+ * Chunks this phase held back as provably over the model's declared
1181
+ * input window (chunk skip-and-hold, F2), and one record per chunk.
1182
+ * Absent until the phase holds something: a tally a hold-free run
1183
+ * owns never carries either, which is what lets the stats freeze drop
1184
+ * both together.
1185
+ */
1186
+ embeddingsHeld?: number;
1187
+ heldChunks?: HeldChunkRecord[];
1188
+ /**
1189
+ * The cost gate's own verdict for this phase's census, set just before
1190
+ * the first provider call (t_9d155d0e). `forced` is true only when a
1191
+ * force bypass overrode a gate that would have refused the spend, so a
1192
+ * receipt can name its own bypass. Optional and undefined until then:
1193
+ * a tally an embedding-free caller owns never carries one.
1194
+ */
1195
+ spend?: MaintenanceSpendReceipt;
1196
+ }
1197
+
1198
+ export interface EmbeddingPhaseOptions {
1199
+ /** Bypass the configured spend ceiling for this run. */
1200
+ readonly forceCost?: boolean;
1201
+ /**
1202
+ * Path scope of the pending census. It reaches the census only through
1203
+ * the spend plan, so the gate, the refusal and the receipt read the
1204
+ * same chunks the phase embeds. Vault-wide when absent.
1205
+ */
1206
+ readonly scope?: PendingVectorScope;
1207
+ /**
1208
+ * A spend plan the caller already computed on this store and over the
1209
+ * same `scope`; the phase embeds its pending census instead of reading
1210
+ * it a second time, so a caller that reported the plan embeds exactly
1211
+ * what it priced. Its price and gate verdict are recomputed here from
1212
+ * the current config, so a forced or stale verdict is never trusted.
1213
+ * Recomputed in full when absent.
1214
+ */
1215
+ readonly plan?: EmbeddingSpendPlan;
1216
+ readonly safeguard?: import("../brain/safeguard.ts").Safeguard;
1217
+ readonly signal?: AbortSignal;
1218
+ /**
1219
+ * The RUN's progress counter, not a sink of its own.
1220
+ *
1221
+ * This phase is the half of an index run that can report a fraction -
1222
+ * the pending list is an array before the loop starts - but it is a
1223
+ * PHASE, not a run: it is called both from `indexInto` and standalone
1224
+ * by the vector backfill. Given a sink it would build a second counter,
1225
+ * and a stream carrying two terminators cannot say which one ended the
1226
+ * run. So the caller that owns the run owns the counter, and this phase
1227
+ * borrows it. That is why `progress-census.test.ts` carries a written
1228
+ * exemption for this interface rather than a sink.
1229
+ */
1230
+ readonly progress?: import("../brain/progress.ts").ProgressCounter;
1231
+ }
1232
+
1233
+ /** One entry of the embedding phase's pending census. */
1234
+ type PendingCensusEntry = EmbeddingSpendPlan["pending"][number];
1235
+
1236
+ /**
1237
+ * Split a pending census into what the embedding phase may send and what
1238
+ * it must HOLD back (chunk skip-and-hold, F2).
1239
+ *
1240
+ * The hold acts on proof only. A chunk is held when the conservative
1241
+ * bound - code points charged at no more than one token per
1242
+ * `MAX_CODE_POINTS_PER_TOKEN` (embeddings/signature.ts), through the
1243
+ * prefix the configured backend actually prepends - already exceeds the
1244
+ * model's effective declared window: real tokenizers absorb several code
1245
+ * points per token, so a text over even that generous charge cannot fit.
1246
+ * The chars-over-four
1247
+ * average is deliberately NOT the trigger: it is an average, not a bound,
1248
+ * and holding on it read whole English chunks that fit the window as over
1249
+ * it - recall lost on an arithmetic guess.
1250
+ *
1251
+ * Everything between that bound and the average-rate estimate is the
1252
+ * undecided band: those chunks stay embedded exactly as before this
1253
+ * feature, because acting there would hold work on a guess, and the window
1254
+ * census beside this phase reports the band rather than passing it in
1255
+ * silence. A model with no declared window (or the local embedder, which
1256
+ * has no window by construction) proves nothing at all - for them nothing
1257
+ * is held and every chunk stays pending.
1258
+ *
1259
+ * The hold bound is the same measurement the oversize-chunk census makes
1260
+ * its `over-window` arm with, so the phase and the report can never
1261
+ * disagree about which chunks are provably over.
1262
+ */
1263
+ function partitionHeldChunks(
1264
+ pending: ReadonlyArray<PendingCensusEntry>,
1265
+ semantic: ResolvedEmbeddingConfig,
1266
+ model: string | null,
1267
+ ): { readonly embeddable: Array<PendingCensusEntry>; readonly held: HeldChunkRecord[] } {
1268
+ const windowTokens = effectiveInputWindowTokens(semantic, model);
1269
+ if (windowTokens === null) return { embeddable: [...pending], held: [] };
1270
+ // Charge the text the provider will actually receive: only
1271
+ // `openai-compat` prepends the configured passage prefix, and a
1272
+ // prefix nobody sends cannot push a chunk over a window.
1273
+ const prefix = passagePrefixSentByProvider(semantic.provider, semantic.passagePrefix);
1274
+ const embeddable: Array<PendingCensusEntry> = [];
1275
+ const held: HeldChunkRecord[] = [];
1276
+ for (const chunk of pending) {
1277
+ const heldTokens = tokenHoldFloor(textExtent(prefix + chunk.content));
1278
+ if (heldTokens > windowTokens) {
1279
+ held.push(
1280
+ Object.freeze({
1281
+ chunkId: chunk.chunkId,
1282
+ estimatedTokens: heldTokens,
1283
+ windowTokens,
1284
+ reason: CHUNK_HOLD_REASON.overDeclaredWindow,
1285
+ }),
1286
+ );
1287
+ } else {
1288
+ embeddable.push(chunk);
1289
+ }
1290
+ }
1291
+ return { embeddable, held };
1292
+ }
1293
+
1294
+ /**
1295
+ * Compute and store a vector for every indexed chunk that has none.
1296
+ *
1297
+ * Chunks whose token estimate PROVABLY exceeds the model's effective
1298
+ * declared input window are held back instead (see
1299
+ * {@link partitionHeldChunks}): they are never sent, never stored and
1300
+ * never priced, and the tally records each one.
1301
+ *
1302
+ * Exported (provenance-at-the-boundary, F) because it is the whole of
1303
+ * `o2b search vector-backfill --apply`: the population step is already
1304
+ * resumable by construction - the anti-join finds exactly the chunks
1305
+ * still missing a row and `vecUpsert` commits per chunk - so the backfill
1306
+ * verb is this phase run on its own, not a second implementation of it.
1307
+ *
1308
+ * Every refusal here is a SearchError, because reaching this function is
1309
+ * an attempt: the capability tier is what a caller reports when it
1310
+ * declines to attempt.
1311
+ */
1312
+ export async function runEmbeddingPhase(
1313
+ store: Store,
1314
+ config: ResolvedSearchConfig,
1315
+ stats: EmbeddingPhaseTally,
1316
+ opts: EmbeddingPhaseOptions = {},
1317
+ ): Promise<void> {
1318
+ const forceCost = opts.forceCost === true;
1319
+ const safeguard = opts.safeguard;
1320
+ const signal = opts.signal;
1321
+ const progress = opts.progress;
1322
+ if (!config.semantic.enabled) {
1323
+ throw new SearchError(
1324
+ "EMBEDDING_DISABLED",
1325
+ "set search_semantic_enabled=true and embedding_* keys to compute embeddings",
1326
+ );
1327
+ }
1328
+ // The offline local provider needs no key; every remote provider does.
1329
+ if (config.semantic.provider !== "local" && !config.semantic.apiKey) {
1330
+ throw new SearchError(
1331
+ "EMBEDDING_KEY_MISSING",
1332
+ "embedding_api_key is required when computing embeddings",
1333
+ );
1334
+ }
1335
+ if (!store.vecLoaded()) {
1336
+ throw new SearchError(
1337
+ "VEC_EXTENSION_UNAVAILABLE",
1338
+ "sqlite-vec did not load; cannot store embeddings",
1339
+ );
1340
+ }
1341
+
1342
+ // A handed-in plan keeps its census but is priced and gated again here,
1343
+ // unforced: the verdict this phase acts on is always its own.
1344
+ const initialPlan =
1345
+ opts.plan !== undefined
1346
+ ? priceSpendPlan(opts.plan.pending, config)
1347
+ : planEmbeddingSpend(store, config, opts.scope ? { scope: opts.scope } : {});
1348
+ const pending = initialPlan.pending;
1349
+ if (pending.length === 0) return;
1350
+
1351
+ const consent = resolveProviderConsent({
1352
+ configPath: config.configPath ?? null,
1353
+ env: process.env,
1354
+ semantic: config.semantic,
1355
+ });
1356
+ const provider = makeProvider(config.semantic, consent);
1357
+ const model = config.semantic.model ?? provider.model;
1358
+
1359
+ // Skip-and-hold (F2): chunks provably over the declared window leave
1360
+ // the census BEFORE it is priced, batched or gated, so held work can
1361
+ // neither trip the cost gate nor appear on the receipt. Filtering ahead
1362
+ // of the batch loop is also what keeps the 1:1 invariant below intact:
1363
+ // the provider is only ever asked about chunks it will answer for.
1364
+ const { embeddable, held } = partitionHeldChunks(pending, config.semantic, model);
1365
+ if (held.length > 0) {
1366
+ stats.embeddingsHeld = (stats.embeddingsHeld ?? 0) + held.length;
1367
+ (stats.heldChunks ??= []).push(...held);
1368
+ // The record is what makes the hold outlive the run: the pending
1369
+ // anti-join excludes these chunks under this key, so the status
1370
+ // estimate, the preview and the next census stop pricing work this
1371
+ // config proved it will not spend. A hold the config-side resolver
1372
+ // cannot key is not persisted - there is no stable identity to
1373
+ // release it under.
1374
+ const exclusion = chunkHoldExclusion(config);
1375
+ if (exclusion !== null) {
1376
+ store.recordChunkHolds(
1377
+ held.map((h) => ({
1378
+ chunkId: h.chunkId,
1379
+ estimatedTokens: h.estimatedTokens,
1380
+ windowTokens: h.windowTokens,
1381
+ })),
1382
+ { model: exclusion.model, embeddingSignature: exclusion.embeddingSignature },
1383
+ );
1384
+ }
1385
+ }
1386
+ // A run that holds everything pending spends nothing: no provider
1387
+ // request, no gate verdict, and no receipt on a census it will not
1388
+ // embed.
1389
+ if (embeddable.length === 0) return;
1390
+ const plan = held.length > 0 ? priceSpendPlan(embeddable, config) : initialPlan;
1391
+
1392
+ // Cost gate: the shared spend plan estimates the whole pending set up
1393
+ // front and the run is refused when it exceeds the configured ceiling,
1394
+ // unless forced.
1395
+ //
1396
+ // The plan is evaluated UNFORCED so the refusal and the receipt read
1397
+ // one verdict: `blocked && !forceCost` is exactly the blocked flag a
1398
+ // forced plan would have returned, and `blocked && forceCost` is the
1399
+ // honest meaning of the receipt's `forced` - this run overrode a gate
1400
+ // that would have refused it.
1401
+ if (plan.gate.blocked && !forceCost) {
1402
+ const gateUsd = config.semantic.costGateUsd;
1403
+ if (plan.gate.reason === EMBEDDING_GATE_REASON.unpriced) {
1404
+ throw new SearchError("EMBEDDING_COST_UNPRICED", unpricedRefusalMessage(plan, gateUsd));
1405
+ }
1406
+ throw new SearchError(
1407
+ "EMBEDDING_COST_GATE",
1408
+ `estimated embedding cost ${formatEstimatedUsd(plan.estimatedUsd)} for ${plan.pending.length} chunk(s) ` +
1409
+ `exceeds ${COST_GATE_KEY} ${formatEstimatedUsd(gateUsd)}. ` +
1410
+ `Re-run with ${FORCE_COST_FLAG} to proceed or raise the gate.`,
1411
+ );
1412
+ }
1413
+ stats.spend = {
1414
+ model: plan.model,
1415
+ tokens: plan.tokens,
1416
+ estimatedUsd: plan.estimatedUsd,
1417
+ forced: plan.gate.blocked && forceCost,
1418
+ priceSource: plan.quote.source,
1419
+ };
1420
+ const batchSize = Math.max(1, config.semantic.batchSize);
1421
+ // Hand the provider a super-batch large enough to keep its internal
1422
+ // `embedding_concurrency` semaphore busy. Without this multiplier the
1423
+ // indexer's outer loop would serialise provider.embed() calls and the
1424
+ // configured concurrency would never kick in. It is an upper bound, not
1425
+ // an exact fill: when `embedding_batch_tokens` is set the provider closes
1426
+ // a batch on the token estimate as well as on the count, so a super-batch
1427
+ // may split into more - and therefore smaller - requests than
1428
+ // `embedding_concurrency`.
1429
+ const superBatch = batchSize * Math.max(1, config.semantic.concurrency);
1430
+
1431
+ progress?.start(INDEX_STAGE.embed, embeddable.length);
1432
+ for (let i = 0; i < embeddable.length; i += superBatch) {
1433
+ // Cooperative deadline: embedding batches are the other long
1434
+ // phase of an index run - abort between batches, never mid-batch.
1435
+ safeguard?.checkpoint();
1436
+ throwIfAborted(signal, "index");
1437
+ const batch = embeddable.slice(i, i + superBatch);
1438
+ progress?.advance(INDEX_STAGE.embed, batch.length);
1439
+ const texts = batch.map((p) => p.content);
1440
+ const vectors = await provider.embed(texts, "passage");
1441
+ stats.embeddingsRetries += provider.consumeRetryCount?.() ?? 0;
1442
+ if (vectors.length !== batch.length) {
1443
+ throw new SearchError(
1444
+ "EMBEDDING_PROVIDER_HTTP",
1445
+ `provider returned ${vectors.length} vectors for ${batch.length} inputs`,
1446
+ );
1447
+ }
1448
+ // Lock in the auto-detected dimension on the very first batch.
1449
+ const dim = provider.dimension ?? vectors[0]?.length ?? 0;
1450
+ if (dim <= 0) {
1451
+ throw new SearchError(
1452
+ "EMBEDDING_DIMENSION_MISMATCH",
1453
+ "provider returned vectors of zero length",
1454
+ );
1455
+ }
1456
+ store.ensureEmbeddingModel(model, dim, {
1457
+ query: config.semantic.queryPrefix ?? "",
1458
+ passage: config.semantic.passagePrefix ?? "",
1459
+ });
1460
+ for (let j = 0; j < batch.length; j++) {
1461
+ const chunkId = batch[j]!.chunkId;
1462
+ const vec = vectors[j]!;
1463
+ const embHash = sha256Hex(vec.map((x) => x.toFixed(8)).join(","));
1464
+ store.vecUpsert(chunkId, vec, model, dim, embHash);
1465
+ stats.embeddingsComputed++;
1466
+ }
1467
+ }
1468
+ }
1469
+
1470
+ /** What an embedding pass about to run on this config is predicted to spend. */
1471
+ export interface EmbeddingSpendPreview {
1472
+ /** The model the pass would name; null when the config leaves it unset. */
1473
+ readonly model: string | null;
1474
+ /** Chunks the phase's own anti-join still finds vectorless. */
1475
+ readonly pendingChunks: number;
1476
+ readonly tokens: number;
1477
+ /** Null when nobody stated the model's price. */
1478
+ readonly estimatedUsd: number | null;
1479
+ /** Who stated the price the estimate used. */
1480
+ readonly priceSource: EmbeddingPriceSource;
1481
+ /**
1482
+ * True when the configured gate would refuse this spend unforced - the
1483
+ * fact a `--force-cost` receipt is honest about.
1484
+ */
1485
+ readonly blocked: boolean;
1486
+ /** Why the gate would refuse; null when it would not. */
1487
+ readonly reason: EmbeddingGateReason | null;
1488
+ }
1489
+
1490
+ /**
1491
+ * The spend preview the maintenance lane announces before its reindex
1492
+ * task and records on its journal row after it (t_9d155d0e).
1493
+ *
1494
+ * Deliberately a READ over the same spend plan {@link runEmbeddingPhase}
1495
+ * gates on - the phase's guards, in its order, and `planEmbeddingSpend`
1496
+ * (`embedding-spend.ts`) - so what a run ANNOUNCES and what it later RECORDS
1497
+ * cannot drift from what would actually be refused or embedded. This
1498
+ * function never spends: the phase remains the only spender, and a
1499
+ * refusal it would throw stays its to throw.
1500
+ *
1501
+ * Null means "this run cannot spend", per guard: semantic not configured
1502
+ * or its credential missing; the index missing entirely (the next pass
1503
+ * builds it, so the pending census does not exist yet); sqlite-vec not
1504
+ * loadable; or nothing pending. Every one of those is a verdict the
1505
+ * caller may print or omit - never an error - and for that reason the
1506
+ * banner it feeds is printed ONLY when this returns a preview.
1507
+ */
1508
+ export async function estimatePendingEmbeddingSpend(
1509
+ config: ResolvedSearchConfig,
1510
+ ): Promise<EmbeddingSpendPreview | null> {
1511
+ if (semanticCapabilityIsBlocked(resolveSemanticCapability(config.semantic))) return null;
1512
+ let store: Store;
1513
+ try {
1514
+ store = await Store.open(config, { mode: "read" });
1515
+ } catch (e) {
1516
+ if (e instanceof SearchError && e.code === "INDEX_MISSING") return null;
1517
+ throw e;
1518
+ }
1519
+ try {
1520
+ if (!store.vecLoaded()) return null;
1521
+ const plan = planEmbeddingSpend(store, config);
1522
+ if (plan.pending.length === 0) return null;
1523
+ return {
1524
+ model: plan.model,
1525
+ pendingChunks: plan.pending.length,
1526
+ tokens: plan.tokens,
1527
+ estimatedUsd: plan.estimatedUsd,
1528
+ priceSource: plan.quote.source,
1529
+ blocked: plan.gate.blocked,
1530
+ reason: plan.gate.reason,
1531
+ };
1532
+ } finally {
1533
+ await store.close();
1534
+ }
1535
+ }
1536
+
1537
+ // ─────────────────────────────────────────────────────────────────────────────
1538
+ // reindexVault — atomic full rebuild
1539
+ // ─────────────────────────────────────────────────────────────────────────────
1540
+
1541
+ export async function reindexVault(
1542
+ config: ResolvedSearchConfig,
1543
+ opts?: IndexVaultOptions,
1544
+ ): Promise<IndexStats> {
1545
+ const stats = await reindexVaultUnless(config, null, opts);
1546
+ // No predicate, so the rebuild always runs.
1547
+ return stats!;
1548
+ }
1549
+
1550
+ /**
1551
+ * {@link reindexVault} that re-checks, once it HOLDS the writer lock,
1552
+ * whether the rebuild is still wanted: `stillCurrent` returning true
1553
+ * abandons it before anything is built or swapped, and the call returns
1554
+ * `null`. The self-heal paths pass their inspection here, so a second
1555
+ * process that queued behind a rebuild another process just finished does
1556
+ * not rebuild again over it (and over its `.bak`).
1557
+ */
1558
+ export async function reindexVaultUnless(
1559
+ config: ResolvedSearchConfig,
1560
+ stillCurrent: (() => boolean) | null,
1561
+ opts?: IndexVaultOptions,
1562
+ ): Promise<IndexStats | null> {
1563
+ // The rebuild owns the run's counter from before the lock wait to after
1564
+ // the swap, and hands it to the staging build rather than letting that
1565
+ // build open one of its own. Two reasons, and they are the same reason
1566
+ // twice: a rebuild is not finished when its build is. `indexVault`'s
1567
+ // own counter terminated at the end of the build, so a caller tailing
1568
+ // the stream read `finished` while the live index was still the old one
1569
+ // and the rename that makes the rebuild real had not been attempted -
1570
+ // and if that rename then failed (ENOSPC, EPERM, a cross-device
1571
+ // `dbPath`), the command exited non-zero after a terminator that said
1572
+ // the run had finished.
1573
+ const progress = progressCounter(OPERATION.reindex, opts?.onProgress);
1574
+ return await withProgressAsync(progress, () => reindexInto(config, progress, stillCurrent, opts));
1575
+ }
1576
+
1577
+ async function reindexInto(
1578
+ config: ResolvedSearchConfig,
1579
+ progress: ProgressCounter,
1580
+ stillCurrent: (() => boolean) | null,
1581
+ opts?: IndexVaultOptions,
1582
+ ): Promise<IndexStats | null> {
1583
+ // The run's own clock: the build below times only its note walk, and a
1584
+ // rebuild is also the lock wait, the brain store's ingest and the swap
1585
+ // (a real-size store: "done in 8.3s" after 1 min 51 s of wall time).
1586
+ const startedAt = Date.now();
1587
+ const newPath = stagingIndexPath(config.dbPath);
1588
+ const bakPath = config.dbPath + ".bak";
1589
+
1590
+ assertVaultDirectory(config.vault);
1591
+ mkdirSync(dirname(config.dbPath), { recursive: true });
1592
+
1593
+ // Opened BEFORE the wait, not after it. `acquireWriterLock` can block
1594
+ // for the whole duration of a competing reindex, and a stream that
1595
+ // emits nothing while it does is the state this release names as
1596
+ // indistinguishable from a hang.
1597
+ progress.start(INDEX_STAGE.lock, 1);
1598
+
1599
+ // Hold the writer lock on the LIVE index path for the whole rebuild +
1600
+ // swap. Keyed on `config.dbPath` (not the `.new` staging path), so a
1601
+ // second concurrent reindex — the double-reindex a schema-bump upgrade
1602
+ // triggers when CLI and the long-lived MCP server both self-heal at
1603
+ // once — waits-or-bails on the SAME lock instead of unlinking this run's
1604
+ // in-progress staging DB and then having its empty seed swapped over the
1605
+ // live index (INDEX_UNREADABLE, silent data loss). The staging-DB opens
1606
+ // below lock a different path (`.new`), so there is no self-deadlock.
1607
+ const lease = await acquireWriterLease(config.dbPath);
1608
+ progress.advance(INDEX_STAGE.lock);
1609
+ // What a search answering from the staging file, the session notice and
1610
+ // the error text read while this rebuild runs (`build-progress.ts`).
1611
+ let recorder: IndexBuildRecorder | null = null;
1612
+ try {
1613
+ if (stillCurrent !== null && stillCurrent()) return null;
1614
+ // A set-aside stopped between two renames is finished first, so the
1615
+ // parked names read below are the real ones (`parked-set-aside.ts`).
1616
+ finishInterruptedSetAsides(config.dbPath, lease);
1617
+ // The refusal the swap would end in, decided BEFORE the build: both
1618
+ // parked names held and neither of them releasable is knowable now -
1619
+ // the parked names and their readability are known up front - and
1620
+ // deciding it here means the operator gets the answer in a second and
1621
+ // no staging index of the full size is written for a build that
1622
+ // cannot be swapped in. The swap keeps its own check for the two
1623
+ // things only it can know (the live index's integrity verdict, and
1624
+ // whether a removal succeeds).
1625
+ //
1626
+ // The preflight counts the stored embeddings and runs the same
1627
+ // integrity check the swap runs, and both read the index in full: on a
1628
+ // large one they block this thread for longer than a heartbeat can
1629
+ // wait, and the lease would go stale under the rebuild that holds it.
1630
+ // The lease is kept fresh off this thread for the same work the swap
1631
+ // keeps it fresh through, so a writer that took the lock over in the
1632
+ // meantime is refused before the build, not at the swap.
1633
+ const parkRefusal = keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () =>
1634
+ preflightParkNames(config.dbPath, opts?.target ?? plainParkedTarget(config.dbPath)),
1635
+ );
1636
+ if (parkRefusal !== null) {
1637
+ throw new SearchError(
1638
+ "INDEX_LOCKED",
1639
+ `the rebuild of ${config.dbPath} found earlier indexes parked at both ` +
1640
+ `${config.dbPath}.bak and ${config.dbPath}.old, so it swapped nothing in and removed ` +
1641
+ `neither: ${parkRefusal}`,
1642
+ );
1643
+ }
1644
+ recorder = new IndexBuildRecorder(config.dbPath, Date.now, () => leaseStillHeld(lease));
1645
+ sweepStagingClaims(config.dbPath);
1646
+ // Build into the temp file with an override config.
1647
+ const tempConfig: ResolvedSearchConfig = Object.freeze({
1648
+ ...config,
1649
+ dbPath: newPath,
1650
+ });
1651
+
1652
+ // Resumable staging (opt-in). A compatible in-progress `.new` from an
1653
+ // interrupted run is resumed via the incremental fastpath instead of
1654
+ // rebuilt from scratch; an incompatible or unreadable one is
1655
+ // discarded. With the flag OFF, the temp file is always rebuilt fresh
1656
+ // and no staging marker is written or read - byte-identical to the
1657
+ // pre-suite path (no extra staging-DB open/close cycles).
1658
+ let resume = false;
1659
+ if (config.resumeReindex) {
1660
+ const signature = reindexStagingSignature(config, opts?.embeddings === true);
1661
+ // An unknown-identity embedding component (an unnamed model) is
1662
+ // compatible with nothing, including a staging build stamped under
1663
+ // the same unknown identity: such a build always rebuilds.
1664
+ if (existsSync(newPath)) {
1665
+ resume = await stagingSignatureMatches(tempConfig, signature);
1666
+ }
1667
+ if (!resume) discardStaging(newPath);
1668
+ // Stamp the signature so an interruption leaves a build a later run
1669
+ // can recognise and resume. An unknown-identity signature is stamped
1670
+ // too: it documents the identity, and the comparison above never
1671
+ // lets it match.
1672
+ await withStagingStore(tempConfig, (store) =>
1673
+ store.setState(REINDEX_SIGNATURE_KEY, JSON.stringify(signature)),
1674
+ );
1675
+ } else {
1676
+ discardStaging(newPath);
1677
+ }
1678
+ // A staging file resumed from an earlier run was built before this
1679
+ // one began: whatever the store has forgotten since (a removed signal,
1680
+ // preference or lane entry) leaves it before any search may read it.
1681
+ if (resume && config.brainStore) {
1682
+ await withStagingStore(tempConfig, (store) => dropForgottenRecords(store, tempConfig));
1683
+ }
1684
+ // The staging file is this build's now, accepted or recreated: searches
1685
+ // may read it from here on (until here the record said `preparing`).
1686
+ recorder.ready();
1687
+
1688
+ // The brain store goes into the staging index first (design D5), every
1689
+ // shard from offset 0, so the swapped-in index answers with the store
1690
+ // from its first read instead of catching up on it afterwards, and a
1691
+ // search that answers from the staging file while the build runs finds
1692
+ // the signals, preferences and decisions before the vault's notes. It
1693
+ // is best effort: a store that cannot be read must not throw the note
1694
+ // rebuild away. A shard whose watermark was not written is read from
1695
+ // offset 0 by the next catch-up, so nothing is lost; the failure is
1696
+ // reported among the run's errors.
1697
+ let storeError: { readonly path: string; readonly message: string } | null = null;
1698
+ if (config.brainStore) {
1699
+ try {
1700
+ recorder.storeBegins();
1701
+ await withStagingStore(tempConfig, (store) =>
1702
+ ingestStoreInto(store, tempConfig, (done, total, records) =>
1703
+ recorder?.store(done, total, records),
1704
+ ),
1705
+ );
1706
+ } catch (e) {
1707
+ storeError = {
1708
+ path: STORE_RECORD_PATH_PREFIX,
1709
+ message: `brain store not ingested, the next catch-up reads it: ${e instanceof Error ? e.message : String(e)}`,
1710
+ };
1711
+ }
1712
+ recorder.storeEnds();
1713
+ }
1714
+
1715
+ // `force: false` on resume lets the fastpath skip the files the
1716
+ // partial build already committed; a fresh build forces every file.
1717
+ // `onProgress` is dropped from the forwarded options: the build
1718
+ // reports into THIS run's counter, passed explicitly, rather than
1719
+ // opening a second one over the same sink.
1720
+ let stats = await indexInto(
1721
+ tempConfig,
1722
+ { ...opts, force: !resume, onProgress: undefined },
1723
+ undefined,
1724
+ progress,
1725
+ );
1726
+ if (storeError !== null) stats = { ...stats, errors: [...stats.errors, storeError] };
1727
+
1728
+ // Clear the marker so the swapped-in live index carries no staging
1729
+ // state. Only present when resume was enabled.
1730
+ if (config.resumeReindex) {
1731
+ await withStagingStore(tempConfig, (store) => store.deleteState(REINDEX_SIGNATURE_KEY));
1732
+ }
1733
+
1734
+ // A search may be reading the staging file (`build-progress.ts`). From
1735
+ // here on no new one opens it, and the ones holding it (one query each)
1736
+ // are waited for, so the WAL below folds completely and, on Windows,
1737
+ // the rename meets no open handle. A reader that outstays the wait (a
1738
+ // process stuck mid-query) does not fail the build: the fold and the
1739
+ // rename each retry for a bounded time. The barrier itself must hold:
1740
+ // a build that cannot publish it never swaps.
1741
+ if (recorder !== null && !recorder.finish()) {
1742
+ throw new SearchError(
1743
+ "INDEX_LOCKED",
1744
+ `the rebuild of ${config.dbPath} could not keep searches off its staging file for the swap: the progress file could not be written or removed`,
1745
+ );
1746
+ }
1747
+ // Readers still in flight after the wait do not stop the swap: the
1748
+ // fold and the renames retry. A claim list that could not be read at
1749
+ // all is not a drained one, so the swap stops.
1750
+ const drain = await waitForStagingReaders(config.dbPath, STAGING_SWAP_BUDGET_MS);
1751
+ if (drain === "unknown") {
1752
+ throw new SearchError(
1753
+ "INDEX_LOCKED",
1754
+ `the rebuild of ${config.dbPath} could not list the searches reading its staging file, so it does not swap it in`,
1755
+ );
1756
+ }
1757
+ await foldStagingWal(newPath);
1758
+
1759
+ // Same-directory rename swap. The two renames are each atomic on
1760
+ // POSIX; the gap between them is the only crash window. A read that
1761
+ // opens in that window is held off by this same lock (see
1762
+ // restoreFromBakIfMissing in store.ts), so it cannot restore the stale
1763
+ // `.bak` over the freshly built index; a genuine crash leaves the lock
1764
+ // stale and the .bak restore on the next Store.open recovers.
1765
+ //
1766
+ // A `.bak` holding more stored embeddings than the live index is kept:
1767
+ // it is the only copy of vectors a keyword-only rebuild cannot
1768
+ // recompute, and replacing it with a vector-less live index (two
1769
+ // self-heal rebuilds in a row) would discard them while the rebuild
1770
+ // notice still points at `.bak`. The live index is parked beside it
1771
+ // for the swap and removed once the swap succeeds; a crash between the
1772
+ // renames leaves it at `.old`, which the next Store.open restores in
1773
+ // preference to the older `.bak` (restoreFromBakIfMissing).
1774
+ // Windows: a bun:sqlite connection with unfinalized statements survives
1775
+ // close() as a zombie holding the staging DB handle until GC, so the
1776
+ // rename swap below fails EBUSY against the process's OWN handle (POSIX
1777
+ // is unaffected - rename(2) ignores open handles). Force collection to
1778
+ // release finalizer-pending handles before the renames.
1779
+ if (typeof Bun !== "undefined") Bun.gc(true);
1780
+ else (globalThis as { gc?: () => void }).gc?.();
1781
+ progress.start(INDEX_STAGE.swap, 1);
1782
+ const oldPath = config.dbPath + ".old";
1783
+ // A rebuild killed between the renames of an earlier swap left the
1784
+ // previous index parked with no live index beside it, its main file and
1785
+ // journals possibly split between the two names. It is put back first,
1786
+ // so it is parked again below like any live index instead of being
1787
+ // read as leftovers: nothing parked is discarded before this rebuild
1788
+ // has verified the index that supersedes it.
1789
+ lease.assertHeld();
1790
+ restoreParkedIndexUnderLock(config.dbPath, lease);
1791
+ // Again once a live index is back: a set-aside left part way is
1792
+ // finished before a free parked name has its journals cleared.
1793
+ finishInterruptedSetAsides(config.dbPath, lease);
1794
+ if (!existsSync(config.dbPath) && (existsSync(bakPath) || existsSync(oldPath))) {
1795
+ throw new SearchError(
1796
+ "INDEX_LOCKED",
1797
+ `the rebuild of ${config.dbPath} found a parked previous index it could not put back, ` +
1798
+ "so it swapped nothing in; the parked index is untouched",
1799
+ );
1800
+ }
1801
+ // Counting the stored embeddings reads the index in full, which on a
1802
+ // large one blocks for a while; the lock is kept fresh meanwhile.
1803
+ const builtVectors = keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () =>
1804
+ countStoredEmbeddings(newPath),
1805
+ );
1806
+ const builtGeneration = readIndexGeneration(newPath);
1807
+ // The live index is parked at a free parked name: `.bak`, or `.old`
1808
+ // beside an earlier `.bak` (one that still holds stored embeddings a
1809
+ // keyword-only rebuild cannot recompute). When both hold an earlier
1810
+ // index - a rebuild that died before verifying its successor - the live
1811
+ // index decides between them, if it passes the same check.
1812
+ let parkPath = freeParkPath(bakPath, oldPath);
1813
+ if (parkPath === null) {
1814
+ lease.assertHeld();
1815
+ const blocked = keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () =>
1816
+ settleParkedBesideLive(
1817
+ config.dbPath,
1818
+ lease,
1819
+ opts?.target ?? plainParkedTarget(config.dbPath),
1820
+ ),
1821
+ );
1822
+ parkPath = freeParkPath(bakPath, oldPath);
1823
+ if (parkPath === null) {
1824
+ throw new SearchError(
1825
+ "INDEX_LOCKED",
1826
+ `the rebuild of ${config.dbPath} found earlier indexes parked at both ${bakPath} and ` +
1827
+ `${oldPath}, so it swapped nothing in and removed neither: ${blocked}`,
1828
+ );
1829
+ }
1830
+ }
1831
+ // The last moment the rebuild can still be thrown away harmlessly,
1832
+ // right before the first destructive step. A lease another writer took
1833
+ // over (this run stalled past the stale window) no longer excludes that
1834
+ // writer, and swapping now would replace whatever it committed with
1835
+ // this run's staging build.
1836
+ lease.assertHeld();
1837
+ const park = parkPath;
1838
+ // On Windows each rename may retry for STAGING_SWAP_BUDGET_MS, blocking
1839
+ // this thread: the lease is kept fresh off it for both, and ownership
1840
+ // is checked again once they are done.
1841
+ keepWriterLeasesFresh(SWAP_LEASE_BUDGET_MS, () => {
1842
+ // Each database moves as a set with its `-wal`, `-shm` and
1843
+ // `-journal` (`sqlite-file-set.ts`): a writer killed after a
1844
+ // commit leaves a non-empty `-wal` at the live path, and SQLite
1845
+ // would replay it into whatever database is renamed there next. The
1846
+ // previous index takes its siblings with it to the parked path, and
1847
+ // the new one is renamed in only over a live path with none left.
1848
+ // A free parked name holds no main file; journals of nothing found
1849
+ // there would be adopted by the set parked now, so they go first.
1850
+ discardSiblings(park, lease);
1851
+ discardSiblings(newPath, lease);
1852
+ // Durable before the main file moves: a stop between the renames
1853
+ // below leaves the main at `park` and its journals at the live path,
1854
+ // and the crash restore reunites them by this record, not by name.
1855
+ lease.assertHeld();
1856
+ writeParkMarker(config.dbPath, park);
1857
+ try {
1858
+ parkSqliteFileSet(config.dbPath, park, SWAP_RENAME_SEAMS, () => lease.assertHeld());
1859
+ } catch (err) {
1860
+ clearMarkerIfLiveWhole(config.dbPath, lease);
1861
+ throw new SearchError(
1862
+ "INDEX_LOCKED",
1863
+ `the rebuild of ${config.dbPath} could not park the live index at ${park}: ${err instanceof Error ? err.message : String(err)}`,
1864
+ );
1865
+ }
1866
+ try {
1867
+ const stray = sqliteJournalsPresent(config.dbPath);
1868
+ if (stray.length > 0) {
1869
+ throw new SearchError(
1870
+ "INDEX_LOCKED",
1871
+ `the rebuild of ${config.dbPath} could not swap its index in: ${stray.join(", ")} ` +
1872
+ "appeared at the live path after the previous index was moved aside",
1873
+ );
1874
+ }
1875
+ // The publish itself: only while the lease is still this run's. A
1876
+ // writer that took the lock over while the renames above retried
1877
+ // owns the live path now, and the previous index is put back.
1878
+ lease.assertHeld();
1879
+ // must succeed — `newPath` was just built
1880
+ renameWithRetry(newPath, config.dbPath, SWAP_RENAME_SEAMS);
1881
+ } catch (swapError) {
1882
+ let rollback: string | null;
1883
+ try {
1884
+ lease.assertHeld();
1885
+ rollback = restoreLiveFromBak(park, config.dbPath, lease);
1886
+ } catch (e) {
1887
+ rollback = `writer lease could not be confirmed: ${e instanceof Error ? e.message : String(e)}`;
1888
+ }
1889
+ if (rollback === null) {
1890
+ clearMarkerIfLiveWhole(config.dbPath, lease);
1891
+ throw swapError;
1892
+ }
1893
+ // The swap's own failure stays first; the refusal never reads as
1894
+ // "previous index intact" when it is not.
1895
+ const what = swapError instanceof Error ? swapError.message : String(swapError);
1896
+ throw new SearchError(
1897
+ swapError instanceof SearchError ? swapError.code : "INDEX_LOCKED",
1898
+ `${what}; the previous index could not be put back (${rollback}) and stays at ` +
1899
+ `${park}, where the next open of the index restores it`,
1900
+ );
1901
+ }
1902
+ });
1903
+ lease.assertHeld();
1904
+ // The previous index stays parked through the swap, so a crash between
1905
+ // the renames restores it. Parked indexes are removed only here, once
1906
+ // the new live index has been opened for writing, passed an integrity
1907
+ // check, is the file this rebuild built and has no sibling left beside
1908
+ // it; one that holds more stored embeddings than the new index is kept
1909
+ // (a keyword-only rebuild cannot recompute them, and the rebuild notice
1910
+ // points at it). A new index that fails the check is swapped back out
1911
+ // and the previous one restored.
1912
+ const verdict = keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () =>
1913
+ checkIndexFile(config.dbPath, builtGeneration),
1914
+ );
1915
+ if (verdict.kind === "corrupt") {
1916
+ lease.assertHeld();
1917
+ keepWriterLeasesFresh(SWAP_LEASE_BUDGET_MS, () =>
1918
+ rollBackCorruptSwap(config.dbPath, park, verdict.fault, lease),
1919
+ );
1920
+ }
1921
+ if (verdict.kind === "verified") {
1922
+ lease.assertHeld();
1923
+ keepWriterLeasesFresh(WRITER_LEASE_BLOCKING_BUDGET_MS, () => {
1924
+ lease.assertHeld();
1925
+ pruneParkedIndexes(config.dbPath, builtVectors, lease);
1926
+ });
1927
+ }
1928
+ // What is still parked beside the new live index, and why: the rebuild
1929
+ // names it at its end, so a file that stays beside the index is never a
1930
+ // surprise. Only a verified rebuild prunes, so only it has a set to
1931
+ // report; an unverified swap says which previous index it kept in its
1932
+ // own notice.
1933
+ const keptParked =
1934
+ verdict.kind === "verified"
1935
+ ? parkedIndexesLeftBeside(
1936
+ config.dbPath,
1937
+ builtVectors,
1938
+ opts?.target ?? plainParkedTarget(config.dbPath),
1939
+ )
1940
+ : [];
1941
+ // The swap is over and the live index is in place: the marker names
1942
+ // nothing any more.
1943
+ clearMarkerIfLiveWhole(config.dbPath, lease);
1944
+ progress.advance(INDEX_STAGE.swap);
1945
+ if (verdict.kind === "unverified") {
1946
+ // An inconclusive check is no verdict on the index: the build stands,
1947
+ // nothing is rolled back and nothing parked is removed. The next
1948
+ // rebuild whose check completes prunes what this one kept.
1949
+ const swapUnverified =
1950
+ `the rebuilt index was published at ${config.dbPath}, but its check after the swap ` +
1951
+ "could not complete (another handle on the file, or a busy scan); " +
1952
+ (existsSync(park)
1953
+ ? `the previous index is kept at ${park}`
1954
+ : "there was no previous index to keep");
1955
+ // eslint-disable-next-line no-console
1956
+ console.error(`search index rebuilt: ${swapUnverified}`);
1957
+ return Object.freeze({ ...stats, swapUnverified, durationMs: Date.now() - startedAt });
1958
+ }
1959
+ return Object.freeze({
1960
+ ...stats,
1961
+ // Absent when the rebuild left nothing parked beside the index, so a
1962
+ // rebuild with no parked file emits exactly the shape it emitted
1963
+ // before this field existed.
1964
+ ...(keptParked.length > 0 ? { keptParkedIndexes: keptParked } : {}),
1965
+ durationMs: Date.now() - startedAt,
1966
+ });
1967
+ } finally {
1968
+ recorder?.end();
1969
+ lease.release();
1970
+ }
1971
+ }
1972
+
1973
+ /** index_state key carrying the staging-build compatibility signature. */
1974
+ const REINDEX_SIGNATURE_KEY = "reindex_signature";
1975
+
1976
+ /** Embedding component of the staging signature when no embeddings are computed. */
1977
+ const STAGING_EMBEDDING_OFF = "off";
1978
+
1979
+ /**
1980
+ * Embedding component when the active signature cannot be resolved at
1981
+ * all (semantic search off while embeddings were requested). Carried
1982
+ * over from the pre-suite fallback rendering.
1983
+ */
1984
+ const STAGING_EMBEDDING_UNRESOLVED = "active";
1985
+
1986
+ /** Embedding components that are markers, not embedding signatures. */
1987
+ const STAGING_EMBEDDING_MARKERS: ReadonlySet<string> = new Set([
1988
+ STAGING_EMBEDDING_OFF,
1989
+ STAGING_EMBEDDING_UNRESOLVED,
1990
+ ]);
1991
+
1992
+ /** The parts of a staging signature, compared field by field on resume. */
1993
+ interface StagingSignature {
1994
+ readonly schema: number;
1995
+ readonly chunker: number;
1996
+ readonly chunkSize: number;
1997
+ readonly chunkOverlap: number;
1998
+ readonly chunkMinSize: number;
1999
+ readonly embedding: string;
2000
+ }
2001
+
2002
+ /**
2003
+ * The dimension the staging identity is judged by: the configured one;
2004
+ * the local embedder's fixed default; for a named remote model with none
2005
+ * configured, the model's own native width ({@link MODEL_NATIVE_DIMENSION}).
2006
+ * Null only for an unnamed model, whose identity stays unknown.
2007
+ */
2008
+ function stagingEmbeddingDimension(
2009
+ config: ResolvedSearchConfig,
2010
+ model: string | null,
2011
+ ): EmbeddingIdentity["dimension"] {
2012
+ if (config.semantic.dimension !== null) return config.semantic.dimension;
2013
+ if (config.semantic.provider === "local") return LOCAL_DEFAULT_DIMENSION;
2014
+ return model === null ? null : MODEL_NATIVE_DIMENSION;
2015
+ }
2016
+
2017
+ /**
2018
+ * The embedding component of the staging compatibility signature: the
2019
+ * active embedding signature under the effective dimension, or one of
2020
+ * the named markers above.
2021
+ */
2022
+ function stagingEmbeddingComponent(config: ResolvedSearchConfig, embeddings: boolean): string {
2023
+ if (!embeddings) return STAGING_EMBEDDING_OFF;
2024
+ if (!config.semantic.enabled) return STAGING_EMBEDDING_UNRESOLVED;
2025
+ const model = activeEmbeddingModel(config);
2026
+ return embeddingSignature({
2027
+ provider: config.semantic.provider,
2028
+ model,
2029
+ dimension: stagingEmbeddingDimension(config, model),
2030
+ });
2031
+ }
2032
+
2033
+ /**
2034
+ * Compatibility signature for a staging rebuild: a resume is safe only
2035
+ * when the schema version, chunker rules, chunk parameters, and (when embeddings are
2036
+ * computed) the active embedding signature all match the partial build.
2037
+ * Any drift invalidates the staging DB and forces a fresh rebuild.
2038
+ */
2039
+ function reindexStagingSignature(
2040
+ config: ResolvedSearchConfig,
2041
+ embeddings: boolean,
2042
+ ): StagingSignature {
2043
+ return {
2044
+ schema: LATEST_SCHEMA_VERSION,
2045
+ chunker: CHUNKER_VERSION,
2046
+ chunkSize: config.chunkSize,
2047
+ chunkOverlap: config.chunkOverlap,
2048
+ chunkMinSize: config.chunkMinSize,
2049
+ embedding: stagingEmbeddingComponent(config, embeddings),
2050
+ };
2051
+ }
2052
+
2053
+ /**
2054
+ * Whether a stamped staging marker is compatible with the active
2055
+ * signature. The embedding component goes through
2056
+ * {@link isStaleSignature}, so an unknown identity (an unnamed model)
2057
+ * never compares equal to anything, not even its own stamp; the named
2058
+ * markers and every other field compare by value.
2059
+ */
2060
+ function stagingSignatureCompatible(active: StagingSignature, storedRaw: string): boolean {
2061
+ let stored: Partial<StagingSignature>;
2062
+ try {
2063
+ stored = JSON.parse(storedRaw) as Partial<StagingSignature>;
2064
+ } catch {
2065
+ return false;
2066
+ }
2067
+ if (typeof stored.embedding !== "string") return false;
2068
+ const { embedding: activeEmbedding, ...activeRest } = active;
2069
+ const { embedding: storedEmbedding, ...storedRest } = stored;
2070
+ if (JSON.stringify(activeRest) !== JSON.stringify(storedRest)) return false;
2071
+ if (STAGING_EMBEDDING_MARKERS.has(activeEmbedding)) return activeEmbedding === storedEmbedding;
2072
+ return !isStaleSignature(activeEmbedding, storedEmbedding);
2073
+ }
2074
+
2075
+ /** Read the staging signature from an existing `.new`; false on any
2076
+ * read error (a corrupt or partial staging DB is rebuilt, not trusted). */
2077
+ async function stagingSignatureMatches(
2078
+ tempConfig: ResolvedSearchConfig,
2079
+ signature: StagingSignature,
2080
+ ): Promise<boolean> {
2081
+ try {
2082
+ const store = await Store.open(tempConfig, { mode: "write", loadVec: false });
2083
+ try {
2084
+ const stored = store.getState(REINDEX_SIGNATURE_KEY);
2085
+ return stored !== null && stagingSignatureCompatible(signature, stored);
2086
+ } finally {
2087
+ await store.close();
2088
+ }
2089
+ } catch {
2090
+ return false;
2091
+ }
2092
+ }
2093
+
2094
+ /** Run a short write against the staging DB (set/clear the marker). */
2095
+ async function withStagingStore(
2096
+ tempConfig: ResolvedSearchConfig,
2097
+ fn: (store: Store) => void,
2098
+ ): Promise<void> {
2099
+ const store = await Store.open(tempConfig, { mode: "write", loadVec: false });
2100
+ try {
2101
+ fn(store);
2102
+ } finally {
2103
+ await store.close();
2104
+ }
2105
+ }
2106
+
2107
+ /**
2108
+ * The index generation (a fresh ULID per index file, schema v17) of the
2109
+ * index at `dbPath` when it opens read-only at the current schema; null
2110
+ * when it is absent, unreadable or at another schema. A rebuild compares
2111
+ * the live file's against its staging build's to know that the file now
2112
+ * live is the one it built before it removes the previous one.
2113
+ */
2114
+ function readIndexGeneration(dbPath: string): string | null {
2115
+ if (!existsSync(dbPath)) return null;
2116
+ let db: Database;
2117
+ try {
2118
+ db = new Database(dbPath, { readonly: true });
2119
+ } catch {
2120
+ return null;
2121
+ }
2122
+ try {
2123
+ if (readSchemaVersion(db) !== LATEST_SCHEMA_VERSION) return null;
2124
+ return (
2125
+ db
2126
+ .query<{ value: string }, [string]>("SELECT value FROM index_state WHERE key = ?")
2127
+ .get(STORE_INDEX_GENERATION_KEY)?.value ?? null
2128
+ );
2129
+ } catch {
2130
+ return null;
2131
+ } finally {
2132
+ closeDatabase(db);
2133
+ }
2134
+ }
2135
+
2136
+ /** What {@link checkIndexFile} found. */
2137
+ type IndexFileVerdict =
2138
+ | { readonly kind: "verified" }
2139
+ | { readonly kind: "unverified" }
2140
+ | { readonly kind: "corrupt"; readonly fault: string };
2141
+
2142
+ /**
2143
+ * Open the index at `dbPath` for writing and check it: no sibling beside
2144
+ * it before or after, the current schema, the generation `generation`
2145
+ * names (`undefined`: any), and a passing `PRAGMA quick_check`, whose
2146
+ * completion is recorded so the next write open does not repeat it.
2147
+ * `corrupt` is a failed check; `unverified` is anything else that falls
2148
+ * short (an unreadable file, another generation, a data-bearing journal), which
2149
+ * deletes nothing and undoes nothing.
2150
+ */
2151
+ function checkIndexFile(dbPath: string, generation: string | null | undefined): IndexFileVerdict {
2152
+ const unverified: IndexFileVerdict = { kind: "unverified" };
2153
+ if (generation === null || sqliteJournalsPresent(dbPath).length > 0) return unverified;
2154
+ let db: Database;
2155
+ try {
2156
+ db = new Database(dbPath);
2157
+ } catch {
2158
+ return unverified;
2159
+ }
2160
+ let verdict: IndexFileVerdict = unverified;
2161
+ try {
2162
+ const stored = db
2163
+ .query<{ value: string }, [string]>("SELECT value FROM index_state WHERE key = ?")
2164
+ .get(STORE_INDEX_GENERATION_KEY)?.value;
2165
+ const ours = generation === undefined || stored === generation;
2166
+ if (ours && readSchemaVersion(db) === LATEST_SCHEMA_VERSION) {
2167
+ const check = runIntegrityCheck(db);
2168
+ if (!check.ok) {
2169
+ // A scan that could not complete is no verdict: nothing is undone.
2170
+ verdict =
2171
+ check.inconclusive === true ? unverified : { kind: "corrupt", fault: check.fault };
2172
+ } else {
2173
+ const now = new Date().toISOString();
2174
+ db.run(
2175
+ "INSERT INTO index_state(key, value, updated_at) VALUES (?, ?, ?) " +
2176
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
2177
+ [INTEGRITY_CHECKED_AT_STATE_KEY, now, now],
2178
+ );
2179
+ verdict = { kind: "verified" };
2180
+ }
2181
+ }
2182
+ } catch {
2183
+ verdict = unverified;
2184
+ } finally {
2185
+ closeDatabase(db);
2186
+ }
2187
+ if (verdict.kind === "verified" && sqliteJournalsPresent(dbPath).length > 0) return unverified;
2188
+ return verdict;
2189
+ }
2190
+
2191
+ /** The first of `candidates` that holds no parked main file, or null. */
2192
+ function freeParkPath(...candidates: string[]): string | null {
2193
+ return candidates.find((p) => !existsSync(p)) ?? null;
2194
+ }
2195
+
2196
+ /**
2197
+ * The step that has just verified the live index at `dbPath` (holding
2198
+ * `liveVectors` stored embeddings, null when that count cannot be read)
2199
+ * removes the parked indexes it supersedes: every one but the single
2200
+ * parked index holding the most stored embeddings, and that one too unless
2201
+ * it holds more than the live index. A parked index whose count cannot be
2202
+ * read is kept, and so is every parked index while the live count cannot
2203
+ * be read. What is kept stays under the parked name it has (moving a set
2204
+ * between parked names is itself a split a stop could leave), so the
2205
+ * rebuild notice names the parked paths that exist. A removal that fails
2206
+ * is left for the next verified rebuild.
2207
+ */
2208
+ function pruneParkedIndexes(dbPath: string, liveVectors: number | null, lease: WriterLease): void {
2209
+ const parked = parkedIndexStates(dbPath);
2210
+ const keep = new Set<string>(
2211
+ keptParkedReasons(parked, { present: true, vectors: liveVectors }).keys(),
2212
+ );
2213
+ for (const p of parked) {
2214
+ if (keep.has(p.path)) continue;
2215
+ lease.assertHeld();
2216
+ discardQuietlySet(p.path, lease);
2217
+ }
2218
+ }
2219
+
2220
+ /**
2221
+ * The parked indexes that are still beside the live index after a verified
2222
+ * rebuild: the ones the rule keeps, and the ones whose removal failed (a
2223
+ * reader may hold one open). The rebuild's end line names them, so a file
2224
+ * that stays beside the index is never a surprise.
2225
+ *
2226
+ * `target` is the index the release step must act on: the caller carries
2227
+ * it in, so the step names the index this run names.
2228
+ */
2229
+ function parkedIndexesLeftBeside(
2230
+ dbPath: string,
2231
+ liveVectors: number | null,
2232
+ target: ParkedIndexTarget,
2233
+ ): ReadonlyArray<KeptParkedIndex> {
2234
+ const left = parkedIndexStates(dbPath);
2235
+ const kept = new Map<string, KeptParkedIndex>(
2236
+ keptParkedIndexes(left, { present: true, vectors: liveVectors }, target).map((p) => [
2237
+ p.path,
2238
+ p,
2239
+ ]),
2240
+ );
2241
+ return left.map((p) => {
2242
+ const k = kept.get(p.path);
2243
+ if (k !== undefined) return k;
2244
+ // Not kept by the rule, so the rebuild tried to remove it and the
2245
+ // removal did not succeed: the file is still there.
2246
+ return {
2247
+ ...p,
2248
+ reason: "removal-failed" as const,
2249
+ release: parkedIndexReleaseStep(
2250
+ { path: p.path, reason: "removal-failed", vectors: p.vectors },
2251
+ target,
2252
+ ),
2253
+ };
2254
+ });
2255
+ }
2256
+
2257
+ /**
2258
+ * Whether the swap could park the live index at a free parked name -
2259
+ * decided BEFORE the build, because the parked names and their readability
2260
+ * are known up front. Null when the swap can park it (a name is free, or
2261
+ * the swap's prune would free one), else why it cannot: the same wording
2262
+ * the swap's own refusal uses, for the same state.
2263
+ *
2264
+ * Nothing is removed here. The prune itself stays at the swap, where the
2265
+ * live index has been verified - nothing parked is removed before a
2266
+ * verified successor exists - and where a removal that fails is reported.
2267
+ *
2268
+ * The preflight refuses only what the swap would refuse, and says only
2269
+ * what it has established:
2270
+ *
2271
+ * - a live index whose stored vectors cannot be counted is left to the
2272
+ * build and the swap: it may be a file that fails its check, and the
2273
+ * swap restores the parked `.old` over such a live index, which frees
2274
+ * the name this preflight would have refused for;
2275
+ * - a live index that FAILS its check is left to the build and the swap
2276
+ * for the same reason: the swap puts the parked `.old` back over it.
2277
+ * The verdict comes from the same check the swap runs
2278
+ * ({@link checkIndexFile}), so the two agree on what a live index is;
2279
+ * - whether a removal the prune attempts actually succeeds stays at the
2280
+ * swap, where the removal is made.
2281
+ */
2282
+ function preflightParkNames(dbPath: string, target: ParkedIndexTarget): string | null {
2283
+ const bakPath = dbPath + ".bak";
2284
+ const oldPath = dbPath + ".old";
2285
+ // Nothing to park aside: the swap has no live index to move.
2286
+ if (!existsSync(dbPath)) return null;
2287
+ // A name is free: the swap parks the live index there.
2288
+ if (freeParkPath(bakPath, oldPath) !== null) return null;
2289
+ const liveVectors = countStoredEmbeddings(dbPath);
2290
+ if (liveVectors === null) {
2291
+ // The live index cannot be weighed against the parked ones: the swap
2292
+ // judges it (it restores the parked `.old` over a live index that
2293
+ // fails its check), so the preflight says nothing about it.
2294
+ return null;
2295
+ }
2296
+ // The same order the swap's own refusal names them in.
2297
+ const parked = parkedIndexStates(dbPath);
2298
+ const keep = keptParkedReasons(parked, { present: true, vectors: liveVectors });
2299
+ // The swap's prune removes every parked index but the kept ones, so a
2300
+ // name frees and the swap can park the live index.
2301
+ if (keep.size < parked.length) return null;
2302
+ // No name can be freed by the prune. The swap refuses only when the live
2303
+ // index is not the failed successor it replaces: one that fails its
2304
+ // check is put back over by the parked `.old`, which frees a name. The
2305
+ // same check the swap runs decides it here, so the preflight refuses
2306
+ // only what the swap would refuse.
2307
+ if (checkIndexFile(dbPath, undefined).kind === "corrupt") return null;
2308
+ const unreadable = parked.filter((p) => p.vectors === null).map((p) => p.path);
2309
+ if (unreadable.length === 0) {
2310
+ // Every parked index is readable and every one of them is kept: the
2311
+ // prune would remove none, and the swap's own attempt decides whether
2312
+ // a removal fails.
2313
+ return null;
2314
+ }
2315
+ return unreadableParkedRefusal(unreadable, target);
2316
+ }
2317
+
2318
+ /**
2319
+ * Both parked names are taken and a live index is present: a rebuild
2320
+ * died after swapping its index in and before verifying it, or the parked
2321
+ * indexes are ones no verified rebuild may remove (an unreadable one, one
2322
+ * richer in stored vectors than the live index). The live index is checked
2323
+ * now; verified, it supersedes the parked indexes {@link
2324
+ * pruneParkedIndexes} says it does, which may free a name. Found corrupt,
2325
+ * it is the failed successor: the newest parked index is put back over it.
2326
+ * Which parked set was the failed successor's predecessor is not recorded
2327
+ * once it was published; restoring `.old` keeps `.bak` where it is, the
2328
+ * restored index is parked again by the rebuild that called this, and the
2329
+ * parked sets are then pruned by the same verified rule as after any
2330
+ * rebuild.
2331
+ *
2332
+ * Returns why no name is free, worded as the step that frees one, for the
2333
+ * caller's refusal when both names are still taken. Nothing parked is
2334
+ * removed here unless the verified rule says so, so a parked index whose
2335
+ * stored vectors cannot be counted stays until the operator moves it out
2336
+ * of the way: the refusal names it.
2337
+ */
2338
+ function settleParkedBesideLive(
2339
+ dbPath: string,
2340
+ lease: WriterLease,
2341
+ target: ParkedIndexTarget,
2342
+ ): string {
2343
+ const verdict = checkIndexFile(dbPath, undefined);
2344
+ if (verdict.kind === "verified") {
2345
+ const liveVectors = countStoredEmbeddings(dbPath);
2346
+ lease.assertHeld();
2347
+ pruneParkedIndexes(dbPath, liveVectors, lease);
2348
+ if (liveVectors === null) {
2349
+ return "the live index passes its check but its stored vectors could not be counted, so neither parked index can be weighed against it; run the rebuild again";
2350
+ }
2351
+ const unreadable = parkedIndexPaths(dbPath).filter(
2352
+ (p) => existsSync(p) && countStoredEmbeddings(p) === null,
2353
+ );
2354
+ if (unreadable.length > 0) return unreadableParkedRefusal(unreadable, target);
2355
+ return "a parked index the live index supersedes could not be removed (another process may have it open); run the rebuild again once nothing else has it open";
2356
+ }
2357
+ if (verdict.kind === "corrupt") {
2358
+ try {
2359
+ lease.assertHeld();
2360
+ unparkSqliteFileSet(dbPath + ".old", dbPath, undefined, () => lease.assertHeld());
2361
+ return "the live index failed its check and the parked one was put back";
2362
+ } catch (e) {
2363
+ return (
2364
+ `the live index fails its check (${verdict.fault}) and ${dbPath}.old could not be put ` +
2365
+ `back over it (${e instanceof Error ? e.message : String(e)}); stop everything that uses ` +
2366
+ `the index, move ${dbPath} together with its -wal, -shm and -journal files out of the ` +
2367
+ "folder, and the next open of the index restores the parked one"
2368
+ );
2369
+ }
2370
+ }
2371
+ return "the live index could not be checked (another handle on it, or a busy scan), so it cannot decide between them; run the rebuild again once nothing else has the index open";
2372
+ }
2373
+
2374
+ /**
2375
+ * The new live index failed its integrity check: put the parked previous
2376
+ * index back over it (its rename replaces the corrupt file), or remove the
2377
+ * corrupt file when there was no previous index, and refuse with the
2378
+ * integrity fault. A step that fails is added to the refusal; it never
2379
+ * replaces the fault or skips the restore.
2380
+ */
2381
+ function rollBackCorruptSwap(
2382
+ dbPath: string,
2383
+ parkPath: string,
2384
+ fault: string,
2385
+ lease: WriterLease,
2386
+ ): never {
2387
+ const problems: string[] = [];
2388
+ try {
2389
+ discardSqliteFileSet(dbPath, SWAP_RENAME_SEAMS, () => lease.assertHeld());
2390
+ } catch (e) {
2391
+ problems.push(e instanceof Error ? e.message : String(e));
2392
+ }
2393
+ if (problems.length > 0 && existsSync(parkPath)) {
2394
+ throw new SearchError(
2395
+ "INDEX_UNREADABLE",
2396
+ `the rebuilt index failed its integrity check after the swap (${fault}); the previous index stays parked at ${parkPath} because rejected live files could not all be removed (${problems.join("; ")}); run ${REINDEX_COMMAND} again`,
2397
+ );
2398
+ }
2399
+ let outcome: string;
2400
+ if (existsSync(parkPath)) {
2401
+ lease.assertHeld();
2402
+ try {
2403
+ unparkSqliteFileSet(parkPath, dbPath, SWAP_RENAME_SEAMS, () => lease.assertHeld());
2404
+ clearMarkerIfLiveWhole(dbPath, lease);
2405
+ outcome = `the previous index is back at ${dbPath}`;
2406
+ } catch (e) {
2407
+ outcome = `the previous index could not be put back and is at ${parkPath}`;
2408
+ problems.push(e instanceof Error ? e.message : String(e));
2409
+ }
2410
+ } else {
2411
+ try {
2412
+ lease.assertHeld();
2413
+ discardSqliteFileSet(dbPath, SWAP_RENAME_SEAMS, () => lease.assertHeld());
2414
+ outcome = "there was no previous index, and the rebuilt one was removed";
2415
+ } catch (e) {
2416
+ outcome = "there was no previous index, and the rebuilt one could not be removed";
2417
+ problems.push(e instanceof Error ? e.message : String(e));
2418
+ }
2419
+ }
2420
+ throw new SearchError(
2421
+ "INDEX_UNREADABLE",
2422
+ `the rebuilt index failed its integrity check after the swap (${fault}); ${outcome}; ` +
2423
+ `run ${REINDEX_COMMAND} again` +
2424
+ (problems.length > 0 ? ` (also: ${problems.join("; ")})` : ""),
2425
+ );
2426
+ }
2427
+
2428
+ /**
2429
+ * Clear the park marker once the live main file is back in place, while
2430
+ * the lease is still this run's. A lease lost, or a live path still empty,
2431
+ * leaves the marker for the crash restore of whoever holds the lock next.
2432
+ */
2433
+ function clearMarkerIfLiveWhole(dbPath: string, lease: WriterLease): void {
2434
+ if (!existsSync(dbPath)) return;
2435
+ try {
2436
+ lease.assertHeld();
2437
+ clearParkMarker(dbPath);
2438
+ } catch {
2439
+ // not this run's to clear
2440
+ }
2441
+ }
2442
+
2443
+ /** Remove the journal siblings of `path`, leaving the main file. */
2444
+ function discardSiblings(path: string, lease: WriterLease): void {
2445
+ for (const sibling of sqliteSiblingsPresent(path)) {
2446
+ lease.assertHeld();
2447
+ unlinkWithRetry(sibling);
2448
+ }
2449
+ }
2450
+
2451
+ /** {@link discardSqliteFileSet} that leaves what it cannot remove for the next rebuild. */
2452
+ function discardQuietlySet(path: string, lease: WriterLease): void {
2453
+ try {
2454
+ discardSqliteFileSet(path, undefined, () => lease.assertHeld());
2455
+ } catch {
2456
+ // still held (a reader on Windows): the next rebuild removes it
2457
+ }
2458
+ }
2459
+
2460
+ /**
2461
+ * How long the swap waits for searches reading the staging file, and how
2462
+ * long each of its renames and its WAL fold retry: a search holds the file
2463
+ * for one query, which takes seconds at most.
2464
+ */
2465
+ const STAGING_SWAP_BUDGET_MS = 30_000;
2466
+
2467
+ /**
2468
+ * The most file operations one swap can make, each retried for at most
2469
+ * {@link STAGING_SWAP_BUDGET_MS} on Windows: removing journals of nothing
2470
+ * at the parked name and beside the staging file (3 + 3), parking the live
2471
+ * set (4 renames) and undoing a park that failed part way (4), renaming
2472
+ * the new index in (1), and putting the previous index back after a failed
2473
+ * swap (4) with that move's own undo (4).
2474
+ */
2475
+ const SWAP_MAX_FILE_OPERATIONS = 23;
2476
+
2477
+ /**
2478
+ * How long the lease is kept fresh through the swap: every retry budget the
2479
+ * swap can spend, and a margin. A shorter budget let the lease go stale
2480
+ * while the renames still retried, so another writer could take the lock
2481
+ * over before the publish.
2482
+ */
2483
+ const SWAP_LEASE_BUDGET_MS = SWAP_MAX_FILE_OPERATIONS * STAGING_SWAP_BUDGET_MS + 10_000;
2484
+
2485
+ /** The retry seams of the swap's renames: {@link STAGING_SWAP_BUDGET_MS} on Windows. */
2486
+ const SWAP_RENAME_SEAMS = Object.freeze({ budgetMs: STAGING_SWAP_BUDGET_MS });
2487
+
2488
+ /**
2489
+ * Whether `lease` is still this rebuild's, for its progress record: a
2490
+ * lease taken over (or one that cannot be confirmed) is not.
2491
+ */
2492
+ function leaseStillHeld(lease: WriterLease): boolean {
2493
+ if (lease.lost) return false;
2494
+ try {
2495
+ lease.assertHeld();
2496
+ return true;
2497
+ } catch {
2498
+ return false;
2499
+ }
2500
+ }
2501
+
2502
+ /** A fresh build's staging file and its journal siblings, discarded. */
2503
+ function discardStaging(newPath: string): void {
2504
+ discardSqliteFileSet(newPath);
2505
+ }
2506
+
2507
+ /**
2508
+ * Fold the staging file's WAL into the file before it is renamed: a frame
2509
+ * left in `<staging>-wal` would not follow the rename. A checkpoint that
2510
+ * a reader keeps from completing is retried for
2511
+ * {@link STAGING_SWAP_BUDGET_MS}; one that never completes fails the swap
2512
+ * rather than swap in an index missing its last writes.
2513
+ */
2514
+ async function foldStagingWal(newPath: string): Promise<void> {
2515
+ const db = new Database(newPath);
2516
+ try {
2517
+ db.exec("PRAGMA busy_timeout = 1000");
2518
+ const deadline = Date.now() + STAGING_SWAP_BUDGET_MS;
2519
+ for (;;) {
2520
+ const row = db
2521
+ .query<{ busy: number; log: number; checkpointed: number }, []>(
2522
+ "PRAGMA wal_checkpoint(TRUNCATE)",
2523
+ )
2524
+ .get();
2525
+ if (row === null || (row.busy === 0 && row.log === row.checkpointed)) break;
2526
+ if (Date.now() >= deadline) {
2527
+ throw new SearchError(
2528
+ "INDEX_LOCKED",
2529
+ `the staging index ${newPath} could not be checkpointed before the swap: a reader kept it busy`,
2530
+ );
2531
+ }
2532
+ // eslint-disable-next-line no-await-in-loop
2533
+ await Bun.sleep(50);
2534
+ }
2535
+ try {
2536
+ db.exec("PRAGMA journal_mode = DELETE");
2537
+ } catch {
2538
+ // another connection still has it open: the WAL is empty, which is all the rename needs
2539
+ }
2540
+ } finally {
2541
+ closeDatabase(db);
2542
+ }
2543
+ }
2544
+
2545
+ /**
2546
+ * Undo the first half of a reindex swap whose second rename failed: put the
2547
+ * previous index (parked at `.bak` or `.old`) back at the live path, so the
2548
+ * failure reads as "reindex refused, old index intact" rather than "no
2549
+ * search index" until the next `Store.open` happens to run its
2550
+ * crash-restore (#187). Nothing parked is a fresh reindex with nothing to
2551
+ * restore.
2552
+ *
2553
+ * Returns null when the previous index is back (or there was none), else
2554
+ * why it is not: the caller keeps the swap's own error first and adds
2555
+ * this, so a refusal never claims a restore that failed. The parked set
2556
+ * then stays where it is (`sqlite-file-set.ts` never moves the main file
2557
+ * back without its journals) and the crash-restore in `Store.open`
2558
+ * recovers it.
2559
+ *
2560
+ * `.new` is left in place. It holds a complete build, and in the Windows
2561
+ * case that motivates this path it is the very file a sharing violation
2562
+ * refuses to move, so deleting it would only spend a second retry budget;
2563
+ * the next reindex discards it (or resumes from it with `resumeReindex`).
2564
+ */
2565
+ function restoreLiveFromBak(bakPath: string, dbPath: string, lease: WriterLease): string | null {
2566
+ const occupied = [dbPath, ...sqliteSiblingsPresent(dbPath)].filter((p) => existsSync(p));
2567
+ if (occupied.length > 0) {
2568
+ return `the live path is occupied (${occupied.join(", ")}); the previous index stays at ${bakPath}`;
2569
+ }
2570
+ try {
2571
+ unparkSqliteFileSet(bakPath, dbPath, undefined, () => lease.assertHeld());
2572
+ return null;
2573
+ } catch (err) {
2574
+ return err instanceof Error ? err.message : String(err);
2575
+ }
2576
+ }
2577
+
2578
+ // ─────────────────────────────────────────────────────────────────────────────
2579
+ // indexStatus
2580
+ // ─────────────────────────────────────────────────────────────────────────────
2581
+
2582
+ /**
2583
+ * How many held chunks the status snapshot names. A vault can hold
2584
+ * thousands of chunks after a model swap, and the status JSON is read by
2585
+ * humans and by agents on a token budget; the report's `total` carries
2586
+ * the whole so the cap is a disclosure, not a concealment.
2587
+ */
2588
+ export const HELD_CHUNK_REPORT_CAP = 20;
2589
+
2590
+ export async function indexStatus(config: ResolvedSearchConfig): Promise<IndexStatusSnapshot> {
2591
+ let store: Store;
2592
+ try {
2593
+ store = await Store.open(config, { mode: "read" });
2594
+ } catch (e) {
2595
+ if (e instanceof SearchError && e.code === "INDEX_MISSING") {
2596
+ return Object.freeze({
2597
+ indexPath: config.dbPath,
2598
+ exists: false,
2599
+ schemaVersion: null,
2600
+ documents: 0,
2601
+ chunks: 0,
2602
+ embeddings: 0,
2603
+ staleEmbeddings: 0,
2604
+ embeddingModel: null,
2605
+ embeddingDimension: null,
2606
+ embeddingSignature: activeEmbeddingSignature(config),
2607
+ estimatedRefreshCostUsd: 0,
2608
+ refreshPriceSource: null,
2609
+ vecExtension: "unknown" as const,
2610
+ semanticEnabled: config.semantic.enabled,
2611
+ embeddingKeyPresent: !!config.semantic.apiKey,
2612
+ lastIndexedAt: null,
2613
+ lastFullIndexAt: null,
2614
+ embeddingAbi: Object.freeze([]),
2615
+ warnings: Object.freeze([]),
2616
+ });
2617
+ }
2618
+ // An index on an older schema is upgraded in place, exactly as the
2619
+ // query path upgrades it: the same decision (`planIndexRepair`), the
2620
+ // same helper. Reporting a rebuild here would send the user to a
2621
+ // minute of work for an upgrade that takes seconds and keeps every
2622
+ // stored embedding. An index no upgrade can repair keeps the refusal
2623
+ // it always had - the rebuild advice is right for those.
2624
+ if (e instanceof SearchError && e.code === "SCHEMA_MISMATCH") {
2625
+ const heal = await import("./self-heal.ts");
2626
+ store = await heal.openReadWithUpgrade(config);
2627
+ } else {
2628
+ throw e;
2629
+ }
2630
+ }
2631
+ try {
2632
+ const counts = store.counts();
2633
+ const model = store.getState("embedding_model");
2634
+ const dimRaw = store.getState("embedding_dimension");
2635
+ const dim = dimRaw ? Number(dimRaw) : null;
2636
+ const last = store.getState(LAST_INDEXED_AT_STATE_KEY);
2637
+ const full = store.getState(LAST_FULL_INDEX_AT_STATE_KEY);
2638
+
2639
+ const warnings: string[] = [];
2640
+ if (config.semantic.enabled && !store.vecLoaded()) {
2641
+ warnings.push("sqlite-vec unavailable; semantic search disabled this session");
2642
+ }
2643
+ // A FIFTH site that derived the credential fact for itself, in a
2644
+ // fourth spelling, and which the unit-F brief did not name. Routed
2645
+ // through the same resolver while the file is open: two of these
2646
+ // copies disagreed about whether the local provider needs a key.
2647
+ if (
2648
+ resolveSemanticCapability(config.semantic).tier === SEMANTIC_CAPABILITY_TIER.credentialMissing
2649
+ ) {
2650
+ warnings.push(await semanticCapabilityLabel(SEMANTIC_CAPABILITY_CODE.credentialMissing));
2651
+ }
2652
+
2653
+ // Instruction-prefix drift (memory-write-path-integrity B2). Stored
2654
+ // vectors were embedded under the prefix pair recorded at index time; if
2655
+ // the configured pair now differs they are not comparable to prefixed
2656
+ // queries, so surface the reindex-required warning. A stored null is a
2657
+ // pre-feature (unprefixed) index, compared as the empty pair.
2658
+ if (config.semantic.enabled && counts.embeddings > 0) {
2659
+ const storedQuery = store.getState(EMBEDDING_PREFIX_QUERY_STATE_KEY) ?? "";
2660
+ const storedPassage = store.getState(EMBEDDING_PREFIX_PASSAGE_STATE_KEY) ?? "";
2661
+ const configuredQuery = config.semantic.queryPrefix ?? "";
2662
+ const configuredPassage = config.semantic.passagePrefix ?? "";
2663
+ if (storedQuery !== configuredQuery || storedPassage !== configuredPassage) {
2664
+ warnings.push(
2665
+ "embedding instruction prefixes changed since the last index run " +
2666
+ `(stored [${storedQuery}|${storedPassage}], configured ` +
2667
+ `[${configuredQuery}|${configuredPassage}]); run: o2b search reindex --embeddings`,
2668
+ );
2669
+ }
2670
+ }
2671
+
2672
+ // Embedding-ABI drift (context-integrity-gates, Unit E). The read
2673
+ // open already ran the gated comparison, so this only surfaces what
2674
+ // it found: empty when the stamps agree AND whenever the operator
2675
+ // has `integrity.embedding_abi` off. Gated on stored vectors for the
2676
+ // same reason the prefix warning above is - an index with no
2677
+ // embeddings has nothing that could be incomparable.
2678
+ //
2679
+ // Reported twice, deliberately: as one operator-facing line here and
2680
+ // as the structured `embeddingAbi` field below. The MCP status block
2681
+ // carries both, so an agent can branch on the field instead of
2682
+ // matching on message text.
2683
+ const abiDrift =
2684
+ config.semantic.enabled && counts.embeddings > 0
2685
+ ? store.embeddingAbiMismatches()
2686
+ : Object.freeze([] as ReadonlyArray<StampMismatch>);
2687
+ if (abiDrift.length > 0) {
2688
+ warnings.push(formatEmbeddingAbiDrift(abiDrift));
2689
+ }
2690
+
2691
+ // Oversize-chunk census (what-the-index-already-knew, task H). The
2692
+ // two reportable states leave by different doors, following the
2693
+ // convention the ABI drift beside them already sets: the warning
2694
+ // channel is for what an operator can act on, the structured field
2695
+ // for what is simply true.
2696
+ //
2697
+ // - chunks past a DECLARED window is a measured fault with a
2698
+ // command behind it, so it is a warning. So is the undecided
2699
+ // band beside it: the census cannot rule the truncation out, the
2700
+ // remedy is the same lever, and it fires only for chunks that
2701
+ // actually carry non-ASCII text near the window - never on the
2702
+ // all-Latin index, which is what keeps it from becoming noise;
2703
+ // - a model with no declared window is a check that could not run.
2704
+ // It has no command - nobody can declare a window for someone
2705
+ // else's model - and it is the COMMON case, so a warning here
2706
+ // would repeat forever on the majority of configurations and
2707
+ // train operators to skip the channel. It rides the snapshot as
2708
+ // its own field instead, which still distinguishes it from a
2709
+ // pass.
2710
+ //
2711
+ // A census that cleared BOTH bounds is neither, so a status that had
2712
+ // no warning before this feature still has none.
2713
+ const chunkWindow = censusChunkWindow(store, config, model);
2714
+ const chunkWindowUndeclared = chunkWindow?.verdict === "window-undeclared" ? chunkWindow : null;
2715
+ if (
2716
+ chunkWindow !== null &&
2717
+ (chunkWindow.verdict === "over-window" || chunkWindow.verdict === "estimate-undecided")
2718
+ ) {
2719
+ warnings.push(await formatChunkWindowMeasured(chunkWindow));
2720
+ }
2721
+
2722
+ // What the index holds back right now (chunk skip-and-hold, F2), read
2723
+ // from the durable records under the ACTIVE configuration's key. A
2724
+ // row whose key a config change released is a decision the next run
2725
+ // will not honour, so it is not a hold this status would report, and
2726
+ // a configuration that can hold nothing (no model, no declared
2727
+ // window) reads nothing. Absent unless something matches the key -
2728
+ // the same byte discipline as the census field beside it.
2729
+ let heldChunks: HeldChunkReport | undefined;
2730
+ const holdKey = config.semantic.enabled ? chunkHoldExclusion(config) : null;
2731
+ if (holdKey !== null) {
2732
+ const heldCensus = store.heldChunkCensus(holdKey, HELD_CHUNK_REPORT_CAP);
2733
+ if (heldCensus.total > 0) {
2734
+ const items: HeldChunkReportItem[] = heldCensus.rows.map((row) =>
2735
+ Object.freeze({
2736
+ path: row.path,
2737
+ chunkIndex: row.chunkIndex,
2738
+ estimatedTokens: row.estimatedTokens,
2739
+ windowTokens: row.windowTokens,
2740
+ // The only decision the hold table records.
2741
+ reason: CHUNK_HOLD_REASON.overDeclaredWindow,
2742
+ }),
2743
+ );
2744
+ heldChunks = Object.freeze({ total: heldCensus.total, items: Object.freeze(items) });
2745
+ }
2746
+ }
2747
+
2748
+ // Best-effort spend estimate to bring stale/missing embeddings current,
2749
+ // from the shared spend plan. Chunk content is scanned only when the
2750
+ // price is a positive known rate: a known-free model costs 0. An
2751
+ // unknown price is unknown only while chunks are pending - a fully
2752
+ // embedded index has nothing to pay for, so it reads 0, counted
2753
+ // without loading a chunk body.
2754
+ let estimatedRefreshCostUsd: number | null = 0;
2755
+ let refreshPriceSource: EmbeddingPriceSource | null = null;
2756
+ if (config.semantic.enabled) {
2757
+ const { quote } = activeSpendQuote(config);
2758
+ refreshPriceSource = quote.source;
2759
+ if (quote.usdPerMtok !== null && quote.usdPerMtok > 0) {
2760
+ estimatedRefreshCostUsd = planEmbeddingSpend(store, config).estimatedUsd;
2761
+ } else if (
2762
+ quote.usdPerMtok === null &&
2763
+ store.countChunksWithoutEmbeddings(undefined, chunkHoldExclusion(config) ?? undefined) > 0
2764
+ ) {
2765
+ estimatedRefreshCostUsd = null;
2766
+ } else {
2767
+ estimatedRefreshCostUsd = 0;
2768
+ }
2769
+ }
2770
+
2771
+ return Object.freeze({
2772
+ indexPath: config.dbPath,
2773
+ exists: true,
2774
+ schemaVersion: store.schemaVersion(),
2775
+ documents: counts.documents,
2776
+ chunks: counts.chunks,
2777
+ embeddings: counts.embeddings,
2778
+ staleEmbeddings: counts.staleEmbeddings,
2779
+ embeddingModel: model,
2780
+ embeddingDimension: dim,
2781
+ embeddingSignature: activeEmbeddingSignature(config, model, dim),
2782
+ estimatedRefreshCostUsd,
2783
+ refreshPriceSource,
2784
+ vecExtension: store.vecLoaded() ? ("loaded" as const) : ("unavailable" as const),
2785
+ semanticEnabled: config.semantic.enabled,
2786
+ embeddingKeyPresent: !!config.semantic.apiKey,
2787
+ lastIndexedAt: last,
2788
+ lastFullIndexAt: full,
2789
+ embeddingAbi: abiDrift,
2790
+ // Absent, not null, whenever the check could run - so a status
2791
+ // over a curated model serializes the bytes it always has.
2792
+ ...(chunkWindowUndeclared === null ? {} : { chunkWindowUndeclared }),
2793
+ ...(heldChunks === undefined ? {} : { heldChunks }),
2794
+ warnings: Object.freeze(warnings),
2795
+ });
2796
+ } finally {
2797
+ await store.close();
2798
+ }
2799
+ }
2800
+
2801
+ // ─────────────────────────────────────────────────────────────────────────────
2802
+ // indexBehindCount
2803
+ // ─────────────────────────────────────────────────────────────────────────────
2804
+
2805
+ /**
2806
+ * What the next incremental run would do, measured live (t_e4438152).
2807
+ */
2808
+ export interface IndexBehind {
2809
+ /** `unindexed + changed + deleted`: the run's whole to-do list. */
2810
+ readonly behind: number;
2811
+ /** Walked files with no stored row: the run would add them. */
2812
+ readonly unindexed: number;
2813
+ /** Stored mtime or size differs: the run would re-read and hash them. */
2814
+ readonly changed: number;
2815
+ /** Stored paths the walk never saw: the run would delete them. */
2816
+ readonly deleted: number;
2817
+ }
2818
+
2819
+ /**
2820
+ * The live index-behind census: how many documents the next incremental
2821
+ * run would add, update or delete, measured now rather than read back
2822
+ * from the last completed run's count.
2823
+ *
2824
+ * Exactly the incremental fastpath's comparison, without the reads:
2825
+ * `walkVault` yields the in-scope `.md` tree stat-only (no content read,
2826
+ * no hash - the cost is one `readdir` plus one `stat` per entry), and
2827
+ * every walked file is classified against the stored row:
2828
+ *
2829
+ * - `unindexed`: walked, no stored row;
2830
+ * - `changed`: stored mtime (seconds) or size differs - the fastpath
2831
+ * miss the next run must read and hash;
2832
+ * - `deleted`: a stored path the walk never saw.
2833
+ *
2834
+ * Two deliberate semantics, shared with the fastpath this replicates:
2835
+ *
2836
+ * 1. Upper bound. A touch-only file (identical bytes, bumped mtime)
2837
+ * counts as changed: the walk never hashes, so "behind" means
2838
+ * "what the next run would re-read", not "notes missing from
2839
+ * answers".
2840
+ * 2. Second granularity. Stored mtimes are seconds, so an edit that
2841
+ * lands twice within its indexed second at the same size reads as
2842
+ * unchanged. The run after it catches it; do not "fix" that here.
2843
+ *
2844
+ * Read-only and self-contained: one read-mode store open, no writes, no
2845
+ * freshen claim, no state file - nothing registers anywhere. On ANY
2846
+ * failure - a missing or unreadable index, a walk that throws - the
2847
+ * answer is `null`: a failed measurement is not a measurement, and
2848
+ * `null` is never a zero.
2849
+ */
2850
+ export async function indexBehindCount(config: ResolvedSearchConfig): Promise<IndexBehind | null> {
2851
+ let store: Store;
2852
+ try {
2853
+ store = await Store.open(config, { mode: "read" });
2854
+ } catch {
2855
+ return null; // No index, or one that would not open: not measured.
2856
+ }
2857
+ try {
2858
+ const existing = store.listDocuments();
2859
+ const seen = new Set<string>();
2860
+ let unindexed = 0;
2861
+ let changed = 0;
2862
+ for (const file of walkVault(config)) {
2863
+ seen.add(file.relPath);
2864
+ const prev = existing.get(file.relPath);
2865
+ if (prev === undefined) {
2866
+ unindexed++;
2867
+ } else if (
2868
+ prev.mtime !== Math.floor(file.stat.mtimeMs / 1000) ||
2869
+ prev.size !== file.stat.size
2870
+ ) {
2871
+ changed++;
2872
+ }
2873
+ }
2874
+ let deleted = 0;
2875
+ for (const path of existing.keys()) {
2876
+ if (!seen.has(path)) deleted++;
2877
+ }
2878
+ return Object.freeze({
2879
+ behind: unindexed + changed + deleted,
2880
+ unindexed,
2881
+ changed,
2882
+ deleted,
2883
+ });
2884
+ } catch {
2885
+ return null;
2886
+ } finally {
2887
+ try {
2888
+ await store.close();
2889
+ } catch {
2890
+ // A close failure must not unseat the measurement (or the null).
2891
+ }
2892
+ }
2893
+ }
2894
+
2895
+ // ─────────────────────────────────────────────────────────────────────────────
2896
+ // indexRootCoverage
2897
+ // ─────────────────────────────────────────────────────────────────────────────
2898
+
2899
+ /**
2900
+ * Which authorized note roots the index REACHED, and how far.
2901
+ *
2902
+ * The field names say presence rather than coverage on purpose. "Covered"
2903
+ * would claim the root was read out; what the index can show is that at
2904
+ * least one document under it was indexed, which is a strictly weaker
2905
+ * statement - see {@link indexRootCoverage}.
2906
+ */
2907
+ export interface IndexRootCoverage {
2908
+ /** Roots carrying at least one indexed (and, when filtered, admitted) document. */
2909
+ readonly rootsWithDocuments: ReadonlyArray<string>;
2910
+ /** Roots the index holds no (admitted) document under at all. */
2911
+ readonly rootsWithoutDocuments: ReadonlyArray<string>;
2912
+ }
2913
+
2914
+ /** The visibility an unmeasured indexed document answers `admit` with. */
2915
+ const NO_INDEXED_TAGS: ReadonlyArray<string> = Object.freeze([]);
2916
+
2917
+ /**
2918
+ * Partition note roots by whether the index carries any document under
2919
+ * them (silence-is-not-an-answer, U2).
2920
+ *
2921
+ * `indexStatus` says how much was indexed in total; this says WHICH of
2922
+ * the folders the operator authorized were reached at all. A negative
2923
+ * recall needs both: the totals make the receipt, and the partition names
2924
+ * the roots that were never touched.
2925
+ *
2926
+ * The guarantee is deliberately named as presence, not coverage, and the
2927
+ * field names say so: a root lands in `rootsWithDocuments` on the
2928
+ * strength of ONE indexed document, so one note out of a thousand puts it
2929
+ * there. The index knows what it was given and never what it was not, so
2930
+ * it cannot tell that case from a folder that holds exactly one note;
2931
+ * deciding between them needs a filesystem census of the root, which is a
2932
+ * different measurement with a different cost. Until something needs that
2933
+ * census, the honest move is to promise only what this scan sees - the
2934
+ * document TOTAL rides on the receipt beside the root list, so a reader
2935
+ * weighing a negative is never left with the root list alone.
2936
+ *
2937
+ * Throws `SearchError` `INDEX_MISSING` when there is no index, rather
2938
+ * than reporting every root absent. The caller must establish that the
2939
+ * index exists first, and an all-absent answer over a missing index would
2940
+ * read like a measurement.
2941
+ *
2942
+ * `admit`, when given, decides which indexed documents count: a root is
2943
+ * reached only through a document `admit` accepts. It receives the path
2944
+ * and the visibility tokens the index measured for it (empty when none
2945
+ * were measured), so a caller below local reach can count only the pages
2946
+ * it may read and a root holding nothing else answers exactly like an
2947
+ * empty one. It is asked lazily, root by root, and stops at the first
2948
+ * admitted document. Omitted, every indexed document counts and nothing
2949
+ * beyond the path scan is read.
2950
+ *
2951
+ * Cost: one read-mode open and one full document-path scan, plus one
2952
+ * visibility lookup per candidate asked of `admit`. It runs only on the
2953
+ * recall gate's zero-result path, where a search has already failed to
2954
+ * produce anything, and the alternative - a per-root prefix query - would
2955
+ * buy microseconds for a new store surface.
2956
+ */
2957
+ export async function indexRootCoverage(
2958
+ config: ResolvedSearchConfig,
2959
+ roots: ReadonlyArray<string>,
2960
+ admit?: (path: string, indexedTags: ReadonlyArray<string>) => boolean,
2961
+ ): Promise<IndexRootCoverage> {
2962
+ const store = await Store.open(config, { mode: "read" });
2963
+ try {
2964
+ const paths = [...store.listDocuments().keys()];
2965
+ const withDocuments: string[] = [];
2966
+ const withoutDocuments: string[] = [];
2967
+ for (const root of roots) {
2968
+ // Segment-wise: a root of `Notes` is not reached by a document in
2969
+ // `Notes-archive/`. Roots arrive from `resolveNoteRoots`, which
2970
+ // normalises them, and indexed paths are what the walker wrote.
2971
+ const reached = paths.some(
2972
+ (path) =>
2973
+ pathCovers(root, path) &&
2974
+ (admit === undefined ||
2975
+ admit(path, store.indexedVisibilityByPaths([path]).get(path) ?? NO_INDEXED_TAGS)),
2976
+ );
2977
+ (reached ? withDocuments : withoutDocuments).push(root);
2978
+ }
2979
+ return Object.freeze({
2980
+ rootsWithDocuments: Object.freeze(withDocuments),
2981
+ rootsWithoutDocuments: Object.freeze(withoutDocuments),
2982
+ });
2983
+ } finally {
2984
+ await store.close();
2985
+ }
2986
+ }
2987
+
2988
+ // ─────────────────────────────────────────────────────────────────────────────
2989
+ // indexCheck
2990
+ // ─────────────────────────────────────────────────────────────────────────────
2991
+
2992
+ function isDirectoryWritable(dir: string): boolean {
2993
+ try {
2994
+ // `recursive: true` is idempotent — no separate existsSync check.
2995
+ mkdirSync(dir, { recursive: true });
2996
+ accessSync(dir, constants.W_OK);
2997
+ return true;
2998
+ } catch {
2999
+ return false;
3000
+ }
3001
+ }
3002
+
3003
+ /** What one `indexCheck` run may do beyond reading this machine. */
3004
+ export interface IndexCheckOptions {
3005
+ /**
3006
+ * Whether to make the one outbound call this report can make: a single
3007
+ * `ping` at the configured embedding provider. Defaults to `true`,
3008
+ * which is what every release before it has done, so a caller that
3009
+ * passes nothing gets the report it has always got. `false` produces
3010
+ * the `skipped` probe state - never a pass and never a fault, because
3011
+ * a call nobody made proves neither.
3012
+ */
3013
+ readonly probeProvider?: boolean;
3014
+ /**
3015
+ * The env and provider registry the credential-source report reads
3016
+ * names from. Passed explicitly so the report never reads the process
3017
+ * on its own; absent, the report is not built and the result carries no
3018
+ * `credentialSources` field.
3019
+ */
3020
+ readonly credentialContext?: CredentialSourceContext;
3021
+ }
3022
+
3023
+ export async function indexCheck(
3024
+ config: ResolvedSearchConfig,
3025
+ opts?: IndexCheckOptions,
3026
+ ): Promise<IndexCheckReport> {
3027
+ const warnings: string[] = [];
3028
+ const fatal: string[] = [];
3029
+ // One resolver for what the operator configured, shared with the index
3030
+ // run, the semantic lane and the readiness probe
3031
+ // (provenance-at-the-boundary, F1).
3032
+ const capability = resolveSemanticCapability(config.semantic);
3033
+
3034
+ let vaultReadable = false;
3035
+ try {
3036
+ // No vault (design D14): the index holds the brain store only, which
3037
+ // the store checks report on; there is no vault to read.
3038
+ if (config.vault === null) {
3039
+ vaultReadable = true;
3040
+ } else if (statSync(config.vault).isDirectory()) {
3041
+ vaultReadable = true;
3042
+ } else {
3043
+ fatal.push(`vault path exists but is not a directory: ${config.vault}`);
3044
+ }
3045
+ } catch {
3046
+ fatal.push(`vault not readable: ${config.vault}`);
3047
+ }
3048
+
3049
+ const dir = dirname(config.dbPath);
3050
+ const indexDirWritable = isDirectoryWritable(dir);
3051
+ if (!indexDirWritable) fatal.push(`index directory not writable: ${dir}`);
3052
+
3053
+ let sqliteOk = false;
3054
+ let fts5Ok = false;
3055
+ let vecExtension: "loaded" | "unavailable" | "not-attempted" = "not-attempted";
3056
+ /** Runtime ABI token; captured from the probe rather than re-queried. */
3057
+ let vecVersion: string | null = null;
3058
+ try {
3059
+ // Use an in-memory DB so the check never touches the real index.
3060
+ // bun:sqlite is imported statically; the open below is the probe.
3061
+ const db = new Database(":memory:");
3062
+ sqliteOk = true;
3063
+ try {
3064
+ db.exec(
3065
+ "CREATE VIRTUAL TABLE probe USING fts5(content, tokenize='unicode61 remove_diacritics 2')",
3066
+ );
3067
+ fts5Ok = true;
3068
+ } catch (e) {
3069
+ const msg = e instanceof Error ? e.message : String(e);
3070
+ fatal.push(`FTS5 not available: ${msg}`);
3071
+ }
3072
+ // Probed whenever semantic search is switched on at all - including
3073
+ // while the credential is still missing, because the extension is a
3074
+ // machine fact the operator can fix independently of the key.
3075
+ if (capability.tier !== SEMANTIC_CAPABILITY_TIER.disabled) {
3076
+ try {
3077
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
3078
+ const vec = require("sqlite-vec") as { getLoadablePath(): string };
3079
+ db.loadExtension(vec.getLoadablePath());
3080
+ const row = db.query<{ v: string }, []>("SELECT vec_version() AS v").get();
3081
+ vecVersion = typeof row?.v === "string" ? row.v : null;
3082
+ vecExtension = "loaded";
3083
+ } catch (e) {
3084
+ vecExtension = "unavailable";
3085
+ warnings.push(`sqlite-vec unavailable: ${e instanceof Error ? e.message : String(e)}`);
3086
+ }
3087
+ }
3088
+ closeDatabase(db);
3089
+ } catch (e) {
3090
+ fatal.push(`bun:sqlite open failed: ${e instanceof Error ? e.message : String(e)}`);
3091
+ }
3092
+
3093
+ // "The credential side of the configuration is satisfied" - which for
3094
+ // the offline local provider means it needed none. This used to read
3095
+ // `enabled && apiKey`, which reported a fully working local install as
3096
+ // key-less and then recommended setting a key it does not use.
3097
+ const embeddingKeyResolved = !semanticCapabilityIsBlocked(capability);
3098
+ if (capability.tier === SEMANTIC_CAPABILITY_TIER.credentialMissing) {
3099
+ warnings.push(await semanticCapabilityLabel(capability.code));
3100
+ }
3101
+
3102
+ // The live probe (wiring-what-exists, E1). Four decisions, each one
3103
+ // the difference between two states a single verdict used to blur:
3104
+ //
3105
+ // - A recorded DECLINE is `skipped`, with the consent's own sentence
3106
+ // as the reason - decided, before the tiers are consulted. The two
3107
+ // decline keys refuse independently, and the operator who wrote one
3108
+ // made the same decision either way; reporting that as
3109
+ // `not-configured` merged a decision with an absence and read a
3110
+ // broken configuration as one that was never finished.
3111
+ // - Nothing configured is `not-configured`, not a failed probe. The
3112
+ // absence of a provider is not a broken provider, and it costs no
3113
+ // network call: `probeProvider` is never reached on that arm.
3114
+ // - An unconfigured setup takes that arm even when the caller asked
3115
+ // for no probe, because "there is nothing to ask" is established
3116
+ // without asking and is the more specific true statement.
3117
+ // - Only a provider that ANSWERED with a refusal is a fatal finding.
3118
+ // A probe that did not complete goes to `warnings`, because it
3119
+ // proved nothing, and the CLI gives it an exit code of its own so
3120
+ // it is not read as either verdict.
3121
+ const consent = resolveProviderConsent({
3122
+ configPath: config.configPath ?? null,
3123
+ env: process.env,
3124
+ semantic: config.semantic,
3125
+ });
3126
+ const consentDeclined = providerConsentIsDeclined(consent);
3127
+ const probe = consentDeclined
3128
+ ? Object.freeze({ state: PROVIDER_PROBE.skipped, reason: consent.detail })
3129
+ : !embeddingKeyResolved
3130
+ ? PROVIDER_PROBE_NOT_CONFIGURED
3131
+ : opts?.probeProvider === false
3132
+ ? PROVIDER_PROBE_SKIPPED
3133
+ : await probeProvider(() => makeProvider(config.semantic, consent));
3134
+ const providerProbe = probe.state;
3135
+ const providerReason = probe.reason;
3136
+ if (providerProbe === PROVIDER_PROBE.unreachable) {
3137
+ fatal.push(`embedding provider unreachable: ${providerReason}`);
3138
+ } else if (providerProbe === PROVIDER_PROBE.timedOut) {
3139
+ warnings.push(`embedding provider probe did not complete: ${providerReason}`);
3140
+ }
3141
+
3142
+ // Stored-versus-runtime embedding ABI (context-integrity-gates, Unit
3143
+ // E). The probe above deliberately runs in memory and never touches
3144
+ // the real index, so the stored side is read explicitly here - without
3145
+ // it there is nothing to compare against.
3146
+ //
3147
+ // This is the DIAGNOSTIC surface, so it compares ungated: an operator
3148
+ // who ran `search check` asked to be told. The gate governs the read
3149
+ // path, which is where a comparison can refuse; a report cannot.
3150
+ const recordedAbi = config.semantic.enabled ? readEmbeddingAbiSync(config.dbPath) : null;
3151
+ const embeddingAbi =
3152
+ recordedAbi === null
3153
+ ? Object.freeze([] as ReadonlyArray<StampMismatch>)
3154
+ : compareStamps(recordedAbi, runtimeEmbeddingAbi(config, vecVersion));
3155
+ if (embeddingAbi.length > 0) warnings.push(formatEmbeddingAbiDrift(embeddingAbi));
3156
+
3157
+ // The measured pending-vector count (nothing-writes-silently, unit A),
3158
+ // read through the same explicit peek the ABI tokens use and for the
3159
+ // same reason. Two `COUNT(*)`s on a read-only handle; the report is a
3160
+ // diagnostic an operator ran, never the query path. The config's own
3161
+ // chunk-hold exclusion rides along: a held chunk is not work the index
3162
+ // owes a vector for, and counting it here would recommend a backfill
3163
+ // that finds nothing to do and never clears.
3164
+ const pendingVectors = readPendingVectorCensus(
3165
+ config.dbPath,
3166
+ config.semantic.enabled ? (chunkHoldExclusion(config) ?? undefined) : undefined,
3167
+ );
3168
+
3169
+ // The record-vs-data embedder audit (nothing-writes-silently, unit G).
3170
+ // Ungated by the semantic switch on purpose: it compares the index's
3171
+ // record against the index's own data, so what this build is
3172
+ // configured to do next cannot change the answer.
3173
+ const embedderRecord = readEmbedderRecordCensusSync(config.dbPath);
3174
+ const contradiction = formatEmbedderRecordContradiction(embedderRecord);
3175
+ if (contradiction !== null) warnings.push(contradiction);
3176
+
3177
+ // The visibility honesty finding (nothing-writes-silently, unit H,
3178
+ // form B). Ungated by the semantic switch, like embedderRecord beside
3179
+ // it: this reads chunk content the indexer already wrote, regardless
3180
+ // of whether embeddings are configured at all.
3181
+ const visibilityHonesty = readVisibilityHonestyFinding(config.dbPath);
3182
+
3183
+ // §E.2 — Actionable hints derived from the check state.
3184
+ // Rules match the design doc table; agents and operators read the
3185
+ // list to know what command to run next without learning the
3186
+ // internals of OSB.
3187
+ // Names only, and only for a credential-missing tier: every other tier
3188
+ // yields null and the result stays byte-identical.
3189
+ const credentialSources =
3190
+ opts?.credentialContext === undefined
3191
+ ? null
3192
+ : describeCredentialSources({ semantic: config.semantic, ...opts.credentialContext });
3193
+
3194
+ const recommendations = buildRecommendations({
3195
+ config,
3196
+ embeddingKeyResolved,
3197
+ vecExtension,
3198
+ providerProbe,
3199
+ embeddingAbi,
3200
+ pendingVectors,
3201
+ embedderRecord,
3202
+ });
3203
+
3204
+ return Object.freeze({
3205
+ vaultReadable,
3206
+ indexDirWritable,
3207
+ sqliteOk,
3208
+ fts5Ok,
3209
+ embeddingAbi,
3210
+ pendingVectors,
3211
+ embedderRecord,
3212
+ // Absent, not null: a vault that has never used the field gets no
3213
+ // key at all, so its JSON stays byte-identical to before this unit.
3214
+ ...(visibilityHonesty === null ? {} : { visibilityHonesty }),
3215
+ vecExtension,
3216
+ embeddingKeyResolved,
3217
+ providerProbe,
3218
+ providerReason,
3219
+ warnings: Object.freeze(warnings),
3220
+ fatal: Object.freeze(fatal),
3221
+ recommendations: Object.freeze(recommendations),
3222
+ ...(credentialSources === null ? {} : { credentialSources }),
3223
+ });
3224
+ }
3225
+
3226
+ /**
3227
+ * The pending-vector census for one index path, with the peek's three
3228
+ * outcomes folded into the report's two. Both non-`read` outcomes are
3229
+ * UNRECORDED - they differ in their reason, not in what they prove -
3230
+ * and neither is a count of zero.
3231
+ *
3232
+ * `hold` is the configuration's chunk-hold exclusion key; passing it
3233
+ * keeps held chunks out of the pending count, the same way the spend
3234
+ * plan and the backfill exclude them. Callers without a configuration
3235
+ * in hand omit it and read the raw anti-join.
3236
+ *
3237
+ * Exported for the brain doctor's embeddings-health check, which
3238
+ * consolidates this census beside the index counts instead of deriving
3239
+ * a private copy whose unrecorded contract could drift from this one.
3240
+ */
3241
+ export function readPendingVectorCensus(
3242
+ dbPath: string,
3243
+ hold?: ChunkHoldExclusion,
3244
+ ): PendingVectorCensus {
3245
+ const peek = peekPendingVectorsSync(dbPath, hold);
3246
+ if (peek.kind === "read") {
3247
+ return Object.freeze({
3248
+ verdict: "measured" as const,
3249
+ pending: peek.value.pending,
3250
+ chunks: peek.value.chunks,
3251
+ });
3252
+ }
3253
+ return Object.freeze({
3254
+ verdict: "unrecorded" as const,
3255
+ reason:
3256
+ peek.kind === "absent"
3257
+ ? `no search index at ${dbPath}`
3258
+ : describeUnreadableIndex(dbPath, peek.detail),
3259
+ });
3260
+ }
3261
+
3262
+ /**
3263
+ * The visibility honesty finding for an index path, or `null` when there
3264
+ * is nothing to be honest ABOUT: the index does not exist, would not
3265
+ * open, or - the common case - has never carried a `visibility:`-tagged
3266
+ * page AND measured every document it holds. The surface counts are read off the registry's own exported list
3267
+ * at call time and the document counts off the index's own column, never
3268
+ * hand-written, so the finding cannot drift from what backs it.
3269
+ *
3270
+ * CALLABLE rows only. The registry also carries one `index_store` row -
3271
+ * the fact that `chunks` stores a private page's text whatever a
3272
+ * read-side filter hides - and counting a storage fact as a surface an
3273
+ * operator could call would inflate a number reported to operators.
3274
+ */
3275
+ function readVisibilityHonestyFinding(dbPath: string): VisibilityHonestyFinding | null {
3276
+ const peek = peekVisibilityColumnCensus(dbPath, REMOTE_DENY_VISIBILITY_TOKEN);
3277
+ if (peek.kind !== "read") return null;
3278
+ // Reported when the index HAS something to be honest about, which is
3279
+ // either a tagged page or a population it could not measure. Gating on
3280
+ // `tagged` alone suppressed the unmeasured count in exactly the state
3281
+ // it exists to surface: an index migrated to v12 whose chunk-zero rows
3282
+ // are gone reads as untagged for every row, so the operator was told
3283
+ // nothing at all about the documents the index measured nothing for.
3284
+ if (!peek.value.tagged && peek.value.unmeasured === 0) return null;
3285
+ return Object.freeze({
3286
+ excludedSurfaceCount: excludedCallableVisibilitySurfaces().length,
3287
+ totalSurfaceCount: callableVisibilitySurfaces().length,
3288
+ // Both from the store, never hand-written, for the same reason the
3289
+ // two surface counts are read off the registry: a number an operator
3290
+ // acts on must be the measurement rather than a copy of one.
3291
+ reservedDocumentCount: peek.value.reserved,
3292
+ unmeasuredDocumentCount: peek.value.unmeasured,
3293
+ });
3294
+ }
3295
+
3296
+ interface BuildRecommendationsInput {
3297
+ readonly config: ResolvedSearchConfig;
3298
+ readonly embeddingKeyResolved: boolean;
3299
+ readonly vecExtension: "loaded" | "unavailable" | "not-attempted";
3300
+ readonly providerProbe: ProviderProbeState;
3301
+ readonly embeddingAbi: ReadonlyArray<StampMismatch>;
3302
+ readonly pendingVectors: PendingVectorCensus;
3303
+ readonly embedderRecord: EmbedderRecordCensus;
3304
+ }
3305
+
3306
+ /**
3307
+ * The first-vectors recipe, unchanged from the release that wrote it -
3308
+ * what changed is WHEN it fires. It is now reached only by an index
3309
+ * that holds chunks and no vectors for them, which is the state the
3310
+ * sentence has always described.
3311
+ */
3312
+ const FIRST_VECTORS_RECOMMENDATION =
3313
+ "Run `o2b search reindex --embeddings` to compute the first vectors, then optionally " +
3314
+ "`o2b search reindex --cron-template` for periodic refresh.";
3315
+
3316
+ /**
3317
+ * The verb that prices a partial backfill. Named here rather than
3318
+ * priced here: `planVectorBackfill`'s dry run already counts the tokens
3319
+ * and applies the model's rate, and a second estimator on this surface
3320
+ * could quote a different number for the same work.
3321
+ */
3322
+ const VECTOR_BACKFILL_COMMAND = "o2b search vector-backfill";
3323
+
3324
+ function buildRecommendations(input: BuildRecommendationsInput): string[] {
3325
+ const recs: string[] = [];
3326
+
3327
+ // A record the data itself disproves comes first: every other hint
3328
+ // below reasons from what the index claims about itself, and this is
3329
+ // the one finding that says those claims cannot be trusted. Same
3330
+ // sentence as the warning - one finding, one wording.
3331
+ const contradiction = formatEmbedderRecordContradiction(input.embedderRecord);
3332
+ if (contradiction !== null) recs.push(contradiction);
3333
+
3334
+ // Embedding-ABI drift is the one condition here whose remediation is a
3335
+ // single command, so it is named verbatim and copy-pasteable.
3336
+ if (input.embeddingAbi.length > 0) {
3337
+ recs.push(
3338
+ `Stored vectors were written under a different embedding ABI ` +
3339
+ `(${input.embeddingAbi.map(formatStampMismatch).join("; ")}). Run: ` +
3340
+ `${embeddingAbiFixCommand(input.embeddingAbi)}`,
3341
+ );
3342
+ }
3343
+
3344
+ if (input.config.semantic.enabled && !input.embeddingKeyResolved) {
3345
+ recs.push(
3346
+ "Set OPEN_SECOND_BRAIN_EMBEDDING_KEY in the Open Second Brain env file or set OPEN_SECOND_BRAIN_ENV_FILE.",
3347
+ );
3348
+ recs.push(
3349
+ "Provider: OpenAI `text-embedding-3-small` is the default; any OpenAI-compatible endpoint works via OPEN_SECOND_BRAIN_EMBEDDING_BASE_URL.",
3350
+ );
3351
+ }
3352
+
3353
+ // The price the cost gate reasons from (Honest Embedding Spend): an
3354
+ // unpriced active model and a declaration that prices another model.
3355
+ // Silent for priced and local models, so their output is unchanged.
3356
+ if (input.config.semantic.enabled) {
3357
+ recs.push(...embeddingPriceRecommendations(input.config));
3358
+ }
3359
+
3360
+ if (input.vecExtension === "unavailable") {
3361
+ if (process.platform === "darwin") {
3362
+ recs.push(
3363
+ "Install Homebrew SQLite: `brew install sqlite`. The o2b wrapper picks it up automatically on the next invocation via DYLD_LIBRARY_PATH.",
3364
+ );
3365
+ } else {
3366
+ recs.push(
3367
+ "sqlite-vec did not load. Confirm the optional dependency with `bun pm ls`, or rebuild with `bun install --force`.",
3368
+ );
3369
+ }
3370
+ }
3371
+
3372
+ // Everything wired: what to do next is decided by the MEASURED
3373
+ // pending-vector count (nothing-writes-silently, unit A).
3374
+ //
3375
+ // The gate on a reachable provider and a loaded extension is the same
3376
+ // one this branch has always carried - a probe that was skipped or
3377
+ // timed out proves nothing, and advising a command that cannot
3378
+ // succeed is worse than saying nothing. What it no longer does is
3379
+ // stand IN for the count: those two facts say the machine is ready to
3380
+ // embed, never that anything is waiting to be embedded, and a fully
3381
+ // embedded vault was told to compute its first vectors for as long as
3382
+ // they were the whole test. A vault with every chunk vectorised now
3383
+ // gets no recommendation at all.
3384
+ if (input.providerProbe === PROVIDER_PROBE.reachable && input.vecExtension === "loaded") {
3385
+ const census = input.pendingVectors;
3386
+ if (census.verdict === "unrecorded") {
3387
+ recs.push(
3388
+ `The pending-vector count is unrecorded, not zero (${census.reason}). ` +
3389
+ FIRST_VECTORS_RECOMMENDATION,
3390
+ );
3391
+ } else if (census.pending === census.chunks) {
3392
+ // Every chunk there is - including none at all, on an index that
3393
+ // holds no chunks yet - is waiting for its first vector.
3394
+ recs.push(FIRST_VECTORS_RECOMMENDATION);
3395
+ } else if (census.pending > 0) {
3396
+ recs.push(
3397
+ `${census.pending} of ${census.chunks} indexed chunk(s) have no vector. ` +
3398
+ `Run \`${VECTOR_BACKFILL_COMMAND}\` to see what embedding them would cost - it is a ` +
3399
+ `dry run unless \`--apply\` is passed - and \`${VECTOR_BACKFILL_COMMAND} --apply\` to compute them.`,
3400
+ );
3401
+ }
3402
+ }
3403
+
3404
+ return recs;
3405
+ }