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,2362 @@
1
+ /**
2
+ * Configuration discovery and persistence.
3
+ *
4
+ * Mirrors `src/open_second_brain/config.py` from the legacy Python implementation
5
+ * — same lookup chain (env → XDG → ~/.config), same simple `key: value` YAML
6
+ * subset, same atomic write semantics, same redaction policy. Tests pin parity
7
+ * via parallel suites in tests/core/config.test.ts.
8
+ */
9
+
10
+ import { mkdirSync, readFileSync, statSync, type Stats } from "node:fs";
11
+ import { createHmac, randomBytes } from "node:crypto";
12
+ import { homedir } from "node:os";
13
+ import { dirname, isAbsolute, join, resolve } from "node:path";
14
+
15
+ import { atomicWriteText, sleepSync } from "./fs-atomic.ts";
16
+ import { isSecretReferenceValue, SecretReferenceError } from "./secret-ref.ts";
17
+ import { APP_DIR_NAME, configBaseDir } from "./platform-dirs.ts";
18
+ import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";
19
+ import { resolvePointerVault } from "./brain/portability/pointer.ts";
20
+ import { parseBrainYaml } from "./brain/yaml-parse.ts";
21
+ import { BrainConfigError } from "./brain/policy/errors.ts";
22
+ import { BRAIN_CONFIG_FILE, BRAIN_ROOT_REL } from "./brain/path-constants.ts";
23
+ import { resolveSkillRewriteMode, type SkillRewriteMode } from "./brain/skill-rewrite.ts";
24
+ import {
25
+ isWikiLinkFormat,
26
+ WIKI_LINK_FORMATS,
27
+ type WikiLinkFormat,
28
+ } from "./brain/link-graph/format-wikilink.ts";
29
+ import type { LinkOutputFormat } from "./brain/wikilink.ts";
30
+ import { STORE_DUAL_WRITE_CONFIG_KEY, STORE_DUAL_WRITE_ENV } from "./store/constants.ts";
31
+ import type { ConfigDiscovery } from "./types.ts";
32
+ import { lockDirSync } from "./fs-lock.ts";
33
+
34
+ /**
35
+ * The named-secret resolver port (trust-surface-hardening, t_e5807974).
36
+ *
37
+ * A `$secret:` reference in a config value resolves through the vault's
38
+ * custody store, whose own import neighbourhood reaches back into THIS
39
+ * module (store -> audit -> ledger-shards -> config), so a static import
40
+ * of the resolver here closed the six-module cycle config ->
41
+ * secret-resolver -> custody store -> audit -> ledger-shards -> config,
42
+ * whose initialisation order is undefined. Config is the base layer and
43
+ * carries only the PORT; the resolver plane is the adapter and fills it
44
+ * through {@link installNamedSecretResolver} when `secret-resolver.ts`
45
+ * loads - which every production entry (the CLI's `main.ts`, the MCP
46
+ * server, the OpenClaw bridge) does statically at startup, before any
47
+ * command dispatch.
48
+ */
49
+ export interface NamedSecretResolver {
50
+ /** Resolve one `$secret:` reference against `vault`'s custody store. */
51
+ resolveNamedSecret(vault: string, value: string): string;
52
+ }
53
+
54
+ let namedSecretResolver: NamedSecretResolver | undefined;
55
+
56
+ /** Fill the {@link NamedSecretResolver} port; see its docblock for the wiring. */
57
+ export function installNamedSecretResolver(resolver: NamedSecretResolver): void {
58
+ namedSecretResolver = resolver;
59
+ }
60
+
61
+ /**
62
+ * Resolve one reference through the installed resolver. The refusal is
63
+ * unreachable in a wired process (see the port's docblock); failing
64
+ * closed by name keeps an unwired one from ever treating a stored
65
+ * reference as literal text - for the installation secret that mistake
66
+ * would self-heal a fresh key right over the reference.
67
+ */
68
+ function resolveThroughNamedSecretResolver(vault: string, reference: string): string {
69
+ const resolver = namedSecretResolver;
70
+ if (resolver === undefined) {
71
+ throw new SecretReferenceError(
72
+ "no named-secret resolver is installed in this process; the $secret: reference " +
73
+ "cannot be resolved against the vault's custody store",
74
+ reference,
75
+ );
76
+ }
77
+ return resolver.resolveNamedSecret(vault, reference);
78
+ }
79
+
80
+ const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
81
+
82
+ /**
83
+ * Platforms whose per-user configuration root this build cannot derive.
84
+ * Empty since native Windows gained its own layout (`%LOCALAPPDATA%`, see
85
+ * `platform-dirs.ts`); kept as a named list so adding a platform without
86
+ * a layout is a visible decision rather than a silent POSIX fallback.
87
+ */
88
+ const UNSUPPORTED_CONFIG_PLATFORMS: ReadonlyArray<string> = Object.freeze([]);
89
+
90
+ /**
91
+ * Raised when the config path cannot be derived on the running
92
+ * platform. Named and specific because the alternative - a POSIX path on
93
+ * a platform that does not use one - is a plausible-looking answer to a
94
+ * question this build cannot answer. No platform reaches it today; the
95
+ * class stays exported for callers that still distinguish it.
96
+ */
97
+ export class UnsupportedPlatformError extends Error {
98
+ readonly platform: string;
99
+
100
+ constructor(platform: string) {
101
+ super(
102
+ `open-second-brain has no configuration layout for platform '${platform}': ` +
103
+ "this build does not know where per-user configuration lives there. Set " +
104
+ "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " +
105
+ "to a configuration root, to choose the location yourself.",
106
+ );
107
+ this.name = "UnsupportedPlatformError";
108
+ this.platform = platform;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Raised when the plugin config file is PRESENT but its contents cannot be
114
+ * obtained: a directory (or any non-regular file) where the file should be,
115
+ * a path that cannot be stat'ed at all (an untraversable parent, a symlink
116
+ * loop), a file that cannot be opened, or bytes that are not UTF-8.
117
+ *
118
+ * Named and specific for the same reason {@link UnsupportedPlatformError}
119
+ * is: the alternative - reporting the file as absent - is a
120
+ * plausible-looking answer to a question this module cannot answer. Absent
121
+ * means "no operator settings, defaults apply"; every gate resolved from
122
+ * this file is default-OFF, so absorbing an unreadable file turns the
123
+ * operator's flags off and leaves the install indistinguishable from one
124
+ * that never set them.
125
+ */
126
+ export class ConfigReadError extends Error {
127
+ /** The config file that could not be read. */
128
+ readonly path: string;
129
+
130
+ constructor(path: string, reason: string) {
131
+ // The remedy rides in the message rather than in each reporting
132
+ // surface. This error escapes through four channels with nothing in
133
+ // common - the CLI dispatch, an MCP error envelope, a hook's stderr,
134
+ // and a subcommand that wraps it in its own prose - and a remedy
135
+ // rendered per surface would drift between them or be dropped by the
136
+ // wrappers. Long and instructive matches
137
+ // {@link UnsupportedPlatformError}, for the same reason: the whole
138
+ // value of a refusal is telling the operator what to do next.
139
+ super(
140
+ `failed to read plugin config ${path}: ${reason}. The file is present, so its ` +
141
+ "settings are NOT in force and are not read as absent; make it readable " +
142
+ `(chmod u+r "${path}") or set OPEN_SECOND_BRAIN_CONFIG to a readable config file.`,
143
+ );
144
+ this.name = "ConfigReadError";
145
+ this.path = path;
146
+ }
147
+ }
148
+
149
+ /** Injected view of the environment {@link resolveDefaultConfigPath} reads. */
150
+ export interface ConfigPathEnv {
151
+ /** `process.platform` value. */
152
+ readonly platform: string;
153
+ /** `homedir()` value. */
154
+ readonly home: string;
155
+ readonly env: Readonly<Record<string, string | undefined>>;
156
+ }
157
+
158
+ /**
159
+ * Resolve the location of the plugin config file from an injected
160
+ * environment.
161
+ *
162
+ * Order: `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, then the
163
+ * platform default: `%LOCALAPPDATA%\open-second-brain\config.yaml` on
164
+ * Windows, `$HOME/.config/open-second-brain/config.yaml` everywhere else.
165
+ * Only the last step is platform-bound, so an operator on an unsupported
166
+ * platform still has two ways to say where the file lives.
167
+ *
168
+ * @throws {@link UnsupportedPlatformError} on a platform listed in
169
+ * `UNSUPPORTED_CONFIG_PLATFORMS` (none today).
170
+ */
171
+ export function resolveDefaultConfigPath(source: ConfigPathEnv): string {
172
+ const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
173
+ if (override) return expandTilde(override, source.platform, source.home);
174
+
175
+ const xdg = source.env["XDG_CONFIG_HOME"];
176
+ if (xdg) return join(expandTilde(xdg, source.platform, source.home), APP_DIR_NAME, "config.yaml");
177
+
178
+ if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {
179
+ throw new UnsupportedPlatformError(source.platform);
180
+ }
181
+ return join(configBaseDir(source), APP_DIR_NAME, "config.yaml");
182
+ }
183
+
184
+ /**
185
+ * Resolve the location of the plugin config file for this process.
186
+ *
187
+ * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, then the
188
+ * platform default (see {@link resolveDefaultConfigPath}).
189
+ */
190
+ export function defaultConfigPath(): string {
191
+ return resolveDefaultConfigPath({
192
+ platform: process.platform,
193
+ home: homedir(),
194
+ env: process.env,
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Parse the simple `key: value` YAML subset used for the plugin config.
200
+ *
201
+ * Intentionally not a real YAML parser — keeping this dependency-free and
202
+ * matching the Python `parse_simple_yaml` exactly so round-trips are stable.
203
+ * Lines that aren't `key: value` (comments, blanks, complex YAML) are skipped.
204
+ */
205
+ export function parseSimpleYaml(text: string): Record<string, string> {
206
+ const data: Record<string, string> = {};
207
+ for (const rawLine of text.split(/\r?\n/)) {
208
+ const line = rawLine.trim();
209
+ if (!line || line.startsWith("#")) continue;
210
+ const idx = line.indexOf(":");
211
+ if (idx === -1) continue;
212
+ const key = line.slice(0, idx).trim();
213
+ if (!key) continue;
214
+ let value = line.slice(idx + 1).trim();
215
+ // Strip surrounding quotes (single OR double).
216
+ if (
217
+ value.length >= 2 &&
218
+ ((value.startsWith('"') && value.endsWith('"')) ||
219
+ (value.startsWith("'") && value.endsWith("'")))
220
+ ) {
221
+ value = value.slice(1, -1);
222
+ }
223
+ data[key] = value;
224
+ }
225
+ return data;
226
+ }
227
+
228
+ /**
229
+ * Read and parse the config file, or report it as missing.
230
+ *
231
+ * TWO conditions, not one, and they are kept apart on purpose - the same
232
+ * split `Brain/_brain.yaml` makes in `brain/policy/load.ts`:
233
+ *
234
+ * - ABSENT - nothing at this path. There are no operator settings to
235
+ * contradict, so `exists: false` with no data is the correct answer and
236
+ * every resolver above falls back to its documented default. This is
237
+ * the common case on any install that has not run `o2b init`.
238
+ * - PRESENT BUT UNREADABLE - a non-regular file (a directory in the
239
+ * file's place), a path that cannot be stat'ed, a file that cannot be
240
+ * opened, or bytes that are not UTF-8. The operator's settings exist
241
+ * and are NOT the ones in force. Reporting that as absent turned every
242
+ * default-OFF gate resolved from this file back to `false` and left the
243
+ * install looking exactly like one that never set a flag;
244
+ * {@link ConfigReadError} names the file instead.
245
+ *
246
+ * The parse itself has no third condition: {@link parseSimpleYaml} skips
247
+ * whatever it cannot represent (comments, blank lines, nested blocks), and
248
+ * that tolerance is deliberate parity with the legacy Python reader. That
249
+ * tolerance is about SHAPE, not encoding - see {@link readConfigText}.
250
+ */
251
+ export function discoverConfig(path?: string): ConfigDiscovery {
252
+ const resolved = path ?? defaultConfigPath();
253
+ const stat = statConfigPath(resolved);
254
+ if (stat === undefined) {
255
+ return { path: resolved, exists: false, data: {} };
256
+ }
257
+ // Ahead of the read rather than letting `readFileSync` raise `EISDIR`,
258
+ // because it also covers the paths a read cannot survive: a FIFO at the
259
+ // config path would block the process forever.
260
+ if (!stat.isFile()) {
261
+ throw new ConfigReadError(resolved, "path exists but is not a regular file");
262
+ }
263
+ return { path: resolved, exists: true, data: parseSimpleYaml(readConfigText(resolved)) };
264
+ }
265
+
266
+ /**
267
+ * Stat of the config path: `undefined` for a genuine absence, {@link Stats}
268
+ * otherwise, {@link ConfigReadError} when the answer is unknowable.
269
+ *
270
+ * This replaces an `existsSync` check, which is not the absent/broken split
271
+ * it looks like: it answers `false` for EVERY stat failure, so a perfectly
272
+ * readable config behind a directory lacking the execute bit (or under a
273
+ * symlink loop, or past a name-too-long component) reported as absent and
274
+ * silently reverted the operator's `vault` and every gate in the file to
275
+ * its default. Only ENOENT on this path is an absence; every other errno is
276
+ * a failure to read it.
277
+ *
278
+ * `throwIfNoEntry: false` is what makes that split free rather than a
279
+ * downgrade: it suppresses ENOENT alone and still raises every other errno,
280
+ * so the common absent case pays one syscall and constructs no error - the
281
+ * same cost `existsSync` had, since it is the same `stat`.
282
+ */
283
+ function statConfigPath(resolved: string): Stats | undefined {
284
+ try {
285
+ return statSync(resolved, { throwIfNoEntry: false });
286
+ } catch (err) {
287
+ throw new ConfigReadError(resolved, (err as Error).message ?? String(err));
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Decoded contents of a config file that is known to be a regular file, or
293
+ * a {@link ConfigReadError}.
294
+ *
295
+ * The decode is FATAL, so bytes that are not UTF-8 are the present-but-
296
+ * unreadable condition rather than a lossy parse. `parseSimpleYaml` is
297
+ * tolerant about the SHAPE of a line - that is deliberate parity with the
298
+ * legacy Python reader - but nothing about it licenses accepting bytes we
299
+ * cannot represent: a lossy decode drops whichever keys the undecodable
300
+ * run straddles, which is the same silent revert-to-default as reading the
301
+ * file as absent. It is also destructive, because {@link setConfigValue}
302
+ * merges onto what this returns and would persist the operator's file with
303
+ * every undecodable byte replaced.
304
+ */
305
+ function readConfigText(resolved: string): string {
306
+ let bytes: Buffer;
307
+ try {
308
+ bytes = readFileSync(resolved);
309
+ } catch (err) {
310
+ throw new ConfigReadError(resolved, (err as Error).message ?? String(err));
311
+ }
312
+ try {
313
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
314
+ } catch (err) {
315
+ throw new ConfigReadError(
316
+ resolved,
317
+ `not valid UTF-8: ${(err as Error).message ?? String(err)}`,
318
+ );
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Persist a single `key: value` pair into the plugin config file.
324
+ *
325
+ * Atomic: writes to a temp sibling and renames, with fsync on file and parent
326
+ * dir. Rejects values containing characters that would break the simple parser
327
+ * on read-back rather than silently corrupting them.
328
+ */
329
+ export function setConfigValue(key: string, value: string, path?: string): string {
330
+ if (typeof value !== "string") {
331
+ throw new TypeError(`config value for ${JSON.stringify(key)} must be a string`);
332
+ }
333
+ for (const bad of CONFIG_VALUE_REJECTED_CHARS) {
334
+ if (value.includes(bad)) {
335
+ throw new Error(
336
+ `config value for ${JSON.stringify(key)} contains a disallowed character ` +
337
+ `(${JSON.stringify(bad)}); reject rather than silently corrupting on read-back`,
338
+ );
339
+ }
340
+ }
341
+
342
+ const resolved = path ?? defaultConfigPath();
343
+ const discovery = discoverConfig(resolved);
344
+ const data = { ...discovery.data, [key]: value };
345
+ const body =
346
+ Object.entries(data)
347
+ .map(([k, v]) => `${k}: "${v}"`)
348
+ .join("\n") + "\n";
349
+ atomicWriteText(resolved, body, { mode: configWriteMode(resolved, discovery.exists) });
350
+ return resolved;
351
+ }
352
+
353
+ /**
354
+ * Persist a value that is JSON (the dream agent's command, a JSON array of
355
+ * strings) as one `key: value` line. JSON may hold double quotes and
356
+ * backslashes, which {@link setConfigValue} refuses: read back, the
357
+ * simple parser strips only the surrounding quotes, so the JSON text
358
+ * comes back as written. Line breaks are refused.
359
+ */
360
+ export function setConfigJsonValue(key: string, value: unknown, path?: string): string {
361
+ const text = JSON.stringify(value);
362
+ if (/[\r\n]/.test(text)) {
363
+ throw new Error(`config value for ${JSON.stringify(key)} must fit on one line`);
364
+ }
365
+ const resolved = path ?? defaultConfigPath();
366
+ const discovery = discoverConfig(resolved);
367
+ const data = { ...discovery.data, [key]: text };
368
+ const body =
369
+ Object.entries(data)
370
+ .map(([k, v]) => `${k}: "${v}"`)
371
+ .join("\n") + "\n";
372
+ atomicWriteText(resolved, body, { mode: configWriteMode(resolved, discovery.exists) });
373
+ return resolved;
374
+ }
375
+
376
+ /** Preserve an existing machine config's permissions; new configs are owner-only. */
377
+ function configWriteMode(path: string, exists: boolean): number {
378
+ if (!exists) return 0o600;
379
+ const stat = statConfigPath(path);
380
+ if (stat === undefined || !stat.isFile()) {
381
+ throw new ConfigReadError(path, "path changed while preparing a write");
382
+ }
383
+ return stat.mode & 0o7777;
384
+ }
385
+
386
+ export interface TimezoneValidationResult {
387
+ readonly ok: boolean;
388
+ readonly error: string | null;
389
+ }
390
+
391
+ /** Validate an IANA timezone name without normalising or trimming it. */
392
+ export function validateTimezoneName(name: string): TimezoneValidationResult {
393
+ try {
394
+ // Constructing the formatter IS the validation - it throws a
395
+ // RangeError on an unknown zone. Called rather than `new`-ed because
396
+ // the instance is discarded either way, and `new` for its side effect
397
+ // reads as an accident.
398
+ Intl.DateTimeFormat("en-US", { timeZone: name });
399
+ return { ok: true, error: null };
400
+ } catch (exc) {
401
+ return { ok: false, error: (exc as Error).message ?? String(exc) };
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Resolve the IANA timezone for stamping Daily entries.
407
+ *
408
+ * Order: `VAULT_TIMEZONE` env → `timezone` field in plugin config → `null`
409
+ * (caller falls back to the host's local clock). Invalid IANA names are silently
410
+ * treated as "not configured" so a typo never breaks logging.
411
+ */
412
+ export function resolveTimezone(configPath?: string): string | null {
413
+ let name = process.env["VAULT_TIMEZONE"];
414
+ if (!name) {
415
+ name = discoverConfig(configPath).data["timezone"];
416
+ }
417
+ if (!name) return null;
418
+ return validateTimezoneName(name).ok ? name : null;
419
+ }
420
+
421
+ /**
422
+ * Resolve the vault directory.
423
+ *
424
+ * Order: `VAULT_DIR` env → project pointer walk-up → active profile →
425
+ * `vault` field in plugin config → `null`. Caller decides whether to
426
+ * error out or accept a positional path.
427
+ */
428
+ export function resolveVault(
429
+ configPath?: string,
430
+ opts: { cwd?: string; discovery?: ConfigDiscovery } = {},
431
+ ): string | null {
432
+ const env = process.env["VAULT_DIR"];
433
+ if (env) return expandTilde(env);
434
+ // Project pointer (Workspace Insight Suite, t_1375e69f): a pointer file
435
+ // in (or above) the working directory is the most specific durable
436
+ // artifact, so it beats the profile pointer. Pointers only exist when
437
+ // the operator linked the directory - without one the chain is
438
+ // byte-identical to before. The walk stops at the filesystem root and
439
+ // reads at most one small JSON per level; malformed pointers and
440
+ // dangling targets fail soft to the next resolution step.
441
+ const pointerVault = resolvePointerVault(opts.cwd ?? process.cwd());
442
+ if (pointerVault !== null) return expandTilde(pointerVault);
443
+ // Multi-vault profiles (v0.22.0): an active named profile overrides the
444
+ // bare `vault` key. With no profiles registry the result is unchanged.
445
+ // A caller that already read the config passes it, so it is not read twice.
446
+ const discovery = opts.discovery ?? discoverConfig(configPath);
447
+ const profileVault = resolveActiveProfileVault(discovery.path);
448
+ if (profileVault) return expandTilde(profileVault);
449
+ const cfg = discovery.data["vault"];
450
+ if (cfg) return expandTilde(cfg);
451
+ return null;
452
+ }
453
+
454
+ /**
455
+ * The machine config's own `vault` key (`~` expanded), or null when it
456
+ * sets none: unlike {@link resolveVault}, never `VAULT_DIR`, a project
457
+ * pointer or a profile, which name a vault for one session only. For a
458
+ * writer that would persist the answer back as the machine's vault.
459
+ */
460
+ export function configuredVaultKey(configPath?: string): string | null {
461
+ const value = discoverConfig(configPath).data["vault"];
462
+ return value ? expandTilde(value) : null;
463
+ }
464
+
465
+ /**
466
+ * The identity every install writes under until one is configured.
467
+ *
468
+ * It is a placeholder, not a name: two unconfigured installs write under
469
+ * the same token, so any surface that folds contributions per agent merges
470
+ * every one of them into a single row that reads as one very busy agent
471
+ * (a-label-is-not-a-boundary, U5). It is exported so the roster can say
472
+ * "unconfigured" instead of repeating the literal in a second place and
473
+ * calling it a name.
474
+ */
475
+ export const UNCONFIGURED_AGENT_NAME = "agent";
476
+
477
+ /**
478
+ * Whether an agent identity was actually chosen by an operator, as opposed
479
+ * to being the placeholder {@link resolveAgentName} falls back to.
480
+ */
481
+ export function isConfiguredAgentName(name: string): boolean {
482
+ const trimmed = name.trim();
483
+ return trimmed.length > 0 && trimmed !== UNCONFIGURED_AGENT_NAME;
484
+ }
485
+
486
+ /**
487
+ * Resolve the agent identity used when no explicit `agent` is supplied.
488
+ *
489
+ * Order: `VAULT_AGENT_NAME` env → `agent_name`/`agentName` in plugin config →
490
+ * {@link UNCONFIGURED_AGENT_NAME}. Used by every Brain writer that needs
491
+ * an `agent:` field (signals, evidence rows, log entries) and by the
492
+ * Hermes pre_llm_call hook.
493
+ */
494
+ export function resolveAgentName(configPath?: string): string {
495
+ const env = process.env["VAULT_AGENT_NAME"];
496
+ if (env) return env;
497
+ const data = discoverConfig(configPath).data;
498
+ const value = data["agent_name"] ?? data["agentName"];
499
+ if (value) return value;
500
+ return UNCONFIGURED_AGENT_NAME;
501
+ }
502
+
503
+ /**
504
+ * Shared-namespace root from the device config, or null when off
505
+ * (Agent Write Contract Suite, t_936a1a61).
506
+ *
507
+ * Lives here rather than in `brain/shared-namespace.ts` because it is a
508
+ * device-config key resolver like {@link resolveVaultPath} and
509
+ * {@link resolveAgentName}, and because the search-origin enumeration now
510
+ * reads it too: a module on the fan-out path must not have to import the
511
+ * mirror writer - and its signal, log and time dependencies - to learn one
512
+ * config key (a-label-is-not-a-boundary, U5).
513
+ */
514
+ export function resolveSharedNamespace(configPath?: string | null): string | null {
515
+ const discovery = discoverConfig(configPath ?? undefined);
516
+ const value = discovery.data[SHARED_NAMESPACE_KEY]?.trim();
517
+ return value ? value : null;
518
+ }
519
+
520
+ /** Device-config key naming the shared vault that remember-writes mirror into. */
521
+ const SHARED_NAMESPACE_KEY = "shared_namespace";
522
+
523
+ /**
524
+ * Stable per-install device identity (Memory Integrity Suite). Keys the
525
+ * per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl`), so
526
+ * it MUST live in the device-local config and never in the synced
527
+ * vault - all devices sharing one id would defeat the sharding.
528
+ *
529
+ * Generated once (8 hex chars) on first use and persisted. An invalid
530
+ * hand-edited value self-heals to a fresh generated id; the
531
+ * `sync-conflict` prefix is reserved so a renamed Syncthing conflict
532
+ * copy can never masquerade as a shard.
533
+ *
534
+ * ## A config that cannot be READ is a refusal, deliberately
535
+ *
536
+ * {@link resolveDeviceId} and {@link resolveInstallationSecret} tolerate a
537
+ * config directory they cannot LOCK - the lock only orders a race, and
538
+ * losing it costs at most a duplicate generation. They do NOT tolerate a
539
+ * config they cannot READ, and {@link ConfigReadError} propagates out of
540
+ * both. The self-heal is the reason: a miss means generate-and-persist,
541
+ * an unreadable file is not a miss, and treating it as one is destructive
542
+ * twice over. {@link setConfigValue} merges onto what it read, so writing
543
+ * a generated id through it would flatten the operator's whole config to
544
+ * that single line; and the value itself is load-bearing - a fresh device
545
+ * id silently re-shards this device's log, a fresh installation secret
546
+ * silently changes every `vault://` reference agents correlate by. There
547
+ * is no neutral answer to fall back to, so the file is named instead.
548
+ *
549
+ * The env overrides are the escape hatch that makes the refusal
550
+ * survivable: `O2B_DEVICE_ID` (and, for tests,
551
+ * {@link INSTALLATION_SECRET_ENV_KEY}) are honoured before the file is
552
+ * opened at all.
553
+ */
554
+ export const DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
555
+
556
+ /**
557
+ * Names Windows reserves for devices in every path component (`nul`,
558
+ * `con`, `com1`, ...): there a directory under such a name makes writes
559
+ * vanish or reads block. Device ids carry no dot, so the reserved forms
560
+ * with an extension cannot occur.
561
+ */
562
+ const WINDOWS_RESERVED_DEVICE_NAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
563
+
564
+ /**
565
+ * Whether `value` has the shape of a device id. Platform-independent: it
566
+ * judges data that comes from peers (record envelopes, shard listings,
567
+ * folds, digests, log shards), and every machine must accept the same
568
+ * records or their folds and digests stop matching across platforms. A
569
+ * Windows reserved name is a valid id here; choosing this machine's own
570
+ * id is {@link isUsableLocalDeviceId}.
571
+ */
572
+ export function isValidDeviceId(value: string): boolean {
573
+ return DEVICE_ID_RE.test(value) && !value.startsWith("sync-conflict");
574
+ }
575
+
576
+ /** Whether `value` is one of the names Windows reserves for devices (`nul`, `con`, ...). */
577
+ export function isWindowsReservedDeviceId(value: string): boolean {
578
+ return WINDOWS_RESERVED_DEVICE_NAME_RE.test(value);
579
+ }
580
+
581
+ /**
582
+ * Whether `value` may be THIS machine's device id on `platform`. A new id
583
+ * is never a Windows reserved name on any platform (the generated form
584
+ * cannot be one). An existing configured reserved id is refused only on
585
+ * Windows: a POSIX machine whose id is one of them keeps it, so its log
586
+ * shards and store directories stay under that name.
587
+ */
588
+ export function isUsableLocalDeviceId(
589
+ value: string,
590
+ platform: NodeJS.Platform = process.platform,
591
+ ): boolean {
592
+ return isValidDeviceId(value) && !(platform === "win32" && isWindowsReservedDeviceId(value));
593
+ }
594
+
595
+ /** Environment variable that overrides the machine config's `device_id`. */
596
+ export const DEVICE_ID_ENV = "O2B_DEVICE_ID";
597
+
598
+ /**
599
+ * The device id {@link resolveDeviceId} would answer, read without
600
+ * minting one: null when the env override opts out (the empty string)
601
+ * or when no valid id is configured yet. For readers that must agree
602
+ * with the writers' identity but must never write the machine config.
603
+ */
604
+ export function readDeviceId(configPath?: string | null): string | null {
605
+ const env = process.env[DEVICE_ID_ENV];
606
+ if (env === "") return null;
607
+ if (env !== undefined && isUsableLocalDeviceId(env)) return env;
608
+ const value = discoverConfig(configPath ?? defaultConfigPath()).data["device_id"];
609
+ return value !== undefined && isUsableLocalDeviceId(value) ? value : null;
610
+ }
611
+
612
+ export function resolveDeviceId(configPath?: string): string {
613
+ // Env override: a valid id wins outright; the empty string opts out
614
+ // of sharding (legacy single-file log pair). The test preload pins
615
+ // this to "" so the suite stays deterministic; an invalid value
616
+ // falls through to config resolution.
617
+ const env = process.env[DEVICE_ID_ENV];
618
+ if (env !== undefined && (env === "" || isUsableLocalDeviceId(env))) return env;
619
+ const resolved = configPath ?? defaultConfigPath();
620
+
621
+ const read = (): string | null => {
622
+ const value = discoverConfig(resolved).data["device_id"];
623
+ return value && isUsableLocalDeviceId(value) ? value : null;
624
+ };
625
+
626
+ const existing = read();
627
+ if (existing !== null) return existing;
628
+
629
+ // First-use generation, reached only because the config was READ and
630
+ // holds no usable id (see the identity docblock above for why an
631
+ // unreadable one never gets here). Two processes racing could each persist a different
632
+ // id and split one device's logs across two shards, so the
633
+ // read-generate-write sequence holds a directory lock (same
634
+ // bounded-retry shape as the log writer's `acquireLogLock`). A lock
635
+ // failure (read-only config home, exotic fs) falls through to the
636
+ // unlocked path - losing the lock costs at most a duplicate generation,
637
+ // which is not worth failing over.
638
+ const dir = dirname(resolved);
639
+ mkdirSync(dir, { recursive: true });
640
+ let release: (() => void) | undefined;
641
+ try {
642
+ for (let attempt = 0; attempt < 10; attempt++) {
643
+ try {
644
+ release = lockDirSync(dir, { stale: 10_000 });
645
+ break;
646
+ } catch (err) {
647
+ if ((err as NodeJS.ErrnoException).code !== "ELOCKED") break;
648
+ sleepSync(50);
649
+ }
650
+ }
651
+ // Re-check under the lock: the racing process may have just won.
652
+ const won = read();
653
+ if (won !== null) return won;
654
+ const generated = randomBytes(4).toString("hex");
655
+ setConfigValue("device_id", generated, resolved);
656
+ return generated;
657
+ } finally {
658
+ release?.();
659
+ }
660
+ }
661
+
662
+ /**
663
+ * Store-hardening escape hatch (D2). Default OFF: MCP responses redact
664
+ * the absolute vault host path to an opaque store reference (see
665
+ * {@link vaultStoreReference}) because those responses land in model
666
+ * context - the exact leak surface this guards. Set
667
+ * `expose_host_paths: true` (or the env twin) to restore the raw path
668
+ * for operators whose tooling depends on it.
669
+ */
670
+ export function resolveExposeHostPaths(configPath?: string): boolean {
671
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS", "expose_host_paths", configPath);
672
+ }
673
+
674
+ /**
675
+ * Device-local installation secret that keys {@link vaultStoreReference}.
676
+ *
677
+ * Sixteen random bytes (128-bit) rendered as 32 lowercase hex, generated
678
+ * once and persisted beside `device_id` in the same device-local config.
679
+ * Three properties make the store reference unguessable offline:
680
+ *
681
+ * - it is NEVER synced (device-local config, like `device_id`);
682
+ * - it is NEVER derived from `device_id`, so the `O2B_DEVICE_ID=""`
683
+ * sharding opt-out (which makes the device id empty and predictable)
684
+ * cannot weaken it;
685
+ * - it has NO empty/predictable escape hatch: the only env override
686
+ * ({@link INSTALLATION_SECRET_ENV_KEY}, for deterministic tests) is
687
+ * honoured solely when it is itself a full 32-hex key.
688
+ *
689
+ * A missing or corrupt persisted value self-heals to a fresh key under the
690
+ * same directory lock `resolveDeviceId` uses, so a concurrent first use
691
+ * cannot split into two keys.
692
+ */
693
+ export const INSTALLATION_SECRET_CONFIG_KEY = "installation_secret";
694
+ /** Test-only env override; honoured ONLY when it is a full 32-hex key. */
695
+ export const INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET";
696
+ /** Strict shape: 32 lowercase hex = 16 bytes = a 128-bit key. */
697
+ export const INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;
698
+
699
+ export function isValidInstallationSecret(value: string): boolean {
700
+ return INSTALLATION_SECRET_RE.test(value);
701
+ }
702
+
703
+ export function resolveInstallationSecret(configPath?: string, secretsVault?: string): string {
704
+ // Env override exists for deterministic tests only, and is accepted solely
705
+ // as a full 32-hex key so it can never make the secret empty or guessable.
706
+ const env = process.env[INSTALLATION_SECRET_ENV_KEY];
707
+ if (env !== undefined && isValidInstallationSecret(env)) return env;
708
+ const resolved = configPath ?? defaultConfigPath();
709
+
710
+ const read = (): string | null => {
711
+ const raw = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
712
+ // A persisted value written as a `$secret:NAME` reference NEVER
713
+ // self-heals. The reference is the operator's stored intent, and the
714
+ // self-heal below would mint a fresh key over it - silently
715
+ // destroying the reference AND rotating the HMAC key, which changes
716
+ // every `vault://` reference agents correlate by, with no error
717
+ // naming anything. So every reference outcome is either the resolved
718
+ // key or a named refusal: unresolvable (the store and the
719
+ // environment cannot answer), locked (the store refuses), resolves
720
+ // but not a 32-hex key (the stored value is not an installation
721
+ // secret), or no vault passed to resolve against. Self-heal only
722
+ // ever mints when NO reference exists - a missing or plain corrupt
723
+ // value, exactly as before.
724
+ if (isSecretReferenceValue(raw)) {
725
+ const reference = String(raw).trim();
726
+ if (secretsVault === undefined) {
727
+ throw new SecretReferenceError(
728
+ "installation_secret is a $secret: reference but no vault was passed to resolve " +
729
+ "it against; pass the vault (or set O2B_INSTALLATION_SECRET to a 32-hex key)",
730
+ reference,
731
+ );
732
+ }
733
+ const resolvedValue = resolveThroughNamedSecretResolver(secretsVault, reference);
734
+ if (!isValidInstallationSecret(resolvedValue)) {
735
+ throw new SecretReferenceError(
736
+ "installation_secret is a $secret: reference that resolves to a value which is " +
737
+ "not a 32-hex installation key; fix the stored value - the reference in the " +
738
+ "device config is never overwritten",
739
+ reference,
740
+ );
741
+ }
742
+ return resolvedValue;
743
+ }
744
+ return raw && isValidInstallationSecret(raw) ? raw : null;
745
+ };
746
+
747
+ const existing = read();
748
+ if (existing !== null) return existing;
749
+
750
+ // First-use generation under a directory lock, mirroring resolveDeviceId
751
+ // in both halves: a lock failure falls through to the unlocked path,
752
+ // while a config that could not be READ never reaches here at all.
753
+ const dir = dirname(resolved);
754
+ mkdirSync(dir, { recursive: true });
755
+ let release: (() => void) | undefined;
756
+ try {
757
+ for (let attempt = 0; attempt < 10; attempt++) {
758
+ try {
759
+ release = lockDirSync(dir, { stale: 10_000 });
760
+ break;
761
+ } catch (err) {
762
+ if ((err as NodeJS.ErrnoException).code !== "ELOCKED") break;
763
+ sleepSync(50);
764
+ }
765
+ }
766
+ const won = read();
767
+ if (won !== null) return won;
768
+ const generated = randomBytes(16).toString("hex");
769
+ setConfigValue(INSTALLATION_SECRET_CONFIG_KEY, generated, resolved);
770
+ return generated;
771
+ } finally {
772
+ release?.();
773
+ }
774
+ }
775
+
776
+ /** Prefix of the opaque store reference emitted in place of a host path. */
777
+ export const VAULT_STORE_REF_PREFIX = "vault://";
778
+ /** Hex length of the store-reference digest (128 bits of HMAC-SHA256). */
779
+ const VAULT_STORE_REF_HEX_LEN = 32;
780
+
781
+ /**
782
+ * Stable opaque reference for a vault, of the form `vault://<32-hex>`.
783
+ * Computed as HMAC-SHA256, keyed by the device-local
784
+ * {@link resolveInstallationSecret}, over the ABSOLUTE vault path. The key
785
+ * makes the reference unguessable offline (a plain hash of a common host
786
+ * path is trivially reversible), and truncating to 128 bits keeps collisions
787
+ * negligible. It is stable across calls on the same install (agents correlate
788
+ * by it) and never leaks the raw path. Returned by MCP tools in place of the
789
+ * absolute path unless {@link resolveExposeHostPaths} is on.
790
+ *
791
+ * @throws {@link ConfigReadError} when the device-local config holding the
792
+ * key cannot be read. Propagated, not absorbed: the only fallbacks would
793
+ * be a fresh key (breaking the stability every consumer correlates by) or
794
+ * the raw host path (the leak this function exists to prevent). Callers
795
+ * that render a payload report the condition in the field - see
796
+ * `vaultPathField` in `src/mcp/tools.ts`.
797
+ */
798
+ export function vaultStoreReference(vaultPath: string, configPath?: string): string {
799
+ // The referenced vault's custody store backs a `$secret:` reference in
800
+ // the persisted key; a plain key resolves exactly as before.
801
+ const key = resolveInstallationSecret(configPath, vaultPath);
802
+ const digest = createHmac("sha256", key)
803
+ .update(resolve(vaultPath))
804
+ .digest("hex")
805
+ .slice(0, VAULT_STORE_REF_HEX_LEN);
806
+ return `${VAULT_STORE_REF_PREFIX}${digest}`;
807
+ }
808
+
809
+ export function resolveLinkOutputFormat(configPath?: string): LinkOutputFormat {
810
+ const env = process.env["OBSIDIAN_LINK_FORMAT"]?.trim();
811
+ const data = env ? {} : discoverConfig(configPath).data;
812
+ const raw = env || data["link_output_format"] || data["linkOutputFormat"];
813
+ return raw === "markdown" ? "markdown" : "wikilink";
814
+ }
815
+
816
+ /**
817
+ * Named MCP tool-surface profile (Agent Surface Suite). Returns the raw
818
+ * configured name or null; validation against the known profile set
819
+ * happens in the resolver, which fails open on unknown names.
820
+ */
821
+ export function resolveMcpToolProfile(configPath?: string): string | null {
822
+ const env = process.env["OPEN_SECOND_BRAIN_MCP_TOOL_PROFILE"]?.trim();
823
+ if (env) return env;
824
+ const raw = discoverConfig(configPath).data["mcp_tool_profile"]?.trim();
825
+ return raw ? raw : null;
826
+ }
827
+
828
+ /**
829
+ * Optional skills directory override (Agent Surface Suite). When set,
830
+ * `skills_attach` / `list_skills` / `get_skill` read from this path
831
+ * instead of `<vault>/Brain/skills/`. Supports `~` expansion. A relative
832
+ * value is anchored to the directory of the resolved config file so the
833
+ * skill root is deterministic regardless of the process working
834
+ * directory (a bare `skills_dir: nested/skills` would otherwise resolve
835
+ * against an unpredictable CWD). Falls back to null (use the default
836
+ * vault-local path).
837
+ */
838
+ export function resolveSkillsDir(configPath?: string): string | null {
839
+ const discovery = discoverConfig(configPath);
840
+ const env = process.env["OPEN_SECOND_BRAIN_SKILLS_DIR"]?.trim();
841
+ const raw = env || discovery.data["skills_dir"]?.trim();
842
+ if (!raw || raw.length === 0) return null;
843
+ const expanded = expandTilde(raw);
844
+ return isAbsolute(expanded) ? expanded : resolve(dirname(discovery.path), expanded);
845
+ }
846
+
847
+ /**
848
+ * Raw value of one setting: the env override when it is set and non-empty,
849
+ * otherwise the config value, otherwise `undefined`. Env always wins. When
850
+ * `data` is a function it is called only when no env override is set, so
851
+ * an env answer never opens the config file.
852
+ */
853
+ function readSetting(
854
+ envKey: string,
855
+ configKey: string,
856
+ data: Record<string, string> | (() => Record<string, string>),
857
+ ): string | undefined {
858
+ const env = process.env[envKey]?.trim();
859
+ if (env) return env;
860
+ const raw = (typeof data === "function" ? data() : data)[configKey]?.trim();
861
+ return raw ? raw : undefined;
862
+ }
863
+
864
+ /**
865
+ * Name of the setting a rejected value came from: the environment variable
866
+ * when it holds a non-blank value (the one {@link readSetting} answered from),
867
+ * the config key otherwise, so a report points at what the operator set.
868
+ */
869
+ function rejectedSettingName(envKey: string, configKey: string): string {
870
+ return process.env[envKey]?.trim() ? envKey : configKey;
871
+ }
872
+
873
+ /**
874
+ * Shared body for a default-OFF boolean config gate: env var (trimmed)
875
+ * wins, falling back to the matching `_brain.yaml`/config key (trimmed);
876
+ * only the literal strings `"true"`/`"1"` are truthy, anything else
877
+ * (including absence) resolves to `false`. Replaces seven copy-pasted
878
+ * resolver bodies that differed only in their env/config key names.
879
+ */
880
+ function resolveConfigFlag(envKey: string, configKey: string, configPath?: string): boolean {
881
+ return isFlagOn(readSetting(envKey, configKey, () => discoverConfig(configPath).data));
882
+ }
883
+
884
+ /** The one parse every boolean switch in this file shares. */
885
+ function isFlagOn(raw: string | undefined): boolean {
886
+ return raw === "true" || raw === "1";
887
+ }
888
+
889
+ /**
890
+ * Skill-attach triggers gate (Agent Surface Suite). When enabled (default
891
+ * OFF), the `triggers` field from each skill's SKILL.md frontmatter is
892
+ * included in the lexical scorer as a 2x-BM25 tag signal. When disabled
893
+ * or unset, triggers are ignored and scoring is name (3x) + description
894
+ * (1x) only.
895
+ */
896
+ export function resolveSkillsAttachTriggers(configPath?: string): boolean {
897
+ return resolveConfigFlag(
898
+ "OPEN_SECOND_BRAIN_SKILLS_ATTACH_TRIGGERS",
899
+ "skills_attach_triggers",
900
+ configPath,
901
+ );
902
+ }
903
+
904
+ /**
905
+ * Skill auto-attach gate (Agent Surface Suite). Default OFF: the
906
+ * skills_attach tool returns an empty block unless the operator sets
907
+ * `skill_auto_attach: "true"` (or the matching env override), so the
908
+ * default per-turn injection stays bit-identical.
909
+ */
910
+ export function resolveSkillAutoAttach(configPath?: string): boolean {
911
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_SKILL_AUTO_ATTACH", "skill_auto_attach", configPath);
912
+ }
913
+
914
+ /**
915
+ * Skill-attach usage-ordering gate (Agent Surface Suite, t_5d1ec8a8).
916
+ * Default OFF: skills_attach ranks purely by the lexical scorer unless
917
+ * `skills_attach_usage_ordering: "true"` (or the matching env override),
918
+ * so the default offer ordering stays byte-identical. When on, observed
919
+ * `skill_invoked` usage reorders lexical near-ties under the bounded
920
+ * composite in `surface/skill-attach.ts`; the continuity read still only
921
+ * happens when the auto-attach gate above is on too.
922
+ */
923
+ export function resolveSkillsAttachUsageOrdering(configPath?: string): boolean {
924
+ return resolveConfigFlag(
925
+ "OPEN_SECOND_BRAIN_SKILLS_ATTACH_USAGE_ORDERING",
926
+ "skills_attach_usage_ordering",
927
+ configPath,
928
+ );
929
+ }
930
+
931
+ /**
932
+ * Context-pack focus wiring gate (Agent Surface Suite, t_5b478e47).
933
+ * Default OFF: brain_context_pack ignores the active search focus
934
+ * unless `search_focus_context_pack: "true"`, keeping the default
935
+ * pack byte-identical.
936
+ */
937
+ export function resolveSearchFocusContextPack(configPath?: string): boolean {
938
+ return resolveConfigFlag(
939
+ "OPEN_SECOND_BRAIN_SEARCH_FOCUS_CONTEXT_PACK",
940
+ "search_focus_context_pack",
941
+ configPath,
942
+ );
943
+ }
944
+
945
+ /**
946
+ * Context-pack density-ranking gate (impact-per-token allocation,
947
+ * t_affa3bd9). Default OFF: brain_context_pack orders purely by tier →
948
+ * recency unless `density_ranking_context_pack: "true"` (or the env
949
+ * override), keeping the default pack byte-identical. When on, a
950
+ * deterministic value-per-token density score breaks within-tier ties
951
+ * (after session focus, before recency).
952
+ */
953
+ export function resolveDensityRankingContextPack(configPath?: string): boolean {
954
+ return resolveConfigFlag(
955
+ "OPEN_SECOND_BRAIN_DENSITY_RANKING_CONTEXT_PACK",
956
+ "density_ranking_context_pack",
957
+ configPath,
958
+ );
959
+ }
960
+
961
+ /**
962
+ * Context-pack entity-facts gate (dated commitments, t_43b0a379). Default
963
+ * OFF: brain_context_pack carries no `entity_facts` section unless
964
+ * `entity_facts_context_pack: "true"` (or the env override), keeping the
965
+ * default pack byte-identical. When on, the report gains a per-entity
966
+ * rollup over candidates the pack already kept.
967
+ */
968
+ export function resolveEntityFactsContextPack(configPath?: string): boolean {
969
+ return resolveConfigFlag(
970
+ "OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK",
971
+ "entity_facts_context_pack",
972
+ configPath,
973
+ );
974
+ }
975
+
976
+ /**
977
+ * Context-pack score-aware tail-trim gate (delivered-evidence trim,
978
+ * t_cb6a5558). Default OFF: brain_context_pack never trims delivered
979
+ * items after the tier/budget walk unless `tail_trim_context_pack:
980
+ * "true"` (or the env override), keeping the default pack
981
+ * byte-identical. When on, the pack drops the low-scoring tail past its
982
+ * top delivered items and reports the trim in a conditional `tailTrim`
983
+ * report member.
984
+ */
985
+ export function resolveTailTrimContextPack(configPath?: string): boolean {
986
+ return resolveConfigFlag(
987
+ "OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK",
988
+ "tail_trim_context_pack",
989
+ configPath,
990
+ );
991
+ }
992
+
993
+ /**
994
+ * Counterparty-brief hook gate (dated commitments, t_43b0a379). Default
995
+ * OFF: the UserPromptSubmit hook exits without output unless
996
+ * `counterparty_brief_enabled: "true"` (or the env override), so the
997
+ * hook's stdout stays byte-identical on unchanged installs.
998
+ */
999
+ export function resolveCounterpartyBriefEnabled(configPath?: string): boolean {
1000
+ return resolveConfigFlag(
1001
+ "OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED",
1002
+ "counterparty_brief_enabled",
1003
+ configPath,
1004
+ );
1005
+ }
1006
+
1007
+ /**
1008
+ * Operator-declared trigger vocabulary for the counterparty brief (dated
1009
+ * commitments, t_43b0a379): a machine-local main-config list key holding
1010
+ * comma-separated tokens in the operator's language; the brief fires only
1011
+ * when at least one token occurs in the prompt. Nothing ships a built-in
1012
+ * word list (the standing refusal on hardcoded natural-language phrases).
1013
+ *
1014
+ * Each entry is NFC-normalized and trimmed; empty entries are dropped.
1015
+ * ABSENT or MALFORMED answers `[]`, which keeps the brief inert - the
1016
+ * safe direction, since a malformed vocabulary silently matching nothing
1017
+ * is disclosed in the hooks README. A bracket-shaped value (real YAML
1018
+ * list syntax the flat config parser cannot represent) is malformed: its
1019
+ * literal text would ship tokens no prompt ever contains.
1020
+ */
1021
+ export function resolveCounterpartyBriefTriggers(configPath?: string): ReadonlyArray<string> {
1022
+ const raw = discoverConfig(configPath).data["counterparty_brief_triggers"]?.trim();
1023
+ if (raw === undefined || raw === "") return [];
1024
+ if (raw.startsWith("[") && raw.endsWith("]")) return [];
1025
+ const tokens: string[] = [];
1026
+ for (const part of raw.split(",")) {
1027
+ const token = part.normalize("NFC").trim();
1028
+ if (token.length > 0) tokens.push(token);
1029
+ }
1030
+ return tokens;
1031
+ }
1032
+
1033
+ /**
1034
+ * Post-compaction pinned-anchor survival audit gate
1035
+ * (session-lifecycle-capture-durability, t_12c8b256). Default OFF: the
1036
+ * `o2b brain post-compact-audit` entry is a no-op unless
1037
+ * `post_compact_survival_audit: "true"`, so unchanged installs run no
1038
+ * post-compaction re-assertion and stay byte-identical.
1039
+ */
1040
+ export function resolvePostCompactSurvivalAudit(configPath?: string): boolean {
1041
+ return resolveConfigFlag(
1042
+ "OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT",
1043
+ "post_compact_survival_audit",
1044
+ configPath,
1045
+ );
1046
+ }
1047
+
1048
+ /**
1049
+ * Post-compaction verbatim recent-turns re-surface gate (C3 / t_92317f91).
1050
+ * Default OFF: the bounded last-N-turns buffer is captured and readable on
1051
+ * demand, but nothing is auto-surfaced into the post-compaction context
1052
+ * unless `recent_turns_resurface: "true"`, so unchanged installs stay
1053
+ * byte-identical.
1054
+ */
1055
+ export function resolveRecentTurnsResurface(configPath?: string): boolean {
1056
+ return resolveConfigFlag(
1057
+ "OPEN_SECOND_BRAIN_RECENT_TURNS_RESURFACE",
1058
+ "recent_turns_resurface",
1059
+ configPath,
1060
+ );
1061
+ }
1062
+
1063
+ /**
1064
+ * Retire-sibling projection gate (near-duplicate defense, t_acab97de).
1065
+ * Default OFF: the dream summary, `brain_review_candidates` and
1066
+ * `o2b brain reject` carry no `retire_siblings` unless
1067
+ * `near_duplicate_retire_siblings_enabled: "true"`, so unchanged installs
1068
+ * stay byte-identical.
1069
+ */
1070
+ export function resolveNearDuplicateRetireSiblingsEnabled(configPath?: string): boolean {
1071
+ return resolveConfigFlag(
1072
+ "OPEN_SECOND_BRAIN_NEAR_DUPLICATE_RETIRE_SIBLINGS_ENABLED",
1073
+ "near_duplicate_retire_siblings_enabled",
1074
+ configPath,
1075
+ );
1076
+ }
1077
+
1078
+ /**
1079
+ * Write-receipt near-duplicate widening gate (near-duplicate defense,
1080
+ * t_fda66477). Default OFF: the receipt hint compares only pages in the
1081
+ * written page's directory unless `near_duplicate_write_widening_enabled:
1082
+ * "true"`, which adds keyword-index candidates from other directories.
1083
+ */
1084
+ export function resolveNearDuplicateWriteWideningEnabled(configPath?: string): boolean {
1085
+ return resolveConfigFlag(
1086
+ "OPEN_SECOND_BRAIN_NEAR_DUPLICATE_WRITE_WIDENING_ENABLED",
1087
+ "near_duplicate_write_widening_enabled",
1088
+ configPath,
1089
+ );
1090
+ }
1091
+
1092
+ /**
1093
+ * Brain store dual writes (task 1.11, a phase 1 trial). Default OFF: the
1094
+ * legacy writers write only the vault tree. When on, every covered legacy
1095
+ * write also appends the equivalent record to the brain store
1096
+ * (`src/core/store/dual-write.ts`); a store failure never fails the
1097
+ * legacy write. Env twin: `OPEN_SECOND_BRAIN_STORE_DUAL_WRITE`.
1098
+ */
1099
+ export function resolveStoreDualWrite(configPath?: string): boolean {
1100
+ return resolveConfigFlag(STORE_DUAL_WRITE_ENV, STORE_DUAL_WRITE_CONFIG_KEY, configPath);
1101
+ }
1102
+
1103
+ /**
1104
+ * SessionEnd handoff-note gate (Agent Surface Suite, t_28afa4d2).
1105
+ * Default OFF: lifecycle capture writes no handoff note unless
1106
+ * `session_handoff: "true"`.
1107
+ */
1108
+ export function resolveSessionHandoff(configPath?: string): boolean {
1109
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_SESSION_HANDOFF", "session_handoff", configPath);
1110
+ }
1111
+
1112
+ /**
1113
+ * Environment form of the automatic store migration's opt-out (change
1114
+ * auto-store-migration, decision D5). It can only turn the migration off:
1115
+ * CI and tests set it where no machine config is at hand.
1116
+ */
1117
+ export const AUTO_STORE_MIGRATION_ENV = "OPEN_SECOND_BRAIN_AUTO_STORE_MIGRATION";
1118
+
1119
+ /** The machine config key of the automatic store migration's opt-out. */
1120
+ export const AUTO_STORE_MIGRATION_KEY = "auto_store_migration";
1121
+
1122
+ /** The spellings that turn the automatic store migration on (case-insensitive). */
1123
+ export const AUTO_STORE_MIGRATION_ON_VALUES: ReadonlyArray<string> = Object.freeze([
1124
+ "true",
1125
+ "1",
1126
+ "yes",
1127
+ "on",
1128
+ ]);
1129
+
1130
+ /** The spellings that turn it off (case-insensitive). */
1131
+ export const AUTO_STORE_MIGRATION_OFF_VALUES: ReadonlyArray<string> = Object.freeze([
1132
+ "false",
1133
+ "0",
1134
+ "no",
1135
+ "off",
1136
+ ]);
1137
+
1138
+ /** A value of the opt-out that is neither on nor off; it counts as off. */
1139
+ export interface UnrecognisedAutoStoreMigrationValue {
1140
+ readonly source: "environment" | "config";
1141
+ readonly value: string;
1142
+ }
1143
+
1144
+ /** How the automatic store migration's opt-out resolved on this machine. */
1145
+ export interface AutoStoreMigrationSetting {
1146
+ /** Whether a start (and `o2b update`) may run the migration on its own. */
1147
+ readonly enabled: boolean;
1148
+ /** Values that were neither on nor off; each one turned the migration off. */
1149
+ readonly unrecognised: ReadonlyArray<UnrecognisedAutoStoreMigrationValue>;
1150
+ /** Why the machine config could not be read (the migration is then off), or null. */
1151
+ readonly unreadable: string | null;
1152
+ }
1153
+
1154
+ type OptOutValue = "on" | "off" | "unset" | "unrecognised";
1155
+
1156
+ /**
1157
+ * One value of the opt-out: surrounding space and a trailing inline
1158
+ * comment (` # ...`) are ignored, then the spelling is matched without
1159
+ * regard to case.
1160
+ */
1161
+ function readOptOutValue(
1162
+ raw: string | undefined,
1163
+ emptyIsUnset: boolean,
1164
+ ): {
1165
+ kind: OptOutValue;
1166
+ value: string;
1167
+ } {
1168
+ if (raw === undefined) return { kind: "unset", value: "" };
1169
+ let value = raw.replace(/(^|\s)#.*$/, "").trim();
1170
+ if (
1171
+ value.length >= 2 &&
1172
+ ((value.startsWith('"') && value.endsWith('"')) ||
1173
+ (value.startsWith("'") && value.endsWith("'")))
1174
+ ) {
1175
+ value = value.slice(1, -1).trim();
1176
+ }
1177
+ if (value === "" && emptyIsUnset) return { kind: "unset", value };
1178
+ const lower = value.toLowerCase();
1179
+ if (AUTO_STORE_MIGRATION_ON_VALUES.includes(lower)) return { kind: "on", value };
1180
+ if (AUTO_STORE_MIGRATION_OFF_VALUES.includes(lower)) return { kind: "off", value };
1181
+ return { kind: "unrecognised", value: raw.trim() };
1182
+ }
1183
+
1184
+ /**
1185
+ * The automatic store migration's opt-out (change auto-store-migration,
1186
+ * decision D5). Default ON, the opposite of every flag gate above: the
1187
+ * owner decision (2026-11-17) has the product run the migration after an
1188
+ * update, and a machine opts out per machine with
1189
+ * `auto_store_migration: false` in the machine config.
1190
+ *
1191
+ * It is a consent switch, so it fails closed:
1192
+ *
1193
+ * - on only for `true`, `1`, `yes`, `on`; off for `false`, `0`, `no`,
1194
+ * `off` (any case, surrounding space and a trailing inline comment
1195
+ * ignored); any other value is off and is reported as unrecognised;
1196
+ * - off wins: when the config key or the environment variable says off
1197
+ * (or holds an unrecognised value), it is off, and the environment can
1198
+ * never turn the migration on over a config opt-out;
1199
+ * - a machine config that cannot be read means no automatic migration.
1200
+ *
1201
+ * An absent key and an unset (or blank) environment variable leave the
1202
+ * default. A config key with no value is unrecognised. Never throws.
1203
+ */
1204
+ export function autoStoreMigrationSetting(configPath?: string): AutoStoreMigrationSetting {
1205
+ const unrecognised: UnrecognisedAutoStoreMigrationValue[] = [];
1206
+ const env = readOptOutValue(process.env[AUTO_STORE_MIGRATION_ENV], true);
1207
+ if (env.kind === "unrecognised") unrecognised.push({ source: "environment", value: env.value });
1208
+ let config: { kind: OptOutValue; value: string };
1209
+ try {
1210
+ config = readOptOutValue(discoverConfig(configPath).data[AUTO_STORE_MIGRATION_KEY], false);
1211
+ } catch (err) {
1212
+ return {
1213
+ enabled: false,
1214
+ unrecognised,
1215
+ unreadable: err instanceof Error ? err.message : String(err),
1216
+ };
1217
+ }
1218
+ if (config.kind === "unrecognised") unrecognised.push({ source: "config", value: config.value });
1219
+ const off = (v: OptOutValue): boolean => v === "off" || v === "unrecognised";
1220
+ return { enabled: !off(env.kind) && !off(config.kind), unrecognised, unreadable: null };
1221
+ }
1222
+
1223
+ /** Whether the automatic store migration may run; see {@link autoStoreMigrationSetting}. */
1224
+ export function resolveAutoStoreMigration(configPath?: string): boolean {
1225
+ return autoStoreMigrationSetting(configPath).enabled;
1226
+ }
1227
+
1228
+ /**
1229
+ * Why the automatic store migration is off when the reason is not a plain
1230
+ * opt-out (an unrecognised value, an unreadable config), as one operator
1231
+ * sentence; null when the setting reads cleanly.
1232
+ */
1233
+ export function describeAutoStoreMigrationProblem(
1234
+ setting: AutoStoreMigrationSetting,
1235
+ ): string | null {
1236
+ if (setting.unreadable !== null) {
1237
+ return (
1238
+ `the machine config cannot be read (${setting.unreadable}), so the automatic store ` +
1239
+ "migration does not run"
1240
+ );
1241
+ }
1242
+ if (setting.unrecognised.length === 0) return null;
1243
+ const named = setting.unrecognised
1244
+ .map((u) =>
1245
+ u.source === "environment"
1246
+ ? `${AUTO_STORE_MIGRATION_ENV}=${JSON.stringify(u.value)}`
1247
+ : `${AUTO_STORE_MIGRATION_KEY}: ${JSON.stringify(u.value)} in the machine config`,
1248
+ )
1249
+ .join(" and ");
1250
+ return (
1251
+ `unrecognised value ${named}, so the automatic store migration is off; use one of ` +
1252
+ `${AUTO_STORE_MIGRATION_ON_VALUES.join(", ")} to turn it on or ` +
1253
+ `${AUTO_STORE_MIGRATION_OFF_VALUES.join(", ")} to turn it off`
1254
+ );
1255
+ }
1256
+
1257
+ /**
1258
+ * Rated-decision recall config keys (Belief lifecycle suite, B5,
1259
+ * t_5712fa39). Both are OPTIONAL and default-OFF: when neither the env
1260
+ * nor the config key is set, {@link resolveDecisionRecallMaxPerSession}
1261
+ * returns `null`, which disables rated-decision recall entirely so the
1262
+ * session-injection output is byte-identical to today.
1263
+ */
1264
+ export const DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session";
1265
+ export const DECISION_RECALL_MAX_PER_SESSION_ENV_KEY =
1266
+ "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION";
1267
+ export const DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns";
1268
+ export const DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY =
1269
+ "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS";
1270
+
1271
+ /**
1272
+ * Environment twin of the lessons promotion scope list (operator-approved
1273
+ * lesson promotion, t_1e952e43). The flat machine-config key itself is
1274
+ * `lessons.promotion.scopes`, declared beside its resolver in
1275
+ * `src/core/brain/policy/blocks/lessons.ts` so the brain module owns its
1276
+ * own key vocabulary. Comma-separated scope names; the same parsing rules
1277
+ * as `resolveCounterpartyBriefTriggers` apply (entries NFC-normalized and
1278
+ * trimmed, empty entries dropped, bracket-shaped values malformed). Absent
1279
+ * or empty disables promotion entirely.
1280
+ */
1281
+ export const LESSONS_PROMOTION_SCOPES_ENV_KEY = "OPEN_SECOND_BRAIN_LESSONS_PROMOTION_SCOPES";
1282
+
1283
+ /**
1284
+ * Shared body for a non-negative-integer config value: env var (trimmed)
1285
+ * wins, falling back to the config key (trimmed). Returns `null` when
1286
+ * unset, blank, or not a non-negative integer, so an unconfigured value
1287
+ * leaves the caller's default behaviour intact.
1288
+ */
1289
+ function resolveConfigNonNegativeInt(
1290
+ envKey: string,
1291
+ configKey: string,
1292
+ configPath?: string,
1293
+ ): number | null {
1294
+ const env = process.env[envKey]?.trim();
1295
+ const raw = env || discoverConfig(configPath).data[configKey]?.trim();
1296
+ if (!raw || raw.length === 0) return null;
1297
+ const n = Number(raw);
1298
+ if (!Number.isInteger(n) || n < 0) return null;
1299
+ return n;
1300
+ }
1301
+
1302
+ /**
1303
+ * Max rated-decision recalls per session. `null` (the default) disables
1304
+ * the feature entirely - injection stays byte-identical.
1305
+ */
1306
+ export function resolveDecisionRecallMaxPerSession(configPath?: string): number | null {
1307
+ return resolveConfigNonNegativeInt(
1308
+ DECISION_RECALL_MAX_PER_SESSION_ENV_KEY,
1309
+ DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY,
1310
+ configPath,
1311
+ );
1312
+ }
1313
+
1314
+ /**
1315
+ * Minimum turns between two rated-decision recalls. `null` (unset)
1316
+ * resolves to `0` (no spacing) at the call site.
1317
+ */
1318
+ export function resolveDecisionRecallMinSpacingTurns(configPath?: string): number | null {
1319
+ return resolveConfigNonNegativeInt(
1320
+ DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY,
1321
+ DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY,
1322
+ configPath,
1323
+ );
1324
+ }
1325
+
1326
+ /**
1327
+ * Wikilink output format (Workspace Insight Suite, t_5f31b5f1).
1328
+ * Default `preserve` keeps every generated/normalized link exactly as
1329
+ * typed - byte-identical to pre-suite behaviour. `full` and `short`
1330
+ * select the rewrite mode for `o2b brain links normalize` and for
1331
+ * generators that adopt the kernel. An unknown value fails fast: a
1332
+ * typo must never silently rewrite links in the wrong mode.
1333
+ */
1334
+ export function resolveWikiLinkFormat(configPath?: string): WikiLinkFormat {
1335
+ const env = process.env["OPEN_SECOND_BRAIN_WIKI_LINK_FORMAT"]?.trim();
1336
+ const raw = env || discoverConfig(configPath).data["wiki_link_format"]?.trim();
1337
+ if (raw === undefined || raw === "") return "preserve";
1338
+ if (!isWikiLinkFormat(raw)) {
1339
+ throw new Error(
1340
+ `wiki_link_format must be one of ${WIKI_LINK_FORMATS.join(", ")}; got '${raw}'`,
1341
+ );
1342
+ }
1343
+ return raw;
1344
+ }
1345
+
1346
+ /**
1347
+ * Trigger cooldown window in days (Workspace Insight Suite,
1348
+ * t_cd1fee79): how long a dismissed/acted trigger blocks recreation
1349
+ * and how long a delivered trigger stays out of the morning brief.
1350
+ * Default 7. An invalid value fails fast.
1351
+ */
1352
+ export function resolveTriggerCooldownDays(configPath?: string): number {
1353
+ const env = process.env["OPEN_SECOND_BRAIN_TRIGGER_COOLDOWN_DAYS"]?.trim();
1354
+ const raw = env || discoverConfig(configPath).data["trigger_cooldown_days"]?.trim();
1355
+ if (raw === undefined || raw === "") return 7;
1356
+ const days = Number(raw);
1357
+ if (!Number.isInteger(days) || days < 0) {
1358
+ throw new Error(`trigger_cooldown_days must be a non-negative integer; got '${raw}'`);
1359
+ }
1360
+ return days;
1361
+ }
1362
+
1363
+ /**
1364
+ * Recall-gate telemetry gate (Workspace Insight Suite, t_65036e02).
1365
+ * Default OFF: brain_recall_gate stays a pure diagnostic unless
1366
+ * `recall_gate_telemetry: "true"`, when every decision lands as a
1367
+ * gate_telemetry continuity record (prompt hash only, never the
1368
+ * prompt).
1369
+ */
1370
+ export function resolveRecallGateTelemetry(configPath?: string): boolean {
1371
+ return resolveConfigFlag(
1372
+ "OPEN_SECOND_BRAIN_RECALL_GATE_TELEMETRY",
1373
+ "recall_gate_telemetry",
1374
+ configPath,
1375
+ );
1376
+ }
1377
+
1378
+ /**
1379
+ * Recall adequacy thresholds (retrieval-precision-quality-loop,
1380
+ * t_b8f66fec). Configurable floors that drive the sufficient / weak /
1381
+ * insufficient verdict. Defaults mirror
1382
+ * DEFAULT_RECALL_ADEQUACY_THRESHOLDS (0.6 / 0.3 / 1). Invalid values fail
1383
+ * fast rather than silently reverting to a default.
1384
+ *
1385
+ * What these floors are compared against CHANGED in
1386
+ * a-label-is-not-a-boundary, and the numbers kept their values while
1387
+ * their meaning moved. They used to bound a recall attempt's top
1388
+ * relevance SCORE, which could not work: the keyword lane is min-max
1389
+ * normalised inside the candidate set, so the top row of any recall with
1390
+ * a non-empty keyword lane scored at or above the configured
1391
+ * `search_keyword_weight` whatever it matched - shipped at 0.6, identical
1392
+ * to `recall_adequacy_sufficient`, and 0.65 as measured end to end on a
1393
+ * freshly written keyword-only vault, where the freshness prior is added
1394
+ * on top of the normalised lane. Every keyword recall in the product
1395
+ * therefore graded `sufficient / proceed`, `weak` and `insufficient` were
1396
+ * unreachable, and a hundredth of a point on either key would have
1397
+ * inverted the verdict for every query at once.
1398
+ *
1399
+ * They now bound MATCH QUALITY: the share of the query's IDF mass the
1400
+ * retrieved material covers. That share is absolute where a score was
1401
+ * relative - it does not move with rank position, lane magnitude or
1402
+ * fusion mode - though it is measured over the rows a search delivers, so
1403
+ * a narrower `limit` reports less of it. An operator who tuned these keys
1404
+ * against the old quantity was tuning something that never varied, so no
1405
+ * setting is being silently reinterpreted - but the keys do decide
1406
+ * something now, and 0.6 means "covers at least three fifths of what was
1407
+ * asked" rather than "something was returned".
1408
+ */
1409
+ export function resolveRecallAdequacyThresholds(configPath?: string): {
1410
+ sufficient: number;
1411
+ weak: number;
1412
+ minResults: number;
1413
+ } {
1414
+ const data = discoverConfig(configPath).data;
1415
+ const sufficient = resolveAdequacyFloor(
1416
+ "recall_adequacy_sufficient",
1417
+ process.env["OPEN_SECOND_BRAIN_RECALL_ADEQUACY_SUFFICIENT"],
1418
+ data["recall_adequacy_sufficient"],
1419
+ 0.6,
1420
+ );
1421
+ const weak = resolveAdequacyFloor(
1422
+ "recall_adequacy_weak",
1423
+ process.env["OPEN_SECOND_BRAIN_RECALL_ADEQUACY_WEAK"],
1424
+ data["recall_adequacy_weak"],
1425
+ 0.3,
1426
+ );
1427
+ if (weak > sufficient) {
1428
+ throw new Error(
1429
+ `recall_adequacy_weak (${weak}) must not exceed recall_adequacy_sufficient (${sufficient})`,
1430
+ );
1431
+ }
1432
+ const minResults = resolveAdequacyMinResults(
1433
+ process.env["OPEN_SECOND_BRAIN_RECALL_ADEQUACY_MIN_RESULTS"],
1434
+ data["recall_adequacy_min_results"],
1435
+ );
1436
+ return { sufficient, weak, minResults };
1437
+ }
1438
+
1439
+ function resolveAdequacyFloor(
1440
+ key: string,
1441
+ env: string | undefined,
1442
+ fileValue: string | undefined,
1443
+ fallback: number,
1444
+ ): number {
1445
+ const raw = (env?.trim() || fileValue?.trim()) ?? "";
1446
+ if (raw === "") return fallback;
1447
+ const value = Number(raw);
1448
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
1449
+ throw new Error(`${key} must be a number in [0,1]; got '${raw}'`);
1450
+ }
1451
+ return value;
1452
+ }
1453
+
1454
+ function resolveAdequacyMinResults(env: string | undefined, fileValue: string | undefined): number {
1455
+ const raw = (env?.trim() || fileValue?.trim()) ?? "";
1456
+ if (raw === "") return 1;
1457
+ const value = Number(raw);
1458
+ if (!Number.isInteger(value) || value < 1) {
1459
+ throw new Error(`recall_adequacy_min_results must be a positive integer; got '${raw}'`);
1460
+ }
1461
+ return value;
1462
+ }
1463
+
1464
+ /**
1465
+ * Operator-declared model context window, environment channel
1466
+ * (t_a567cc12). The vault-side channel is the `context:` block of
1467
+ * `Brain/_brain.yaml`, and the BLOCK wins over a value here: the
1468
+ * resolver's deliberate precedence (plan B1) is operator config >
1469
+ * operator env > declared table > `1m` suffix > default, and an
1470
+ * explicit per-call argument wins over both operator channels. The
1471
+ * precedence lives with the resolver that consumes the parsed values,
1472
+ * exactly as the recall-adequacy floors above hand theirs to their
1473
+ * consumer.
1474
+ *
1475
+ * A well-formed positive integer is returned as-is: like every
1476
+ * first-hand declaration it passes through the resolver unclamped - the
1477
+ * declaration exists to state the true window. Any other value fails
1478
+ * fast, mirroring the trio above - a window that silently ignored its
1479
+ * operator would mis-size every pack.
1480
+ */
1481
+ export const MODEL_CONTEXT_WINDOW_ENV_KEY = "OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW";
1482
+
1483
+ /** Parse {@link MODEL_CONTEXT_WINDOW_ENV_KEY}; `undefined` when unset or blank. */
1484
+ export function resolveModelContextWindowEnvTokens(): number | undefined {
1485
+ const raw = process.env[MODEL_CONTEXT_WINDOW_ENV_KEY]?.trim() ?? "";
1486
+ if (raw === "") return undefined;
1487
+ const value = Number(raw);
1488
+ if (!Number.isInteger(value) || value <= 0) {
1489
+ throw new Error(`${MODEL_CONTEXT_WINDOW_ENV_KEY} must be a positive integer; got '${raw}'`);
1490
+ }
1491
+ return value;
1492
+ }
1493
+
1494
+ /**
1495
+ * Generation-report tracing gate (Hindsight brain-loop ops, t_281c3edc).
1496
+ * Default OFF: the inbound `generation_report` continuity path stays
1497
+ * dormant unless `generation_trace_enabled: "true"`, when an agent's
1498
+ * post-handoff usage report lands as a continuity record (prompt hash
1499
+ * and counts only, never the prompt). A per-call option can still enable
1500
+ * a single report when the config gate is off.
1501
+ */
1502
+ export function resolveGenerationTraceEnabled(configPath?: string): boolean {
1503
+ return resolveConfigFlag(
1504
+ "OPEN_SECOND_BRAIN_GENERATION_TRACE_ENABLED",
1505
+ "generation_trace_enabled",
1506
+ configPath,
1507
+ );
1508
+ }
1509
+
1510
+ /**
1511
+ * Route-level MCP latency metrics gate (context-pack-economics-
1512
+ * observability suite). Default OFF: the `mcp_route_latency` continuity
1513
+ * path stays dormant unless `mcp_route_metrics_enabled: "true"`, when the
1514
+ * MCP server records one payload-safe latency record per tool call (tool
1515
+ * name, scope, status, duration, and argument key names only - never
1516
+ * argument values). Fail-open: a failed record never fails the call.
1517
+ */
1518
+ export function resolveMcpRouteMetricsEnabled(configPath?: string): boolean {
1519
+ return resolveConfigFlag(
1520
+ "OPEN_SECOND_BRAIN_MCP_ROUTE_METRICS_ENABLED",
1521
+ "mcp_route_metrics_enabled",
1522
+ configPath,
1523
+ );
1524
+ }
1525
+
1526
+ /**
1527
+ * Token-impact + context-pack-quality ledger gate (context-pack-economics-
1528
+ * observability suite). Default OFF: the `token_impact` / `token_impact_outcome`
1529
+ * continuity paths stay dormant unless `token_impact_ledger_enabled: "true"`,
1530
+ * when opt-in `record`/`outcome` posts to `brain_token_impact` persist the
1531
+ * tokenizer-exact prompt-token delta (baseline vs packed, method-labelled)
1532
+ * and modeled inference-avoidance calibration. Payload-safe: counts and an
1533
+ * opaque pack id only, never raw prompts or recalled text. Fail-open: a
1534
+ * failed write never fails the caller. Read paths (list/summary) ignore the
1535
+ * gate so historical aggregates stay inspectable after it is turned off.
1536
+ */
1537
+ export function resolveTokenImpactLedgerEnabled(configPath?: string): boolean {
1538
+ return resolveConfigFlag(
1539
+ "OPEN_SECOND_BRAIN_TOKEN_IMPACT_LEDGER_ENABLED",
1540
+ "token_impact_ledger_enabled",
1541
+ configPath,
1542
+ );
1543
+ }
1544
+
1545
+ /**
1546
+ * Agent-operable context-pack outcome-loop gate (context-pack-economics-
1547
+ * observability suite, C5). Default OFF: the `context_pack_outcome`
1548
+ * continuity path (and its composed `token_impact_outcome` calibration
1549
+ * write) stays dormant unless `context_pack_outcome_enabled: "true"`, when
1550
+ * an opt-in `post` to `brain_context_pack_outcome` records one compact
1551
+ * outcome row - first-pass/repair/retry counters plus the three strictly
1552
+ * separate token signals (exact / modeled / observed) - correlated to a
1553
+ * carried context-pack quality-sample id. Payload-safe: counts and an
1554
+ * opaque sample id only, never raw prompts, completions, or recalled text.
1555
+ * Fail-open: a failed write never fails the caller. Read paths (list/
1556
+ * summary) ignore the gate so historical aggregates stay inspectable.
1557
+ */
1558
+ export function resolveContextPackOutcomeEnabled(configPath?: string): boolean {
1559
+ return resolveConfigFlag(
1560
+ "OPEN_SECOND_BRAIN_CONTEXT_PACK_OUTCOME_ENABLED",
1561
+ "context_pack_outcome_enabled",
1562
+ configPath,
1563
+ );
1564
+ }
1565
+
1566
+ /**
1567
+ * Prompt-time bounded recall-inject gate (recall-trust-and-write-surface,
1568
+ * A2 / t_2ce46130). Default OFF: the opt-in UserPromptSubmit recall-inject
1569
+ * hook stays a no-op unless `recall_inject_enabled: "true"` (or the matching
1570
+ * env override), when each user prompt relevance-recalls a small bounded,
1571
+ * clip-safe brief of vault notes and injects it as additionalContext. The
1572
+ * hook is fail-closed (any error or timeout injects nothing) and audited
1573
+ * (every inject/abstain/error decision writes one line). Flag off keeps the
1574
+ * prompt preamble byte-identical.
1575
+ */
1576
+ export function resolveRecallInjectEnabled(configPath?: string): boolean {
1577
+ return resolveConfigFlag(
1578
+ "OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED",
1579
+ "recall_inject_enabled",
1580
+ configPath,
1581
+ );
1582
+ }
1583
+
1584
+ /**
1585
+ * The per-phase answer-time quote-check modes (answer-trust wave, Lane A).
1586
+ *
1587
+ * Three keys - `quote_check.recall`, `quote_check.active`,
1588
+ * `quote_check.subagent` - live in the `quote_check` block of
1589
+ * `Brain/_brain.yaml`, each `off|shadow|enforce`, default `shadow`, each
1590
+ * with its own resolver and no second reader. The shape follows the
1591
+ * decision-model per-use mode switch
1592
+ * (`src/core/decision-model/contract.ts`, `DECISION_MODEL_MODES`).
1593
+ *
1594
+ * Channel honesty: the Stop hook's annotation renders on Claude Code
1595
+ * only. The other registered runtimes render no Stop annotation - and
1596
+ * grok ships no `transcript_path` at all - so there the check is
1597
+ * silently inert, and a non-`off` mode promises findings that only a
1598
+ * Claude Code session (or the `enforce` Brain-log trail, where a
1599
+ * transcript is read at all) delivers.
1600
+ */
1601
+ export const ANSWER_QUOTE_CHECK_MODES = Object.freeze(["off", "shadow", "enforce"] as const);
1602
+
1603
+ /** Closed union over {@link ANSWER_QUOTE_CHECK_MODES}. */
1604
+ export type AnswerQuoteCheckMode = (typeof ANSWER_QUOTE_CHECK_MODES)[number];
1605
+
1606
+ /** Narrow a mode read back off a payload or a fixture. */
1607
+ export function isAnswerQuoteCheckMode(value: unknown): value is AnswerQuoteCheckMode {
1608
+ return (
1609
+ typeof value === "string" && (ANSWER_QUOTE_CHECK_MODES as ReadonlyArray<string>).includes(value)
1610
+ );
1611
+ }
1612
+
1613
+ /** The `_brain.yaml` block the three keys live in, and its phase keys. */
1614
+ const QUOTE_CHECK_BLOCK = "quote_check";
1615
+
1616
+ /** The phases the quote check runs on, in their pinned listing order. */
1617
+ export const ANSWER_QUOTE_CHECK_PHASES = Object.freeze(["recall", "active", "subagent"] as const);
1618
+
1619
+ /** Closed union over {@link ANSWER_QUOTE_CHECK_PHASES}. */
1620
+ export type AnswerQuoteCheckPhase = (typeof ANSWER_QUOTE_CHECK_PHASES)[number];
1621
+
1622
+ /** The mode every phase resolves to when nothing is configured. */
1623
+ export const ANSWER_QUOTE_CHECK_DEFAULT: AnswerQuoteCheckMode = "shadow";
1624
+ const QUOTE_CHECK_DEFAULT = ANSWER_QUOTE_CHECK_DEFAULT;
1625
+
1626
+ /** Paths and keys whose unknown-field warning already fired in this process. */
1627
+ const quoteCheckWarnedUnknownKeys = new Set<string>();
1628
+
1629
+ /**
1630
+ * The `quote_check` block parsed off `path`, or `null` when the file or
1631
+ * the block is absent - the one condition resolved to defaults, because
1632
+ * there are no operator settings to contradict. A file (or block) that
1633
+ * EXISTS but cannot be honored raises by name instead: read like
1634
+ * `loadBrainConfig`'s absent/present split, so a typo can never silently
1635
+ * turn a configured `enforce` into the default.
1636
+ */
1637
+ function readQuoteCheckBlock(path: string): Record<string, unknown> | null {
1638
+ let stat: Stats;
1639
+ try {
1640
+ const probed = statSync(path, { throwIfNoEntry: false });
1641
+ if (probed === undefined) return null;
1642
+ stat = probed;
1643
+ } catch (err) {
1644
+ throw new BrainConfigError(
1645
+ `failed to stat: ${(err as Error).message}`,
1646
+ QUOTE_CHECK_BLOCK,
1647
+ path,
1648
+ );
1649
+ }
1650
+ if (!stat.isFile()) {
1651
+ throw new BrainConfigError(
1652
+ "path exists but is not a regular file; its settings are not in force and are not read as absent",
1653
+ QUOTE_CHECK_BLOCK,
1654
+ path,
1655
+ );
1656
+ }
1657
+ let parsed: Record<string, unknown>;
1658
+ try {
1659
+ parsed = parseBrainYaml(
1660
+ new TextDecoder("utf-8", { fatal: true }).decode(readFileSync(path)),
1661
+ ) as Record<string, unknown>;
1662
+ } catch (err) {
1663
+ throw new BrainConfigError(
1664
+ `failed to parse: ${(err as Error).message}`,
1665
+ QUOTE_CHECK_BLOCK,
1666
+ path,
1667
+ );
1668
+ }
1669
+ const block = parsed[QUOTE_CHECK_BLOCK];
1670
+ if (block === undefined) return null;
1671
+ if (typeof block !== "object" || block === null || Array.isArray(block)) {
1672
+ throw new BrainConfigError(
1673
+ `expected a block of per-phase modes, got ${Array.isArray(block) ? "an array" : typeof block}`,
1674
+ QUOTE_CHECK_BLOCK,
1675
+ path,
1676
+ );
1677
+ }
1678
+ return block as Record<string, unknown>;
1679
+ }
1680
+
1681
+ /**
1682
+ * Unknown keys inside the `quote_check` block warn per the strict-block
1683
+ * convention (`warnUnknownKeys` in the policy validator), once per key
1684
+ * per process on stderr - the audit channel every consumer of these
1685
+ * resolvers (the Stop hook) already keeps. A warning never changes the
1686
+ * resolved mode.
1687
+ */
1688
+ function warnUnknownQuoteCheckKeys(path: string, block: Record<string, unknown>): void {
1689
+ for (const key of Object.keys(block)) {
1690
+ if ((ANSWER_QUOTE_CHECK_PHASES as ReadonlyArray<string>).includes(key)) continue;
1691
+ const stamp = `${path}\0${key}`;
1692
+ if (quoteCheckWarnedUnknownKeys.has(stamp)) continue;
1693
+ quoteCheckWarnedUnknownKeys.add(stamp);
1694
+ process.stderr.write(`${QUOTE_CHECK_BLOCK}.${key}: unknown field ignored (forward-compat)\n`);
1695
+ }
1696
+ }
1697
+
1698
+ /** One phase's mode off the block; every exported resolver is this read. */
1699
+ function resolveAnswerQuoteCheckPhase(
1700
+ phase: AnswerQuoteCheckPhase,
1701
+ path: string | null,
1702
+ ): AnswerQuoteCheckMode {
1703
+ if (path === null) return QUOTE_CHECK_DEFAULT;
1704
+ const block = readQuoteCheckBlock(path);
1705
+ if (block === null) return QUOTE_CHECK_DEFAULT;
1706
+ warnUnknownQuoteCheckKeys(path, block);
1707
+ const raw = block[phase];
1708
+ if (raw === undefined) return QUOTE_CHECK_DEFAULT;
1709
+ if (!isAnswerQuoteCheckMode(raw)) {
1710
+ throw new BrainConfigError(
1711
+ `unsupported value ${JSON.stringify(raw)}; expected one of ${ANSWER_QUOTE_CHECK_MODES.join(
1712
+ ", ",
1713
+ )}`,
1714
+ `${QUOTE_CHECK_BLOCK}.${phase}`,
1715
+ path,
1716
+ );
1717
+ }
1718
+ return raw;
1719
+ }
1720
+
1721
+ /**
1722
+ * The brain config file the resolvers read when the caller names none:
1723
+ * the standard vault's `Brain/_brain.yaml`. `null` when no vault
1724
+ * resolves, which leaves every phase at its default - a vaultless install
1725
+ * has no operator settings to contradict. This is the legacy layout only:
1726
+ * a vault switched to the store keeps the block in its shared settings,
1727
+ * which `resolveAnswerQuoteCheckModes` (`src/core/brain/quote-check-modes.ts`)
1728
+ * reads - the entry point the Stop hook uses.
1729
+ */
1730
+ function defaultAnswerQuoteCheckConfigPath(): string | null {
1731
+ const vault = resolveVault();
1732
+ return vault === null ? null : join(vault, BRAIN_ROOT_REL, BRAIN_CONFIG_FILE);
1733
+ }
1734
+
1735
+ /**
1736
+ * Mode of `quote_check.recall` (answer-trust wave, Lane A): whether the
1737
+ * Stop hook checks quoted spans against recall-injected notes, and what
1738
+ * it may do about them. See {@link resolveAnswerQuoteCheckPhase} for the
1739
+ * shared semantics; the hook additionally gates this phase on
1740
+ * {@link resolveRecallInjectEnabled}.
1741
+ */
1742
+ export function resolveAnswerQuoteCheckRecall(configPath?: string): AnswerQuoteCheckMode {
1743
+ return resolveAnswerQuoteCheckPhase("recall", configPath ?? defaultAnswerQuoteCheckConfigPath());
1744
+ }
1745
+
1746
+ /**
1747
+ * Mode of `quote_check.active`: the same check over the notes the
1748
+ * SessionStart active digest emitted. The hook gates this phase on a live
1749
+ * active-injection ledger (`osb.active_inject.emitted`).
1750
+ */
1751
+ export function resolveAnswerQuoteCheckActive(configPath?: string): AnswerQuoteCheckMode {
1752
+ return resolveAnswerQuoteCheckPhase("active", configPath ?? defaultAnswerQuoteCheckConfigPath());
1753
+ }
1754
+
1755
+ /**
1756
+ * Mode of `quote_check.subagent`: the same check over the context the
1757
+ * sub-agent carrier delivered. The hook gates this phase on a live
1758
+ * sub-agent delivery ledger.
1759
+ */
1760
+ export function resolveAnswerQuoteCheckSubagent(configPath?: string): AnswerQuoteCheckMode {
1761
+ return resolveAnswerQuoteCheckPhase(
1762
+ "subagent",
1763
+ configPath ?? defaultAnswerQuoteCheckConfigPath(),
1764
+ );
1765
+ }
1766
+
1767
+ /** Recall-inject cap overrides that passed validation (absent = hook default). */
1768
+ export interface RecallInjectCapsResolution {
1769
+ readonly caps: {
1770
+ readonly maxNotes?: number;
1771
+ readonly maxChars?: number;
1772
+ readonly timeBudgetMs?: number;
1773
+ readonly confidenceFloor?: number;
1774
+ };
1775
+ /** Config key names whose value was rejected, in resolution order. */
1776
+ readonly invalid: ReadonlyArray<string>;
1777
+ }
1778
+
1779
+ /** `raw` as a number within `[min, max]` (an integer when asked), else `undefined`. */
1780
+ function parseBounded(raw: string, min: number, max: number, integer: boolean): number | undefined {
1781
+ const value = Number(raw);
1782
+ if (!Number.isFinite(value) || (integer && !Number.isInteger(value))) return undefined;
1783
+ if (value < min || value > max) return undefined;
1784
+ return value;
1785
+ }
1786
+
1787
+ /** One recall-inject cap: its field, env override, config key and range. */
1788
+ const RECALL_INJECT_CAP_SPECS = [
1789
+ {
1790
+ field: "maxNotes",
1791
+ env: "OPEN_SECOND_BRAIN_RECALL_INJECT_MAX_NOTES",
1792
+ key: "recall_inject_max_notes",
1793
+ min: 1,
1794
+ max: 10,
1795
+ integer: true,
1796
+ },
1797
+ {
1798
+ field: "maxChars",
1799
+ env: "OPEN_SECOND_BRAIN_RECALL_INJECT_MAX_CHARS",
1800
+ key: "recall_inject_max_chars",
1801
+ min: 200,
1802
+ max: 8000,
1803
+ integer: true,
1804
+ },
1805
+ {
1806
+ field: "timeBudgetMs",
1807
+ env: "OPEN_SECOND_BRAIN_RECALL_INJECT_TIME_BUDGET_MS",
1808
+ key: "recall_inject_time_budget_ms",
1809
+ min: 250,
1810
+ max: 6000,
1811
+ integer: true,
1812
+ },
1813
+ {
1814
+ field: "confidenceFloor",
1815
+ env: "OPEN_SECOND_BRAIN_RECALL_INJECT_CONFIDENCE_FLOOR",
1816
+ key: "recall_inject_confidence_floor",
1817
+ min: 0,
1818
+ max: 1,
1819
+ integer: false,
1820
+ },
1821
+ ] as const;
1822
+
1823
+ /**
1824
+ * Operator overrides of the recall-inject caps (note count, brief size, time
1825
+ * budget, confidence floor). Each key resolves env first, then config. A value
1826
+ * out of range, non-numeric or (for the integer caps) fractional is left out
1827
+ * of `caps` and named in `invalid`, so the hook keeps its built-in default and
1828
+ * can audit the rejection. Unset keys contribute nothing, so a default install
1829
+ * resolves to empty caps.
1830
+ */
1831
+ export function resolveRecallInjectCaps(configPath?: string): RecallInjectCapsResolution {
1832
+ const data = discoverConfig(configPath).data;
1833
+ const caps: Record<string, number> = {};
1834
+ const invalid: string[] = [];
1835
+ for (const spec of RECALL_INJECT_CAP_SPECS) {
1836
+ const raw = readSetting(spec.env, spec.key, data);
1837
+ if (raw === undefined) continue;
1838
+ const value = parseBounded(raw, spec.min, spec.max, spec.integer);
1839
+ if (value === undefined) invalid.push(rejectedSettingName(spec.env, spec.key));
1840
+ else caps[spec.field] = value;
1841
+ }
1842
+ return { caps: caps as RecallInjectCapsResolution["caps"], invalid };
1843
+ }
1844
+
1845
+ /**
1846
+ * Recall-inject per-session dedupe. Default ON: a note already injected this
1847
+ * session is not injected again. Only an explicit falsy literal (`"false"` or
1848
+ * `"0"`, env first, then config) turns it off.
1849
+ */
1850
+ export function resolveRecallInjectDedupe(configPath?: string): boolean {
1851
+ const raw = readSetting(
1852
+ "OPEN_SECOND_BRAIN_RECALL_INJECT_DEDUPE",
1853
+ "recall_inject_dedupe",
1854
+ discoverConfig(configPath).data,
1855
+ );
1856
+ return raw !== "false" && raw !== "0";
1857
+ }
1858
+
1859
+ /**
1860
+ * Active-digest re-delivery gate. Default OFF: the SessionStart digest is
1861
+ * emitted as one payload, byte-identical to today, unless
1862
+ * `reground_parts_enabled: "true"` (or the matching env override), when an
1863
+ * over-ceiling digest is split and parts 2..n are re-delivered on later events.
1864
+ */
1865
+ export function resolveRegroundPartsEnabled(configPath?: string): boolean {
1866
+ return resolveConfigFlag(
1867
+ "OPEN_SECOND_BRAIN_REGROUND_PARTS_ENABLED",
1868
+ "reground_parts_enabled",
1869
+ configPath,
1870
+ );
1871
+ }
1872
+
1873
+ /**
1874
+ * Default per-part ceiling of a split digest, in UTF-16 code units: the
1875
+ * observed Claude Code 10,000-unit persistence threshold less 10%.
1876
+ */
1877
+ export const REGROUND_PART_CHARS_DEFAULT = 9000;
1878
+
1879
+ /** The per-part ceiling that applies, and the keys whose value was rejected on the way. */
1880
+ export interface RegroundPartCharsResolution {
1881
+ readonly chars: number;
1882
+ /**
1883
+ * Names of the settings whose value was out of range or not an integer, in
1884
+ * precedence order: the environment variable when the value came from it,
1885
+ * the config key otherwise.
1886
+ */
1887
+ readonly invalid: ReadonlyArray<string>;
1888
+ }
1889
+
1890
+ /**
1891
+ * Per-part ceiling of a split digest for one host runtime. Precedence:
1892
+ * `reground_part_chars_<runtime>`, then `reground_part_chars`, then
1893
+ * {@link REGROUND_PART_CHARS_DEFAULT}; each level reads env first, then
1894
+ * config. A value outside the integer range 2000..100000 falls through to the
1895
+ * next level and is named in `invalid` by the source it came from, so the
1896
+ * caller can report it.
1897
+ */
1898
+ export function resolveRegroundPartChars(
1899
+ runtime: "claudecode" | "codex",
1900
+ configPath?: string,
1901
+ ): RegroundPartCharsResolution {
1902
+ const data = discoverConfig(configPath).data;
1903
+ const levels = [
1904
+ [
1905
+ `OPEN_SECOND_BRAIN_REGROUND_PART_CHARS_${runtime.toUpperCase()}`,
1906
+ `reground_part_chars_${runtime}`,
1907
+ ],
1908
+ ["OPEN_SECOND_BRAIN_REGROUND_PART_CHARS", "reground_part_chars"],
1909
+ ] as const;
1910
+ const invalid: string[] = [];
1911
+ for (const [envKey, configKey] of levels) {
1912
+ const raw = readSetting(envKey, configKey, data);
1913
+ if (raw === undefined) continue;
1914
+ const value = parseBounded(raw, 2000, 100_000, true);
1915
+ if (value !== undefined) return { chars: value, invalid };
1916
+ invalid.push(rejectedSettingName(envKey, configKey));
1917
+ }
1918
+ return { chars: REGROUND_PART_CHARS_DEFAULT, invalid };
1919
+ }
1920
+
1921
+ /**
1922
+ * End-of-turn hygiene digest gate (context-injection-pipeline). Default
1923
+ * OFF: the Stop hook stays a silent no-op unless `hygiene_digest_enabled`
1924
+ * is `"true"` (or the matching env override). Resolved BEFORE the vault so
1925
+ * the off path costs one config read - the hook fires after every turn on
1926
+ * every install, and the detectors and search index load only after this
1927
+ * gate passes.
1928
+ */
1929
+ export function resolveHygieneDigestEnabled(configPath?: string): boolean {
1930
+ return resolveConfigFlag(
1931
+ "OPEN_SECOND_BRAIN_HYGIENE_DIGEST_ENABLED",
1932
+ "hygiene_digest_enabled",
1933
+ configPath,
1934
+ );
1935
+ }
1936
+
1937
+ /**
1938
+ * Shared body for a default-ON switch: env var (trimmed) wins, falling
1939
+ * back to the config key (trimmed); only the literal strings `"false"` and
1940
+ * `"0"` turn it off, anything else (including absence) leaves it on - the
1941
+ * `recall_inject_dedupe` reading.
1942
+ */
1943
+ function resolveConfigSwitchDefaultOn(
1944
+ envKey: string,
1945
+ configKey: string,
1946
+ configPath?: string,
1947
+ ): boolean {
1948
+ const raw = readSetting(envKey, configKey, () => discoverConfig(configPath).data);
1949
+ return raw !== "false" && raw !== "0";
1950
+ }
1951
+
1952
+ /**
1953
+ * End-of-turn brain-event nudge (`hooks/stop-log-guardrail.ts`). Default
1954
+ * ON: after a turn that changed files but recorded no brain event, the
1955
+ * model is reminded once. `stop_guardrail_enabled: "false"` (or `"0"`, or
1956
+ * the env override) turns the nudge off on this machine entirely.
1957
+ */
1958
+ export function resolveStopGuardrailEnabled(configPath?: string): boolean {
1959
+ return resolveConfigSwitchDefaultOn(
1960
+ "OPEN_SECOND_BRAIN_STOP_GUARDRAIL_ENABLED",
1961
+ "stop_guardrail_enabled",
1962
+ configPath,
1963
+ );
1964
+ }
1965
+
1966
+ /**
1967
+ * Answer-time quote check (`hooks/answer-quote-check.ts`) master switch.
1968
+ * Default ON. `quote_check_enabled: "false"` (or `"0"`, or the env
1969
+ * override) turns the whole hook off on this machine: no annotation, no
1970
+ * `enforce` Brain-log event, no `reply_presence` record - whatever the
1971
+ * per-phase `quote_check.<phase>` modes in `_brain.yaml` say. With it on,
1972
+ * those modes decide as before.
1973
+ */
1974
+ export function resolveQuoteCheckEnabled(configPath?: string): boolean {
1975
+ return resolveConfigSwitchDefaultOn(
1976
+ "OPEN_SECOND_BRAIN_QUOTE_CHECK_ENABLED",
1977
+ "quote_check_enabled",
1978
+ configPath,
1979
+ );
1980
+ }
1981
+
1982
+ /** How the end-of-turn advisories reach the model on Claude Code. */
1983
+ export type StopAdvisoryDelivery = "async" | "sync";
1984
+
1985
+ /**
1986
+ * Delivery form of the end-of-turn advisories on Claude Code (the brain-event
1987
+ * nudge, the quote check and the hygiene digest). Default `async`: the
1988
+ * synchronous Stop hooks compute and write their durable records, and the
1989
+ * background `stop-advisory-deliver` hook hands the text to the model with
1990
+ * the next user message - not printed in the chat, no extra model turn. A
1991
+ * one-shot `claude -p` run kills that background hook at teardown, so the
1992
+ * text never arrives there. `stop_advisory_delivery: "sync"` (or the env
1993
+ * override `OPEN_SECOND_BRAIN_STOP_ADVISORY_DELIVERY`) selects the
1994
+ * synchronous form instead: the text is printed as "Stop hook says: ..." and
1995
+ * the turn continues once so the model can act on it - the form for people
1996
+ * who run headless. Any other value reads as `async`.
1997
+ */
1998
+ export function resolveStopAdvisoryDelivery(configPath?: string): StopAdvisoryDelivery {
1999
+ const raw = readSetting(
2000
+ "OPEN_SECOND_BRAIN_STOP_ADVISORY_DELIVERY",
2001
+ "stop_advisory_delivery",
2002
+ () => discoverConfig(configPath).data,
2003
+ );
2004
+ return raw === "sync" ? "sync" : "async";
2005
+ }
2006
+
2007
+ /**
2008
+ * Tiered context-injection nav tier gate (retrieval-quality-and-context-delivery,
2009
+ * D1 / t_2d4f34d7). Default OFF: the additive navigation/map tier stays a
2010
+ * no-op unless `nav_tier_enabled: "true"` (or the matching env override). The
2011
+ * always-on kernel (active-inject / recall-inject) is untouched either way, so
2012
+ * flag off keeps the session preamble byte-identical; flag on injects a
2013
+ * structural navmap only on cadence or first-turn trigger.
2014
+ */
2015
+ export function resolveNavTierEnabled(configPath?: string): boolean {
2016
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_NAV_TIER_ENABLED", "nav_tier_enabled", configPath);
2017
+ }
2018
+
2019
+ /**
2020
+ * Optional nav-tier cadence window override in minutes (D1). A valid positive
2021
+ * integer (env first, then config) wins; anything else returns undefined so
2022
+ * the caller falls back to the named-constant default. The cadence window is
2023
+ * the interval during which a fresh nav-tier stamp suppresses re-injection.
2024
+ */
2025
+ export function resolveNavTierCadenceMinutes(configPath?: string): number | undefined {
2026
+ const env = process.env["OPEN_SECOND_BRAIN_NAV_TIER_CADENCE_MINUTES"]?.trim();
2027
+ const raw = env || discoverConfig(configPath).data["nav_tier_cadence_minutes"]?.trim();
2028
+ if (!raw) return undefined;
2029
+ const value = Number(raw);
2030
+ if (!Number.isInteger(value) || value < 1) return undefined;
2031
+ return value;
2032
+ }
2033
+
2034
+ /**
2035
+ * Strict PreToolUse read-block gate (retrieval-quality-and-context-delivery,
2036
+ * D2 / t_36b0fd8d). Default OFF: the opt-in PreToolUse hook stays permissive
2037
+ * (emits nothing, byte-identical to today) unless `hook_strict_enabled:
2038
+ * "true"` (or the matching env override). Flag on denies the FIRST raw
2039
+ * vault-file read of a session with a redirect to the brain search surface,
2040
+ * then downgrades to a soft nudge; every failure path fails open.
2041
+ */
2042
+ export function resolveHookStrictEnabled(configPath?: string): boolean {
2043
+ return resolveConfigFlag(
2044
+ "OPEN_SECOND_BRAIN_HOOK_STRICT_ENABLED",
2045
+ "hook_strict_enabled",
2046
+ configPath,
2047
+ );
2048
+ }
2049
+
2050
+ /**
2051
+ * PreToolUse host-settings backup hook (t_f4555087). Default OFF: the
2052
+ * opt-in hook stays a byte-identical no-op unless `host_settings_backup:
2053
+ * "true"` (or the matching env override). Flag on, a file-tool call
2054
+ * targeting a Claude settings file gets its current content backed up -
2055
+ * into a timestamped folder beside the target, with one audit receipt -
2056
+ * before the write is allowed; a backup that cannot be taken denies the
2057
+ * call via stdout. The hook wrapper restates the flag read stdlib-only;
2058
+ * this resolver is the canonical definition the wrapper's twin must
2059
+ * agree with (pinned by the hook tests).
2060
+ */
2061
+ export function resolveHostSettingsBackupEnabled(configPath?: string): boolean {
2062
+ return resolveConfigFlag(
2063
+ "OPEN_SECOND_BRAIN_HOST_SETTINGS_BACKUP",
2064
+ "host_settings_backup",
2065
+ configPath,
2066
+ );
2067
+ }
2068
+
2069
+ /**
2070
+ * Env var and config key of the maintenance lane's embedding opt-in.
2071
+ * Named because the lane quotes them back: a run that skipped the
2072
+ * embedding phase says which switch would turn it on.
2073
+ */
2074
+ export const MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS";
2075
+ export const MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings";
2076
+
2077
+ /**
2078
+ * Whether the unattended maintenance lane (`o2b brain maintenance run`
2079
+ * and `brain_maintenance`) may run the embedding phase of its reindex
2080
+ * pass. Default OFF: a cron that runs the lane stays keyword-only and
2081
+ * contacts no provider unless the operator opts in, because provider
2082
+ * spend only happens behind an explicit gate. When on, the embedding
2083
+ * cost gate (`embedding_cost_gate_usd`) still applies to every pass.
2084
+ */
2085
+ export function resolveMaintenanceEmbeddings(configPath?: string): boolean {
2086
+ return resolveConfigFlag(
2087
+ MAINTENANCE_EMBEDDINGS_ENV,
2088
+ MAINTENANCE_EMBEDDINGS_CONFIG_KEY,
2089
+ configPath,
2090
+ );
2091
+ }
2092
+
2093
+ /**
2094
+ * Env var and config key of the maintenance lane's custom-task master
2095
+ * switch. Named because the lane quotes them back: `status` says which
2096
+ * of the two turned declared custom tasks off.
2097
+ */
2098
+ export const MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS";
2099
+ export const MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks";
2100
+
2101
+ /** Which source decided a boolean switch: the env override, the config key, or neither. */
2102
+ export type MaintenanceSwitchSource = "env" | "config" | "unset";
2103
+
2104
+ /**
2105
+ * Whether the maintenance lane may run the install-owned custom tasks
2106
+ * declared as `maintenance_custom_<name>` keys in this config file, and
2107
+ * the source that decided it, so `status` can name the env override when
2108
+ * that is what turned the declared tasks off. Default OFF: a declared
2109
+ * command is operator-authored shell, so it runs only behind an explicit
2110
+ * opt-in, and `..._CUSTOM_TASKS=0` in the env turns it off on one host
2111
+ * without editing the shared file. The commands themselves are read from
2112
+ * this machine config only, never from the vault. Same parse as every
2113
+ * other flag in this file. A caller that already parsed the config passes
2114
+ * its `data`, so the switch and the declarations come from one snapshot.
2115
+ */
2116
+ export function resolveMaintenanceCustomTasksSwitch(
2117
+ configPath?: string,
2118
+ data: Readonly<Record<string, string>> = discoverConfig(configPath).data,
2119
+ ): {
2120
+ readonly enabled: boolean;
2121
+ readonly source: MaintenanceSwitchSource;
2122
+ } {
2123
+ const env = process.env[MAINTENANCE_CUSTOM_TASKS_ENV]?.trim();
2124
+ const fromConfig = data[MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY]?.trim();
2125
+ return {
2126
+ enabled: isFlagOn(env || fromConfig),
2127
+ source: env ? "env" : fromConfig ? "config" : "unset",
2128
+ };
2129
+ }
2130
+
2131
+ /**
2132
+ * Env var and config key of the codegraph partner-check switch. Named
2133
+ * rather than inlined because the doctor QUOTES them: the line it prints
2134
+ * for a check it did not run has to tell the operator which switch turned
2135
+ * it off, and a hand-copied spelling there would drift from the one that
2136
+ * is actually read.
2137
+ */
2138
+ export const PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED";
2139
+ export const PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";
2140
+
2141
+ /**
2142
+ * Codegraph partner-check switch (nothing-runs-unwatched, U12). Default
2143
+ * OFF, so `o2b doctor` consults the partner exactly as it always has.
2144
+ *
2145
+ * It is an env var plus a config key - the shape every other boolean gate
2146
+ * in this file takes - rather than a CLI flag, for two reasons. The
2147
+ * property being expressed belongs to a MACHINE ("the partner CLI is
2148
+ * installed here and asking it costs seconds against a cold HOME"), not to
2149
+ * one invocation, so it wants a place to be written down once. And
2150
+ * `doctor()` has three callers - the CLI, the MCP `vault_health` tool and
2151
+ * the OpenClaw extension - of which a flag would reach one; the other two
2152
+ * take no arguments an operator controls.
2153
+ *
2154
+ * The switch gates the DOCTOR's automatic consultation only. `o2b partner
2155
+ * codegraph report` is the operator asking the partner directly, and an
2156
+ * answer they asked for is never suppressed by a switch about background
2157
+ * cost.
2158
+ */
2159
+ export function resolvePartnerCodegraphDisabled(configPath?: string): boolean {
2160
+ return resolveConfigFlag(
2161
+ PARTNER_CODEGRAPH_DISABLED_ENV,
2162
+ PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY,
2163
+ configPath,
2164
+ );
2165
+ }
2166
+
2167
+ /**
2168
+ * Knowledge-gap loop gate (recall-trust-and-write-surface, A3 /
2169
+ * t_67d38036). Default OFF: the opt-in session-start gap agenda and
2170
+ * session-end gap promotion/auto-close stay dormant unless
2171
+ * `gap_loop_enabled: "true"` (or the matching env override). Flag off keeps
2172
+ * the session preamble byte-identical and writes no gap-task notes.
2173
+ */
2174
+ export function resolveGapLoopEnabled(configPath?: string): boolean {
2175
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_GAP_LOOP_ENABLED", "gap_loop_enabled", configPath);
2176
+ }
2177
+
2178
+ /**
2179
+ * Session-start backlog nudge gate (session-mining-economy, t_0358af42).
2180
+ * Default OFF: the SessionStart hook that reports the undistilled-session
2181
+ * count stays dormant unless `backlog_nudge_enabled: "true"` (or the
2182
+ * matching env override). Flag off keeps the session preamble
2183
+ * byte-identical and writes no throttle state.
2184
+ */
2185
+ export function resolveBacklogNudgeEnabled(configPath?: string): boolean {
2186
+ return resolveConfigFlag(
2187
+ "OPEN_SECOND_BRAIN_BACKLOG_NUDGE_ENABLED",
2188
+ "backlog_nudge_enabled",
2189
+ configPath,
2190
+ );
2191
+ }
2192
+
2193
+ /**
2194
+ * Session-start cross-agent log catch-up gate (t_3b44cd9a). Default OFF:
2195
+ * the SessionStart hook that replays the `Brain/log` lines other agents
2196
+ * appended stays dormant unless `log_catchup_enabled: "true"` (or the
2197
+ * matching env override). Flag off keeps the session preamble
2198
+ * byte-identical and writes no cursor state.
2199
+ */
2200
+ export function resolveLogCatchupEnabled(configPath?: string): boolean {
2201
+ return resolveConfigFlag(
2202
+ "OPEN_SECOND_BRAIN_LOG_CATCHUP_ENABLED",
2203
+ "log_catchup_enabled",
2204
+ configPath,
2205
+ );
2206
+ }
2207
+
2208
+ /**
2209
+ * Optional gap-loop recurrence threshold override (A3). A valid positive
2210
+ * integer (env first, then config) wins; anything else returns undefined so
2211
+ * the caller falls back to the named-constant default. Env-overridable so an
2212
+ * operator can tune how often a gap must recur before it promotes to a task.
2213
+ */
2214
+ export function resolveGapLoopThreshold(configPath?: string): number | undefined {
2215
+ const env = process.env["OPEN_SECOND_BRAIN_GAP_LOOP_THRESHOLD"]?.trim();
2216
+ const raw = env || discoverConfig(configPath).data["gap_loop_threshold"]?.trim();
2217
+ if (!raw) return undefined;
2218
+ const value = Number(raw);
2219
+ if (!Number.isInteger(value) || value < 1) return undefined;
2220
+ return value;
2221
+ }
2222
+
2223
+ /**
2224
+ * Optional external judge command for the memory benchmark (Memory
2225
+ * Observability Suite, t_882c396a). Unset (the default) means the
2226
+ * judge phase is skipped - the harness itself never calls an LLM.
2227
+ */
2228
+ export function resolveBenchJudgeCmd(configPath?: string): string | undefined {
2229
+ const env = process.env["OPEN_SECOND_BRAIN_BENCH_JUDGE_CMD"]?.trim();
2230
+ const raw = env || discoverConfig(configPath).data["bench_judge_cmd"]?.trim();
2231
+ return raw !== undefined && raw !== "" ? raw : undefined;
2232
+ }
2233
+
2234
+ export const SESSION_CAPTURE_ROLES = ["user", "assistant", "system", "tool", "meta"] as const;
2235
+
2236
+ export type SessionCaptureRole = (typeof SESSION_CAPTURE_ROLES)[number];
2237
+
2238
+ function isSessionCaptureRole(value: string): value is SessionCaptureRole {
2239
+ return (SESSION_CAPTURE_ROLES as ReadonlyArray<string>).includes(value);
2240
+ }
2241
+
2242
+ /**
2243
+ * Config-level default for session-capture role filtering (Agent
2244
+ * Surface Suite, t_e2346fe9). `session_capture_roles` is a
2245
+ * comma-separated subset of user/assistant/system/tool/meta; absent or
2246
+ * empty means "capture every role" (null = no filter, bit-identical to
2247
+ * the pre-key behaviour). An unknown role name fails fast - a silent
2248
+ * typo here would silently drop memory.
2249
+ */
2250
+ export function resolveSessionCaptureRoles(configPath?: string): SessionCaptureRole[] | null {
2251
+ const env = process.env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_ROLES"]?.trim();
2252
+ const raw = env || discoverConfig(configPath).data["session_capture_roles"]?.trim();
2253
+ if (!raw) return null;
2254
+ const roles: SessionCaptureRole[] = [];
2255
+ for (const part of raw.split(",")) {
2256
+ const role = part.trim().toLowerCase();
2257
+ if (role.length === 0) continue;
2258
+ if (!isSessionCaptureRole(role)) {
2259
+ throw new Error(
2260
+ `session_capture_roles: unknown role "${role}" (expected a subset of ${SESSION_CAPTURE_ROLES.join(", ")})`,
2261
+ );
2262
+ }
2263
+ if (!roles.includes(role)) roles.push(role);
2264
+ }
2265
+ return roles.length > 0 ? roles : null;
2266
+ }
2267
+
2268
+ /**
2269
+ * Inbound Telegram capture bot token (Knowledge intake suite, t_f8f5ef6a).
2270
+ * Order: `TELEGRAM_BOT_TOKEN` env -> `telegram_bot_token` config -> null.
2271
+ * A value written as a `$secret:NAME` reference resolves through the passed
2272
+ * vault's custody store. The key contains "token", so `redactConfigMapping`
2273
+ * (src/core/egress) redacts it from any config snapshot. `null` (the
2274
+ * default) means the capture runner exits with a typed error rather than
2275
+ * starting; nothing runs without an explicit token.
2276
+ */
2277
+ export function resolveTelegramBotToken(configPath?: string, secretsVault?: string): string | null {
2278
+ const env = process.env["TELEGRAM_BOT_TOKEN"]?.trim();
2279
+ const raw = env || discoverConfig(configPath).data["telegram_bot_token"]?.trim();
2280
+ if (raw === undefined || raw.length === 0) return null;
2281
+ // A token written as a `$secret:NAME` reference resolves through the
2282
+ // vault's custody store (read-only); without the vault the value is
2283
+ // taken as-is, exactly as before the resolver routing existed.
2284
+ if (secretsVault !== undefined && isSecretReferenceValue(raw)) {
2285
+ return resolveThroughNamedSecretResolver(secretsVault, raw);
2286
+ }
2287
+ return raw;
2288
+ }
2289
+
2290
+ /**
2291
+ * Allowlisted Telegram chat ids for the capture bot (Knowledge intake
2292
+ * suite, t_f8f5ef6a). Order: `TELEGRAM_CHAT_ALLOWLIST` env ->
2293
+ * `telegram_chat_allowlist` config, comma-separated. Empty (the default)
2294
+ * accepts no chats - the allowlist is structural and must be explicit, so a
2295
+ * misconfigured bot captures nothing rather than everything.
2296
+ */
2297
+ export function resolveTelegramCaptureAllowlist(configPath?: string): string[] {
2298
+ const env = process.env["TELEGRAM_CHAT_ALLOWLIST"]?.trim();
2299
+ const raw = env || discoverConfig(configPath).data["telegram_chat_allowlist"]?.trim();
2300
+ if (!raw) return [];
2301
+ const ids: string[] = [];
2302
+ for (const part of raw.split(",")) {
2303
+ const id = part.trim();
2304
+ if (id.length > 0 && !ids.includes(id)) ids.push(id);
2305
+ }
2306
+ return ids;
2307
+ }
2308
+
2309
+ /**
2310
+ * Rewrite-gate mode for benchmark-gated skill rewrites (agent-presence,
2311
+ * Lane A). `gated` (the default) runs one candidate per gate round;
2312
+ * `iterative` is accepted and currently behaves exactly like `gated` -
2313
+ * one candidate per round - because the bounded edit loop it reserves is
2314
+ * not implemented yet; the value is carried so operators can opt in
2315
+ * without a config migration when the loop ships. The flat
2316
+ * machine-config key is `skill_rewrite.mode`; an unknown value is a named
2317
+ * error from the kernel's own resolver, never a silent fallback to the
2318
+ * default.
2319
+ */
2320
+ export const SKILL_REWRITE_MODE_CONFIG_KEY = "skill_rewrite.mode";
2321
+ export const SKILL_REWRITE_MODE_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_MODE";
2322
+
2323
+ /** Resolve the rewrite mode: env twin first, then the config file's flat key. */
2324
+ export function resolveSkillRewriteModeConfig(configPath?: string): SkillRewriteMode {
2325
+ const env = process.env[SKILL_REWRITE_MODE_ENV_KEY]?.trim();
2326
+ const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_MODE_CONFIG_KEY]?.trim();
2327
+ return resolveSkillRewriteMode(raw);
2328
+ }
2329
+
2330
+ /**
2331
+ * Optional advisory judge command for rewrite gate rounds (agent-presence,
2332
+ * Lane A). Same contract as `bench_judge_cmd` (t_882c396a): unset (the
2333
+ * default) means the judge phase is skipped, and when set the judge is
2334
+ * advisory only - it never moves the `tasks_passed_rate` metric the gate
2335
+ * decides on. The deterministic scorer stays canonical in every message.
2336
+ */
2337
+ export const SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY = "skill_rewrite_judge_cmd";
2338
+ export const SKILL_REWRITE_JUDGE_CMD_ENV_KEY = "OPEN_SECOND_BRAIN_SKILL_REWRITE_JUDGE_CMD";
2339
+
2340
+ /** Resolve the advisory rewrite judge: env twin first, then the config file. */
2341
+ export function resolveSkillRewriteJudgeCmd(configPath?: string): string | undefined {
2342
+ const env = process.env[SKILL_REWRITE_JUDGE_CMD_ENV_KEY]?.trim();
2343
+ const raw = env || discoverConfig(configPath).data[SKILL_REWRITE_JUDGE_CMD_CONFIG_KEY]?.trim();
2344
+ return raw !== undefined && raw !== "" ? raw : undefined;
2345
+ }
2346
+
2347
+ /**
2348
+ * `~` and `~/x` (and `~\x` on Windows) against `home`. The platform and
2349
+ * home default to the running process; the injected-environment resolvers
2350
+ * pass their own so a test for one platform does not read another's.
2351
+ */
2352
+ function expandTilde(
2353
+ p: string,
2354
+ platform: string = process.platform,
2355
+ home: string = homedir(),
2356
+ ): string {
2357
+ if (p === "~") return home;
2358
+ if (p.startsWith("~/")) return join(home, p.slice(2));
2359
+ // Windows users write `~\vault` as naturally as `~/vault`.
2360
+ if (platform === "win32" && p.startsWith("~\\")) return join(home, p.slice(2));
2361
+ return p;
2362
+ }