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,1755 @@
1
+ /**
2
+ * Open Knowledge Format (OKF) export / import round-trip
3
+ * (Brain Portability & Interop suite, Unit C).
4
+ *
5
+ * OKF is a portable, producer-agnostic *directory* bundle for knowledge
6
+ * interchange between wiki / second-brain systems. Where the bank bundle
7
+ * ({@link ./bundle.ts}) is a single JSON envelope tuned for OSB-to-OSB
8
+ * migration, an OKF bundle is a tree of plain markdown a foreign tool can
9
+ * read without knowing OSB internals:
10
+ *
11
+ * <bundle>/
12
+ * okf.json machine-readable manifest (schema, producer,
13
+ * per-page derived fields + preserved foreign
14
+ * provenance)
15
+ * index.md human-readable index, grouped by page class
16
+ * concepts/<slug>.md regular knowledge pages (the default class)
17
+ * queries/<slug>.md saved-question / research-report pages
18
+ * references/<slug>.md cited external-source pages
19
+ * log.md date-grouped change log (from Brain/log/)
20
+ *
21
+ * Page class is derived *structurally* from the frontmatter `kind:`
22
+ * field — never from natural-language heuristics — so the split is
23
+ * deterministic and language-agnostic. Each bundle page file carries the
24
+ * page's frontmatter and body **verbatim** plus the OKF v0.2 derived
25
+ * keys (`type`, `status`, `sources`, `generated` — recomputed on every
26
+ * export; `type` is the spec's one always-required per-concept key) and
27
+ * the `okf_raw` marker declaring the raw native keys riding beside
28
+ * them; the manifest carries the *derived* standard fields (kind,
29
+ * citations, status, sources, freshness) computed from current page
30
+ * state.
31
+ *
32
+ * Re-export honesty: when OSB imported a page from a *foreign* producer,
33
+ * the page keeps that producer's raw type value (`okf_type:`) and any
34
+ * producer-specific frontmatter (`x-*` keys) on disk. A later
35
+ * {@link buildOkfBundle} surfaces the raw foreign type as
36
+ * {@link OkfManifestPage.foreign_type} and the producer-specific keys as
37
+ * {@link OkfManifestPage.producer_meta} while still deriving the standard
38
+ * fields from the page's current state — foreign provenance is preserved,
39
+ * never overwritten or guessed.
40
+ *
41
+ * Import trust gradient: by default imported pages are *staged* under
42
+ * `OKF Review/` with `okf_review: pending` so nothing in the live vault is
43
+ * touched until an operator promotes them. `--trusted` writes each page
44
+ * directly to its recorded vault-relative path (a true round-trip).
45
+ *
46
+ * The bundle's self-declared `producer` is a LABEL, never a credential:
47
+ * any bundle can write `"producer": "open-second-brain"` into its
48
+ * manifest. It decides only provenance stamping. Every security decision
49
+ * - whether machinery frontmatter survives, whether the Brain page lanes
50
+ * are writable - keys on the operator's explicit `--trusted` instead.
51
+ */
52
+
53
+ import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
54
+ import { dirname, join, posix, relative, resolve } from "node:path";
55
+
56
+ import { atomicWriteFileSync } from "../../fs-atomic.ts";
57
+ import {
58
+ EXCLUDED_DIRS,
59
+ extractWikilinks,
60
+ formatFrontmatter,
61
+ parseFrontmatterText,
62
+ } from "../../vault.ts";
63
+ import type { FrontmatterMap, FrontmatterValue } from "../../types.ts";
64
+ import {
65
+ extractFrontmatterRelations,
66
+ normalizeRelationTarget,
67
+ } from "../../graph/frontmatter-relations.ts";
68
+ import { listLogShardFiles } from "../log-jsonl.ts";
69
+ import {
70
+ BRAIN_ROOT_REL,
71
+ BRAIN_SOURCES_REL,
72
+ BRAIN_REPORTS_REL,
73
+ ensureInsideVault,
74
+ isInBrainLane,
75
+ isUnderBrainRoot,
76
+ } from "../paths.ts";
77
+ import { isoSecond } from "../time.ts";
78
+ import { vaultDisplayName } from "../templates.ts";
79
+ import { ORIGIN_CHANNEL_FIELD, isOriginChannelStamp } from "../../origin-channel.ts";
80
+ import { contentClassCreationStamp } from "../provenance/content-class.ts";
81
+ import { KNOWLEDGE_PACK_FIELD, KNOWLEDGE_PACK_SHA_FIELD } from "./pack-stamp.ts";
82
+ import { OPEN_SECOND_BRAIN_VERSION } from "../../version.ts";
83
+ import {
84
+ assertLaneWrite,
85
+ laneEntryClockMs,
86
+ laneEntryInPrivate,
87
+ lanePageExists,
88
+ lanePagesInStore,
89
+ listLaneTree,
90
+ readLaneFile,
91
+ writeLanePage,
92
+ } from "../../store/lane-pages.ts";
93
+ import { assertNoteVaultForWrite } from "../../vault-adapter/index.ts";
94
+ import { groupLogDays, WHOLE_LOG } from "../log-days.ts";
95
+ import { readStoreLogEventsReport } from "../../store/read/log-events.ts";
96
+ import { protectionStore } from "../../store/read/protection-store.ts";
97
+ import { renderLogDayHeader, renderLogEntryBlock } from "../log.ts";
98
+ import { pageVisibility, REMOTE_DENY_VISIBILITY_TOKEN } from "../../graph/visibility.ts";
99
+
100
+ export const OKF_SCHEMA_VERSION = "1";
101
+ export const OKF_PRODUCER = "open-second-brain";
102
+
103
+ /**
104
+ * The OKF spec version this export emits, declared as
105
+ * `okf_version: "0.2"` in the bundle-root `index.md` frontmatter (a MAY
106
+ * per the spec, and the only frontmatter an index file may carry). This
107
+ * is the INTERCHANGE version, not the manifest dialect: Open Second
108
+ * Brain's own `okf.json` keeps its `schema: "1"` field beside it.
109
+ */
110
+ export const OKF_VERSION = "0.2";
111
+
112
+ /** The OKF v0.2 `generated.by` actor string for pages this system exports. */
113
+ const OKF_GENERATED_BY = `${OKF_PRODUCER}/${OPEN_SECOND_BRAIN_VERSION}`;
114
+
115
+ /**
116
+ * Bundle-relative filename of the machine-readable manifest. Named
117
+ * because three sites spelled it as a literal and a fourth - the export
118
+ * verb, which re-serialises this one file after redacting the manifest
119
+ * tree - would have made four.
120
+ */
121
+ export const OKF_MANIFEST_FILENAME = "okf.json";
122
+
123
+ /**
124
+ * Bundle-relative filename of the human-readable index. Named for the
125
+ * same reason as {@link OKF_MANIFEST_FILENAME}: the export verb
126
+ * re-renders this one file from the REDACTED manifest after the guard
127
+ * runs, and a reserved name spelled as a literal in a second module is
128
+ * a name that can drift away from the writer that reserves it.
129
+ */
130
+ export const OKF_INDEX_FILENAME = "index.md";
131
+
132
+ /** Vault-relative root the default (untrusted) import stages pages under. */
133
+ export const OKF_REVIEW_REL = "OKF Review";
134
+
135
+ /** OKF page classes and the bundle subdirectory each maps to. */
136
+ export type OkfPageClass = "concept" | "query" | "reference";
137
+
138
+ const CLASS_DIR: Readonly<Record<OkfPageClass, string>> = {
139
+ concept: "concepts",
140
+ query: "queries",
141
+ reference: "references",
142
+ };
143
+
144
+ /** `kind:` values that route a page to `queries/`. */
145
+ const QUERY_KINDS: ReadonlySet<string> = new Set(["query", "brain-report", "report"]);
146
+ /** `kind:` values that route a page to `references/`. */
147
+ const REFERENCE_KINDS: ReadonlySet<string> = new Set(["reference", "brain-source", "source"]);
148
+
149
+ /** Structural default `kind` for a page with no frontmatter `kind:`. */
150
+ const DEFAULT_KIND = "note";
151
+
152
+ /** Frontmatter key prefix marking producer-specific (foreign) fields. */
153
+ const PRODUCER_META_PREFIX = "x-";
154
+ /** Frontmatter key carrying a foreign producer's raw type value. */
155
+ const FOREIGN_TYPE_KEY = "okf_type";
156
+ /** Frontmatter key carrying the producer that authored an imported page. */
157
+ const PRODUCER_KEY = "okf_producer";
158
+ /** Frontmatter key stamping the import timestamp. */
159
+ const IMPORTED_AT_KEY = "okf_imported_at";
160
+ /** Frontmatter key marking a staged (un-promoted) review candidate. */
161
+ const REVIEW_KEY = "okf_review";
162
+
163
+ /**
164
+ * Frontmatter keys carrying a page's NATIVE `status` / `sources` /
165
+ * `generated` / `type` values beside the derived v0.2 block. The v0.2
166
+ * status enum is closed (`draft | stable | deprecated`) and the derived
167
+ * sources are re-translated from citations, so exporting the native
168
+ * values in place would silently rewrite them: a quarantined page would
169
+ * export as `stable` and un-quarantine on import, workflow statuses like
170
+ * `done` or `active` would be lost, and user-written source lists would
171
+ * be replaced. The same holds for `type`, the spec's one always-required
172
+ * per-concept key: the export emits it DERIVED (the preserved foreign
173
+ * type, else the structural kind), so a native `type` the operator wrote
174
+ * rides the raw namespace instead of being shadowed by the projection.
175
+ * The raw keys ride the same `okf_` producer namespace as
176
+ * {@link FOREIGN_TYPE_KEY} / {@link PRODUCER_KEY}; an own-producer
177
+ * import restores them and drops the derived block (see
178
+ * {@link restoreRawOkfKeys}) - trusted round-trip and review staging
179
+ * alike - while foreign bundles import as-is and shed the keys.
180
+ */
181
+ const RAW_STATUS_KEY = "okf_status_raw";
182
+ const RAW_SOURCES_KEY = "okf_sources_raw";
183
+ const RAW_GENERATED_KEY = "okf_generated_raw";
184
+ const RAW_TYPE_KEY = "okf_type_raw";
185
+
186
+ /**
187
+ * The raw/native key pairs the producer namespace carries beside the
188
+ * derived v0.2 block, in one list: `raw` is the exported carrier,
189
+ * `native` the frontmatter field it preserves. The export's carry and
190
+ * strip, the foreign shed and the import restore all walk THIS, so the
191
+ * set cannot drift between the sites that must agree on it.
192
+ */
193
+ const RAW_OKF_KEYS: ReadonlyArray<{ readonly raw: string; readonly native: string }> =
194
+ Object.freeze([
195
+ { raw: RAW_STATUS_KEY, native: "status" },
196
+ { raw: RAW_SOURCES_KEY, native: "sources" },
197
+ { raw: RAW_GENERATED_KEY, native: "generated" },
198
+ { raw: RAW_TYPE_KEY, native: "type" },
199
+ ]);
200
+
201
+ /**
202
+ * The per-page marker that says "this bundle page was written by a
203
+ * raw-carrying exporter", stamped on EVERY page of a fresh export
204
+ * beside the derived block - raw keys or not. It is what lets the
205
+ * import distinguish a page the current exporter wrote with no native
206
+ * status / sources / generated (absent raw keys mean "the field never
207
+ * had a value": strip the derived block, the page lands plain) from a
208
+ * LEGACY bundle's page (no marker: the frontmatter already is the
209
+ * native state, leave it as-is). Without the marker, a fresh-export
210
+ * plain page took the legacy early-return and landed WITH the derived
211
+ * block - `status: stable` materializing where none existed - and the
212
+ * next export carried the materialized status as a raw native,
213
+ * permanent.
214
+ *
215
+ * The marker IS its coverage: the exporter stamps the list of native
216
+ * names it manages, and the restore drops a derived value only for a
217
+ * pair the marker declares (see {@link rawCarryDeclaredNatives}). A
218
+ * bare `true` is what the pre-list exporters stamped, so it reads as
219
+ * the legacy shape and covers only the old status/sources/generated
220
+ * set - never `type`, whose pair did not exist yet when those exports
221
+ * carried a native type verbatim beside the marker.
222
+ */
223
+ const RAW_CARRY_KEY = "okf_raw";
224
+
225
+ /**
226
+ * The native fields a bare {@link RAW_CARRY_KEY} `true` covers: the
227
+ * three the exporters that stamped the bare shape managed. The `type`
228
+ * pair did not exist yet in those exports - a native `type` rode the
229
+ * page verbatim beside the marker - so `true` must never name it, or
230
+ * the restore would read a legacy page's absent `okf_type_raw` as "the
231
+ * field never had a value" and delete the real type.
232
+ */
233
+ const RAW_CARRY_TRUE_NATIVES: ReadonlySet<string> = new Set(["status", "sources", "generated"]);
234
+
235
+ const FRESHNESS_FIELDS = ["updated_at", "updated"] as const;
236
+
237
+ // ----- Export ---------------------------------------------------------------
238
+
239
+ /**
240
+ * The OKF v0.2 concept lifecycle enum - the spec's CLOSED status
241
+ * vocabulary (`draft | stable | deprecated`; an absent status means
242
+ * stable). Open Second Brain's own page statuses land on it through the
243
+ * conservative map in {@link okfStatusOf}.
244
+ */
245
+ export type OkfStatus = "draft" | "stable" | "deprecated";
246
+
247
+ /** One OKF v0.2 per-page source (a frontmatter `sources:` entry). */
248
+ export interface OkfSource {
249
+ /**
250
+ * REQUIRED per the spec: a path or URL identifying the source. A
251
+ * citation that resolves to neither is dropped rather than guessed.
252
+ */
253
+ readonly resource: string;
254
+ /**
255
+ * Optional stable key. Carried when the citation resolves to a bundle
256
+ * page, whose id is that stable key.
257
+ */
258
+ readonly id?: string;
259
+ }
260
+
261
+ /** A page collected for OKF export, with derived + preserved metadata. */
262
+ export interface OkfPage {
263
+ /** Stable id (the file basename stem). */
264
+ readonly id: string;
265
+ /** Original vault-relative POSIX path. */
266
+ readonly path: string;
267
+ /** Derived OKF class (`concept` | `query` | `reference`). */
268
+ readonly cls: OkfPageClass;
269
+ /** Path within the bundle (`concepts/<slug>.md`, …). */
270
+ readonly bundle_path: string;
271
+ /** Derived standard kind (current frontmatter `kind:` else `note`). */
272
+ readonly kind: string;
273
+ /** Sorted-unique body wikilink + typed-relation targets. */
274
+ readonly citations: ReadonlyArray<string>;
275
+ /** Mapped OKF v0.2 lifecycle (`draft` | `stable` | `deprecated`). */
276
+ readonly status: OkfStatus;
277
+ /** Frontmatter `aliases`, else empty. */
278
+ readonly aliases: ReadonlyArray<string>;
279
+ /** Frontmatter `updated_at`/`updated`, else file mtime (ISO second). */
280
+ readonly freshness: string | null;
281
+ /** Preserved raw foreign type (`okf_type:`), else null. */
282
+ readonly foreign_type: string | null;
283
+ /** Preserved producer-specific frontmatter (`x-*` keys). */
284
+ readonly producer_meta: Readonly<Record<string, string>>;
285
+ /** Verbatim frontmatter of the page. */
286
+ readonly frontmatter: FrontmatterMap;
287
+ /** Verbatim markdown body of the page. */
288
+ readonly body: string;
289
+ }
290
+
291
+ export interface OkfManifestPage {
292
+ readonly id: string;
293
+ readonly path: string;
294
+ readonly class: OkfPageClass;
295
+ readonly bundle_path: string;
296
+ readonly kind: string;
297
+ readonly citations: ReadonlyArray<string>;
298
+ /** Mapped OKF v0.2 lifecycle (`draft` | `stable` | `deprecated`). */
299
+ readonly status: OkfStatus;
300
+ /** OKF v0.2 per-page sources translated from `citations`. */
301
+ readonly sources: ReadonlyArray<OkfSource>;
302
+ readonly aliases: ReadonlyArray<string>;
303
+ readonly freshness: string | null;
304
+ readonly foreign_type: string | null;
305
+ readonly producer_meta: Readonly<Record<string, string>>;
306
+ }
307
+
308
+ export interface OkfManifest {
309
+ readonly schema: string;
310
+ readonly producer: string;
311
+ readonly generated_at: string;
312
+ readonly vault_basename: string;
313
+ readonly pages: ReadonlyArray<OkfManifestPage>;
314
+ /**
315
+ * Count of DAYS folded into `log.md`, across every markdown shard of
316
+ * `Brain/log/` - `<date>.md` and `<date>.<deviceId>.md` alike. Two
317
+ * shards of one day are one day here, not two.
318
+ */
319
+ readonly log_days: number;
320
+ /**
321
+ * Log events the export left out of `log.md` for being private, counted
322
+ * before any content-class filtering. Zero on the legacy layout and for
323
+ * a machine that holds no `private` partition.
324
+ */
325
+ readonly log_private_omitted: number;
326
+ }
327
+
328
+ /** A single file in the in-memory bundle write-plan. */
329
+ export interface OkfBundleFile {
330
+ /** Bundle-relative POSIX path. */
331
+ readonly path: string;
332
+ readonly contents: string;
333
+ }
334
+
335
+ export interface OkfBundle {
336
+ readonly manifest: OkfManifest;
337
+ /** Every file to write, including `okf.json`, sorted by path. */
338
+ readonly files: ReadonlyArray<OkfBundleFile>;
339
+ }
340
+
341
+ function stringField(meta: FrontmatterMap, key: string): string | null {
342
+ const value: FrontmatterValue | undefined = meta[key];
343
+ return typeof value === "string" && value.length > 0 ? value : null;
344
+ }
345
+
346
+ function aliasField(meta: FrontmatterMap): ReadonlyArray<string> {
347
+ const value: FrontmatterValue | undefined = meta["aliases"];
348
+ if (!Array.isArray(value)) return [];
349
+ return value.filter((item): item is string => typeof item === "string");
350
+ }
351
+
352
+ function classifyKind(kind: string): OkfPageClass {
353
+ if (REFERENCE_KINDS.has(kind)) return "reference";
354
+ if (QUERY_KINDS.has(kind)) return "query";
355
+ return "concept";
356
+ }
357
+
358
+ function collectCitations(meta: FrontmatterMap, body: string): string[] {
359
+ const targets: string[] = [];
360
+ for (const raw of extractWikilinks(body)) {
361
+ const norm = normalizeRelationTarget(raw);
362
+ if (norm !== null) targets.push(norm);
363
+ }
364
+ for (const edge of extractFrontmatterRelations(meta)) targets.push(edge.target);
365
+ return [...new Set(targets.filter((v) => v.length > 0))].toSorted();
366
+ }
367
+
368
+ /**
369
+ * Frontmatter `status:` values that mean "no longer current" and map to
370
+ * the OKF `deprecated` value. Deliberately NARROW: the OKF enum has no
371
+ * room for nuance, and a conservative producer prefers understating.
372
+ */
373
+ const OKF_DEPRECATED_STATUSES: ReadonlySet<string> = new Set([
374
+ "deprecated",
375
+ "retired",
376
+ "superseded",
377
+ "archived",
378
+ "terminal",
379
+ ]);
380
+
381
+ /**
382
+ * Map a page onto the OKF v0.2 concept lifecycle, which admits ONLY
383
+ * `draft | stable | deprecated`.
384
+ *
385
+ * PINNED SOURCE FIELD: the page's frontmatter `status:` value - the
386
+ * operator-declared page state - and nothing else. The system-managed
387
+ * `_lifecycle` axis is not consulted: its `verified`/`disputed` values
388
+ * have no OKF counterpart, and a conservative map must not guess one.
389
+ * Completion states (`done` / `closed` / `resolved`) map to `stable` -
390
+ * completion is not deprecation, never the reverse - and a status the
391
+ * vocabulary does not name (including no status at all) lands on
392
+ * `stable`, which is also the OKF default for an absent status.
393
+ */
394
+ function okfStatusOf(meta: FrontmatterMap): OkfStatus {
395
+ const raw = stringField(meta, "status");
396
+ if (raw === null) return "stable";
397
+ const status = raw.trim().toLowerCase();
398
+ if (status === "draft") return "draft";
399
+ if (OKF_DEPRECATED_STATUSES.has(status)) return "deprecated";
400
+ return "stable";
401
+ }
402
+
403
+ function freshnessOf(vault: string, meta: FrontmatterMap, absPath: string): string | null {
404
+ for (const field of FRESHNESS_FIELDS) {
405
+ const stamp = stringField(meta, field);
406
+ if (stamp !== null) return stamp;
407
+ }
408
+ // A file's mtime, or a lane record's clock on a store-only machine.
409
+ const ms = laneEntryClockMs(vault, absPath);
410
+ return ms === null ? null : isoSecond(new Date(ms));
411
+ }
412
+
413
+ function producerMeta(meta: FrontmatterMap): Record<string, string> {
414
+ const out: Record<string, string> = {};
415
+ for (const [key, value] of Object.entries(meta)) {
416
+ if (key.startsWith(PRODUCER_META_PREFIX)) out[key] = String(value);
417
+ }
418
+ return out;
419
+ }
420
+
421
+ /** POSIX vault-relative path for an absolute file under the vault. */
422
+ function vaultRel(vault: string, abs: string): string {
423
+ return relative(vault, abs).split(/[\\/]/).join(posix.sep);
424
+ }
425
+
426
+ /** Basename stem of a POSIX-or-native path (drops one trailing extension). */
427
+ function stem(p: string): string {
428
+ const base = p.split(/[\\/]/).pop() ?? p;
429
+ const dot = base.lastIndexOf(".");
430
+ return dot > 0 ? base.slice(0, dot) : base;
431
+ }
432
+
433
+ /**
434
+ * Walk the vault and collect every exportable page. Three sources feed
435
+ * the bundle: ordinary user pages (everything outside `Brain/`), the
436
+ * ingested source pages under `Brain/sources/` (references), and the
437
+ * research-report pages under `Brain/reports/` (queries). All other
438
+ * Brain machinery (preferences, inbox, entities, log, …) is excluded —
439
+ * the log feeds `log.md` separately, the rest is not knowledge content.
440
+ */
441
+ export function collectOkfPages(vault: string): ReadonlyArray<OkfPage> {
442
+ const seenBundlePaths = new Set<string>();
443
+ const out: OkfPage[] = [];
444
+
445
+ const consider = (abs: string, forceClass?: OkfPageClass): void => {
446
+ let raw: string;
447
+ try {
448
+ raw = readLaneFile(vault, abs);
449
+ } catch {
450
+ return;
451
+ }
452
+ const [parsed, body] = parseFrontmatterText(raw);
453
+ const meta = privateStamped(vault, abs, parsed);
454
+ const kind = stringField(meta, "kind") ?? DEFAULT_KIND;
455
+ const cls = forceClass ?? classifyKind(kind);
456
+ const path = vaultRel(vault, abs);
457
+ const id = stem(path);
458
+ // De-duplicate within the bundle's class subdir; suffix on collision.
459
+ let slug = id;
460
+ let bundlePath = posix.join(CLASS_DIR[cls], `${slug}.md`);
461
+ for (let n = 2; seenBundlePaths.has(bundlePath); n++) {
462
+ slug = `${id}-${n}`;
463
+ bundlePath = posix.join(CLASS_DIR[cls], `${slug}.md`);
464
+ }
465
+ seenBundlePaths.add(bundlePath);
466
+ out.push({
467
+ id,
468
+ path,
469
+ cls,
470
+ bundle_path: bundlePath,
471
+ kind,
472
+ citations: collectCitations(meta, body),
473
+ status: okfStatusOf(meta),
474
+ aliases: aliasField(meta),
475
+ freshness: freshnessOf(vault, meta, abs),
476
+ foreign_type: stringField(meta, FOREIGN_TYPE_KEY),
477
+ producer_meta: producerMeta(meta),
478
+ frontmatter: meta,
479
+ body,
480
+ });
481
+ };
482
+
483
+ // 1. User pages (outside Brain). listing is sorted by path below.
484
+ for (const abs of listMarkdown(vault, [...EXCLUDED_DIRS, BRAIN_ROOT_REL])) consider(abs);
485
+ // 2. References: Brain/sources/*.md (lane records once switched).
486
+ for (const abs of laneMarkdown(vault, join(vault, BRAIN_SOURCES_REL))) consider(abs, "reference");
487
+ // 3. Queries: Brain/reports/*.md (lane records once switched).
488
+ for (const abs of laneMarkdown(vault, join(vault, BRAIN_REPORTS_REL))) consider(abs, "query");
489
+
490
+ out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
491
+ return out;
492
+ }
493
+
494
+ /**
495
+ * A page read from a lane entry of the `private` partition carries the
496
+ * remote-deny token in the bundle (review finding F333). Such an entry can
497
+ * be private by partition alone, with no `visibility:` of its own, and
498
+ * would otherwise land in another vault as an ordinary shared page. The
499
+ * token is added to the tokens the page already declares, never in place
500
+ * of them.
501
+ */
502
+ function privateStamped(vault: string, abs: string, meta: FrontmatterMap): FrontmatterMap {
503
+ if (!laneEntryInPrivate(vault, abs)) return meta;
504
+ const tokens = pageVisibility(meta);
505
+ if (tokens.includes(REMOTE_DENY_VISIBILITY_TOKEN)) return meta;
506
+ return { ...meta, visibility: [...tokens, REMOTE_DENY_VISIBILITY_TOKEN] };
507
+ }
508
+
509
+ /** The `.md` pages under a `Brain/` lane folder, in both modes. */
510
+ function laneMarkdown(vault: string, root: string): string[] {
511
+ return lanePagesInStore(vault) ? listLaneTree(vault, root) : listMarkdown(root, []);
512
+ }
513
+
514
+ /** Recursively list `.md` files under `root`, skipping `skipDirs` names. */
515
+ function listMarkdown(root: string, skipDirs: ReadonlyArray<string>): string[] {
516
+ const skip = new Set(skipDirs);
517
+ const found: string[] = [];
518
+ const walk = (dir: string): void => {
519
+ let entries;
520
+ try {
521
+ entries = readdirSync(dir, { withFileTypes: true });
522
+ } catch {
523
+ return;
524
+ }
525
+ for (const entry of entries) {
526
+ if (entry.isDirectory()) {
527
+ if (skip.has(entry.name) || entry.name.startsWith(".")) continue;
528
+ walk(join(dir, entry.name));
529
+ continue;
530
+ }
531
+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
532
+ found.push(join(dir, entry.name));
533
+ }
534
+ }
535
+ };
536
+ walk(root);
537
+ found.sort();
538
+ return found;
539
+ }
540
+
541
+ /**
542
+ * Read and date-group the markdown side of `Brain/log/` into one change
543
+ * log.
544
+ *
545
+ * Days come from {@link listLogShardFiles}, the recogniser in the module
546
+ * that owns the log layout, rather than from a pattern of this module's
547
+ * own. The local pattern here matched `<date>.md` only, while every
548
+ * default install has written the per-device `<date>.<deviceId>.md` since
549
+ * sharding landed - so a vault with a full change log exported an empty
550
+ * `log.md` and a manifest reading `0 log day(s)`, with nothing to
551
+ * distinguish that from a vault that had never logged anything.
552
+ *
553
+ * Shards of one day fold into ONE dated section, ordered by shard id
554
+ * (`listLogShardFiles` sorts by name), so the bundle is byte-identical
555
+ * whatever order Syncthing delivered the shards in.
556
+ *
557
+ * ## The content-class filter
558
+ *
559
+ * With a {@link OkfLogFilter} the log is NOT whole: the shards hold
560
+ * agent-written material, and a default export that carried it would
561
+ * undo, page by page, the omission the class policy just performed. Two
562
+ * kinds of entry leave, and each drop is counted into the returned
563
+ * `droppedEntries` so the calling verb can name the count:
564
+ *
565
+ * 1. an entry whose `origin_channel` bullet carries the channel
566
+ * {@link contentClassCreationStamp} derives the reserved class from -
567
+ * an entry the MCP transport appended is agent-dictated material. A
568
+ * log entry carries no `content_class` of its own, so the server-
569
+ * derived channel it is stamped with is the one provable marker it
570
+ * can carry; a channel this build does not know marks nothing.
571
+ * 2. an entry whose `target` bullet names a page in the filter's omitted
572
+ * set - the entry would disclose the very name the split withheld.
573
+ *
574
+ * Kept entries are preserved BYTE-EXACTLY: the shard is split at the
575
+ * event-block boundaries the log parser itself reads (`## ` headings),
576
+ * and only the dropped spans are removed - no reformatting, no
577
+ * re-serialisation of what stays. A shard whose every entry is dropped
578
+ * contributes nothing, and a day left with no contributing shard stops
579
+ * counting as a log day. Without a filter - and under
580
+ * `includePromptDerived` - each shard rides whole, exactly as before.
581
+ */
582
+ export interface OkfLogFilter {
583
+ /**
584
+ * The operator override: when true the log rides whole, the same
585
+ * decision `--include-prompt-derived` makes for pages.
586
+ */
587
+ readonly includePromptDerived: boolean;
588
+ /** The vault-relative paths the page split left out of the bundle. */
589
+ readonly omittedPaths: ReadonlySet<string>;
590
+ }
591
+
592
+ export interface OkfLog {
593
+ /** The date-grouped change log, ready for the `log.md` bundle file. */
594
+ readonly contents: string;
595
+ /** Count of DAYS with at least one kept entry, across every shard. */
596
+ readonly days: number;
597
+ /** Entries the content-class filter dropped; zero without a filter. */
598
+ readonly droppedEntries: number;
599
+ /**
600
+ * Log events the store held in its `private` partition, left out of
601
+ * `log.md` and counted before any content-class filtering; zero on the
602
+ * legacy layout.
603
+ */
604
+ readonly privateEntries: number;
605
+ }
606
+
607
+ /**
608
+ * One top-level log bullet, in the shape the log parser itself reads
609
+ * (`- key: value`). Spelled locally because the parser does not export
610
+ * it and this module reads no other log syntax.
611
+ */
612
+ const LOG_BULLET_RE = /^-\s+([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/;
613
+
614
+ export function buildLog(vault: string, filter?: OkfLogFilter): OkfLog {
615
+ const bodiesByDate = new Map<string, string[]>();
616
+ let droppedEntries = 0;
617
+ // One read of the store log, counted by partition: a private event never
618
+ // reaches `log.md` (review finding F333), and the export refuses when a
619
+ // log shard cannot be read, so the bundle is never silently short of
620
+ // events and the private count is never a lower bound.
621
+ const report = readStoreLogEventsReport(WHOLE_LOG, { vault });
622
+ // A store-only machine whose store cannot be opened reads no events and
623
+ // no unreadable shard: refuse as a protection reader does, switched or
624
+ // not, rather than export an empty log that claims nothing private was
625
+ // left out.
626
+ if (report !== null) protectionStore(undefined, { openErrorFails: true, vault });
627
+ if (report !== null && report.unreadable.length > 0) {
628
+ throw new Error(
629
+ `okf export: cannot read log shard(s) ${report.unreadable.join(", ")}; the bundle would be short of their events`,
630
+ );
631
+ }
632
+ // Counted before the content-class filter: the partition rule and the
633
+ // class policy are independent, so the two counts never overlap.
634
+ const privateEntries = report?.events.filter((e) => e.partition === "private").length ?? 0;
635
+ // A store-only machine keeps no day files: the days of the shared events
636
+ // are rendered the way the day file renders it (header, then one block
637
+ // per entry), so the bundle's `log.md` reads the same.
638
+ const storedDays =
639
+ report === null
640
+ ? null
641
+ : groupLogDays(report.events.filter((e) => e.partition === "shared").map((e) => e.entry));
642
+ for (const day of storedDays ?? []) {
643
+ const body = [renderLogDayHeader(day.date), ...day.entries.map(renderLogEntryBlock)]
644
+ .join("\n")
645
+ .trimEnd();
646
+ const text =
647
+ filter === undefined || filter.includePromptDerived
648
+ ? body
649
+ : filterLogShard(body, filter, (dropped) => {
650
+ droppedEntries += dropped;
651
+ });
652
+ if (text.length > 0) bodiesByDate.set(day.date, [text]);
653
+ }
654
+ for (const shard of storedDays === null ? listLogShardFiles(vault) : []) {
655
+ // The bundle is markdown; the JSONL sidecar of a day carries the same
656
+ // entries in machine form and would duplicate every line.
657
+ if (shard.ext !== "md") continue;
658
+ let body: string;
659
+ try {
660
+ body = readFileSync(shard.path, "utf8").trimEnd();
661
+ } catch (err) {
662
+ // Never `continue`: a shard the export could not read is a day of
663
+ // the change log missing from the bundle, and a bundle that is
664
+ // silently short a day is exactly what this export must not produce.
665
+ throw new Error(
666
+ `okf export: cannot read log shard ${shard.name}: ${err instanceof Error ? err.message : String(err)}`,
667
+ );
668
+ }
669
+ if (body.length === 0) continue;
670
+ const text =
671
+ filter === undefined || filter.includePromptDerived
672
+ ? body
673
+ : filterLogShard(body, filter, (dropped) => {
674
+ droppedEntries += dropped;
675
+ });
676
+ if (text.length === 0) continue;
677
+ const bodies = bodiesByDate.get(shard.date);
678
+ if (bodies === undefined) bodiesByDate.set(shard.date, [text]);
679
+ else bodies.push(text);
680
+ }
681
+ const sections = [...bodiesByDate.keys()]
682
+ .toSorted()
683
+ .map((date) => `## ${date}\n\n${bodiesByDate.get(date)!.join("\n\n")}`);
684
+ return {
685
+ contents: sections.join("\n\n"),
686
+ days: bodiesByDate.size,
687
+ droppedEntries,
688
+ privateEntries,
689
+ };
690
+ }
691
+
692
+ /**
693
+ * Drop the filtered entries from one shard's text, keeping every other
694
+ * byte where it was. The shard is split at the `## ` event-heading
695
+ * boundaries the log parser reads; the text before the first heading is
696
+ * the shard's own frontmatter and title and always stays, and each
697
+ * entry's span runs to the next heading, so removing an entry removes
698
+ * exactly its lines and nothing else. Splitting on `\n` and rejoining on
699
+ * `\n` keeps a hand-edited CRLF shard's kept bytes untouched.
700
+ */
701
+ function filterLogShard(
702
+ body: string,
703
+ filter: OkfLogFilter,
704
+ recordDrop: (dropped: number) => void,
705
+ ): string {
706
+ const lines = body.split("\n");
707
+ let firstBlock = -1;
708
+ for (let i = 0; i < lines.length; i++) {
709
+ if (lines[i]!.startsWith("## ")) {
710
+ firstBlock = i;
711
+ break;
712
+ }
713
+ }
714
+ // No event headings: no entry can be provably marked, so the shard
715
+ // stays whole rather than being guessed about.
716
+ if (firstBlock < 0) return body;
717
+ const starts: number[] = [];
718
+ for (let i = firstBlock; i < lines.length; i++) {
719
+ if (lines[i]!.startsWith("## ")) starts.push(i);
720
+ }
721
+ const prologue = lines.slice(0, firstBlock).join("\n");
722
+ const kept: string[] = [];
723
+ for (let n = 0; n < starts.length; n++) {
724
+ const end = n + 1 < starts.length ? starts[n + 1]! : lines.length;
725
+ if (!logEntryIsFilteredOut(lines.slice(starts[n]!, end), filter)) {
726
+ kept.push(lines.slice(starts[n]!, end).join("\n"));
727
+ } else {
728
+ recordDrop(1);
729
+ }
730
+ }
731
+ // Every entry dropped: the shard has nothing left to say, and a bare
732
+ // frontmatter-plus-title shell would count as a log day that logs
733
+ // nothing.
734
+ if (kept.length === 0) return "";
735
+ return `${prologue}${kept.join("")}`.trimEnd();
736
+ }
737
+
738
+ /**
739
+ * Whether one event block leaves under the filter. The block's top-level
740
+ * bullets are read the way the log parser reads them (`- key: value`,
741
+ * later occurrences of a key winning), and the decision is fail-open: an
742
+ * entry that carries neither a known channel nor an omitted target stays.
743
+ */
744
+ function logEntryIsFilteredOut(blockLines: ReadonlyArray<string>, filter: OkfLogFilter): boolean {
745
+ const bullets = new Map<string, string>();
746
+ for (const line of blockLines) {
747
+ const bullet = LOG_BULLET_RE.exec(line);
748
+ if (bullet !== null) bullets.set(bullet[1]!, bullet[2]!);
749
+ }
750
+ // The channel the creation stamp derives the reserved class from: an
751
+ // entry appended over the MCP transport is agent-dictated material,
752
+ // exactly as a page created there is. A bullet naming a channel this
753
+ // build does not know marks nothing.
754
+ const channel = bullets.get(ORIGIN_CHANNEL_FIELD);
755
+ if (
756
+ typeof channel === "string" &&
757
+ isOriginChannelStamp(channel) &&
758
+ contentClassCreationStamp(channel) !== null
759
+ ) {
760
+ return true;
761
+ }
762
+ // A write entry whose target is the page the split left out would name
763
+ // the omission right back into the bundle.
764
+ const target = bullets.get("target");
765
+ return typeof target === "string" && filter.omittedPaths.has(target);
766
+ }
767
+
768
+ /**
769
+ * Render the bundle-root `index.md` from a manifest. Exported because
770
+ * the export verb re-renders the index from the REDACTED manifest after
771
+ * the guard runs - an index naming a value the shipped `okf.json` no
772
+ * longer carries (a redacted foreign type, an omitted page) would make
773
+ * the bundle disagree with itself in the file a human reads first.
774
+ */
775
+ export function renderIndex(manifest: OkfManifest): string {
776
+ const lines: string[] = [
777
+ "---",
778
+ // OKF v0.2's version declaration. Per the spec it is a MAY in the
779
+ // bundle-root index, and the ONLY frontmatter an index file carries.
780
+ `okf_version: "${OKF_VERSION}"`,
781
+ "---",
782
+ "",
783
+ `# ${manifest.vault_basename} — Open Knowledge Format bundle`,
784
+ "",
785
+ `> Portable knowledge bundle produced by \`${manifest.producer}\`.`,
786
+ `> Schema ${manifest.schema}. ${manifest.pages.length} page(s),`,
787
+ `> ${manifest.log_days} log day(s). See \`okf.json\` for machine-readable`,
788
+ `> metadata and \`log.md\` for the change log.`,
789
+ "",
790
+ ];
791
+ const order: ReadonlyArray<[OkfPageClass, string]> = [
792
+ ["concept", "Concepts"],
793
+ ["query", "Queries"],
794
+ ["reference", "References"],
795
+ ];
796
+ for (const [cls, label] of order) {
797
+ const subset = manifest.pages.filter((p) => p.class === cls);
798
+ if (subset.length === 0) continue;
799
+ lines.push(`## ${label}`, "");
800
+ for (const p of subset) {
801
+ const foreign = p.foreign_type ? ` (foreign type: ${p.foreign_type})` : "";
802
+ lines.push(`- [${p.id}](${p.bundle_path}) — \`${p.path}\`${foreign}`);
803
+ }
804
+ lines.push("");
805
+ }
806
+ return lines.join("\n");
807
+ }
808
+
809
+ /**
810
+ * Serialise a manifest to the exact bytes `okf.json` carries. Exported
811
+ * because the export verb redacts the manifest as a TREE - a pass over
812
+ * serialised JSON can eat a closing quote - and then has to re-render
813
+ * this one file from the redacted result.
814
+ */
815
+ export function renderOkfManifest(manifest: OkfManifest): string {
816
+ return JSON.stringify(manifest, null, 2) + "\n";
817
+ }
818
+
819
+ /** A citation target that names an absolute resource, not a vault page. */
820
+ const URL_TARGET_RE = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
821
+
822
+ /**
823
+ * Build the resolver that turns citation targets into OKF v0.2
824
+ * `sources:` entries. It keys on the page walk's own bundle_path
825
+ * assignment, so a resolved source names exactly the file the bundle
826
+ * wrote for the cited page. Resolution order:
827
+ *
828
+ * 1. a URL target is carried as-is;
829
+ * 2. a path-shaped target must name a collected page (with or without
830
+ * the `.md` suffix) - otherwise it is dropped, never guessed. The
831
+ * entry carries the page's id only when that stem is unique; a
832
+ * colliding basename has no stable id to name;
833
+ * 3. a bare basename resolves only when EXACTLY ONE page carries that
834
+ * stem: the colliding-basename case (two `Dup.md` pages) is dropped
835
+ * rather than guessed.
836
+ *
837
+ * Anything else is dangling and dropped - consumers must tolerate
838
+ * broken links, and a wrong source is worse than no source.
839
+ */
840
+ function sourceResolver(pages: ReadonlyArray<OkfPage>): (citation: string) => OkfSource | null {
841
+ const byPath = new Map<string, OkfPage>();
842
+ const byStem = new Map<string, OkfPage[]>();
843
+ for (const p of pages) {
844
+ byPath.set(p.path, p);
845
+ const stems = byStem.get(p.id);
846
+ if (stems === undefined) byStem.set(p.id, [p]);
847
+ else stems.push(p);
848
+ }
849
+ return (citation: string): OkfSource | null => {
850
+ if (URL_TARGET_RE.test(citation)) return { resource: citation };
851
+ if (citation.includes("/")) {
852
+ const direct = byPath.get(citation) ?? byPath.get(`${citation}.md`);
853
+ if (direct === undefined) return null;
854
+ // The path resolves the page, but its stem names an id only when it
855
+ // is unique: two colliding basenames are both id "Dup", and the id
856
+ // field is a stable key. The entry carries the bundle path alone -
857
+ // same refuse-to-guess rule as the basename branch.
858
+ const stems = byStem.get(direct.id);
859
+ if (stems !== undefined && stems.length > 1) return { resource: direct.bundle_path };
860
+ return { resource: direct.bundle_path, id: direct.id };
861
+ }
862
+ // The stem map keys on stems, but a citation may keep its extension
863
+ // (`[[Dup.md]]` names the same page `[[Dup]]` does), so a direct miss
864
+ // falls back to stem(citation). Exact-unique either way: the
865
+ // colliding-basename case still drops rather than guess.
866
+ const stems = byStem.get(citation) ?? byStem.get(stem(citation));
867
+ if (stems === undefined || stems.length !== 1) return null;
868
+ return { resource: stems[0]!.bundle_path, id: stems[0]!.id };
869
+ };
870
+ }
871
+
872
+ /** Translate a page's citations into de-duplicated source entries. */
873
+ function translateSources(
874
+ page: OkfPage,
875
+ resolveSource: (citation: string) => OkfSource | null,
876
+ ): OkfSource[] {
877
+ const out: OkfSource[] = [];
878
+ const seen = new Set<string>();
879
+ for (const citation of page.citations) {
880
+ const source = resolveSource(citation);
881
+ if (source === null || seen.has(source.resource)) continue;
882
+ seen.add(source.resource);
883
+ out.push(source);
884
+ }
885
+ return out;
886
+ }
887
+
888
+ /**
889
+ * Render one scalar inside a YAML flow mapping (`{resource: …, id: …}`).
890
+ * EVERY value is emitted as a JSON string literal: JSON string syntax is
891
+ * valid YAML double-quoted style, so the scalar always parses back as a
892
+ * string — a bare-looking id like `2024` would be an integer to a strict
893
+ * YAML reader, bare `true` / `null` / `~` would be a boolean or null, and
894
+ * a hand-rolled escape covers nothing like the full metacharacter set
895
+ * (control characters included) JSON.stringify handles. The flow shapes
896
+ * around the scalars are kept.
897
+ */
898
+ function okfFlowScalar(value: string): string {
899
+ return JSON.stringify(value);
900
+ }
901
+
902
+ /**
903
+ * Serialise one bundle page file: the page's own frontmatter and body
904
+ * verbatim, plus the OKF v0.2 per-page keys (`type`, `status`,
905
+ * `sources`, `generated`) as DERIVED fields. The derived keys are
906
+ * recomputed from current page state on every export and never carried
907
+ * through from a previous bundle, so re-exporting an imported page
908
+ * re-derives them instead of stacking a foreign bundle's values a second
909
+ * time. Because the derived block is a projection - a closed status
910
+ * enum, sources re-translated from citations, a type taken from the
911
+ * preserved foreign type or the structural kind - the page's NATIVE
912
+ * values ride beside it under the producer namespace (`okf_status_raw`,
913
+ * `okf_sources_raw`, `okf_generated_raw`, `okf_type_raw`), so a trusted
914
+ * own-producer import can restore what the projection cannot name. The
915
+ * derived `type` is the spec's one always-required per-concept key, so
916
+ * every page carries it even when its frontmatter never did.
917
+ *
918
+ * The derived block is rendered by hand in YAML flow style because the
919
+ * shared frontmatter writer emits scalars and inline arrays only - and
920
+ * the flow shapes chosen (one line per source entry, one line for
921
+ * `generated`) keep the page parseable by consumers with full YAML
922
+ * parsers while never producing a line this system's own scanner would
923
+ * misread as a top-level key.
924
+ */
925
+ function renderOkfPageFile(
926
+ page: OkfPage,
927
+ sources: ReadonlyArray<OkfSource>,
928
+ generatedAt: string,
929
+ ): string {
930
+ const carried: FrontmatterMap = {};
931
+ for (const [key, value] of Object.entries(page.frontmatter)) {
932
+ // Both sides of every pair are skipped: the native field is re-derived
933
+ // below, and the raw carrier is re-stamped from the current state - the
934
+ // pair list is the one source of what must not ride through verbatim.
935
+ if (RAW_OKF_KEYS.some(({ raw, native }) => raw === key || native === key)) continue;
936
+ if (key === RAW_CARRY_KEY) continue;
937
+ carried[key] = value;
938
+ }
939
+ // The native values ride the producer namespace beside the derived
940
+ // block: the derived status maps onto a closed enum and the derived
941
+ // sources are re-translated from citations, so exporting them in place
942
+ // would rewrite what the operator wrote. Recomputed from current page
943
+ // state on every export and never carried through from a previous
944
+ // bundle - the same honesty rule as the derived block. A value is
945
+ // carried on PRESENCE alone (the rule sources and generated follow):
946
+ // a non-string status - a number from a hand-built frontmatter map, a
947
+ // list - is exactly the value the closed enum cannot name, so reading
948
+ // it through the string-only field would drop the one raw key that
949
+ // preserves it.
950
+ for (const { raw, native } of RAW_OKF_KEYS) {
951
+ if (page.frontmatter[native] !== undefined) carried[raw] = page.frontmatter[native];
952
+ }
953
+ // The raw-carrying declaration, stamped fresh on every page of every
954
+ // export: this is what tells the own-producer import that absent raw
955
+ // keys mean "the field never had a value" rather than "a legacy
956
+ // bundle's page - leave the frontmatter alone". It names exactly the
957
+ // natives this exporter manages - the derived `type` included - so
958
+ // the restore drops the whole derived block from a page that never
959
+ // carried one natively, and a bare `true` stays what it always was:
960
+ // a LEGACY page's marker, covering the pre-type-pair set only.
961
+ carried[RAW_CARRY_KEY] = RAW_OKF_KEYS.map(({ native }) => native);
962
+ // formatFrontmatter with an empty body is exactly "---\n<keys>---\n";
963
+ // drop the closing fence, append the derived block, re-close.
964
+ let out = formatFrontmatter(carried, "").slice(0, -"---\n".length);
965
+ // `type` is the spec's only always-required per-concept key (non-empty),
966
+ // so the derived block opens with it: the preserved foreign type when
967
+ // the page was imported from a foreign producer, else the page's own
968
+ // structural kind - the honest fields the page walk collected. A native
969
+ // `type` is NOT shadowed by this projection: it rode out under
970
+ // okf_type_raw above, and the own-producer restore puts it back.
971
+ out += `type: ${okfFlowScalar(page.foreign_type ?? page.kind)}\n`;
972
+ out += `status: ${page.status}\n`;
973
+ if (sources.length > 0) {
974
+ out += "sources:\n";
975
+ for (const source of sources) {
976
+ out += ` - {resource: ${okfFlowScalar(source.resource)}`;
977
+ if (source.id !== undefined) out += `, id: ${okfFlowScalar(source.id)}`;
978
+ out += "}\n";
979
+ }
980
+ }
981
+ out += `generated: {by: ${okfFlowScalar(OKF_GENERATED_BY)}, at: "${generatedAt}"}\n`;
982
+ out += "---\n";
983
+ if (page.body.length > 0) out += `\n${page.body}\n`;
984
+ return out;
985
+ }
986
+
987
+ /**
988
+ * Build an OKF bundle write-plan from the vault. Pure and read-only:
989
+ * returns the manifest plus every file to write. Content is
990
+ * deterministic across runs (pages and log days are sorted); the only
991
+ * value that varies is the single shared generated instant, which the
992
+ * manifest's `generated_at` and every page's `generated.at` carry.
993
+ */
994
+ export function buildOkfBundle(vault: string): OkfBundle {
995
+ return assembleOkfBundle(vault, collectOkfPages(vault), buildLog(vault));
996
+ }
997
+
998
+ /**
999
+ * Build an OKF bundle write-plan over a caller-chosen SUBSET of pages and
1000
+ * no change log. The knowledge-pack export is the caller: a pack carries
1001
+ * the pages an operator selected, never the vault's whole history, so the
1002
+ * date-grouped `log.md` a full bundle folds in is left out (the manifest
1003
+ * says `log_days: 0`). Pure; the pages are written as given.
1004
+ */
1005
+ export function buildOkfSubsetBundle(vault: string, pages: ReadonlyArray<OkfPage>): OkfBundle {
1006
+ return assembleOkfBundle(vault, pages, null);
1007
+ }
1008
+
1009
+ /**
1010
+ * Build a full OKF bundle write-plan - change log included - over
1011
+ * caller-collected pages, composing from the array as given instead of
1012
+ * walking the vault again. {@link buildOkfSubsetBundle} is the existing
1013
+ * page-input entry point, but a subset bundle carries no `log.md` by
1014
+ * contract, so a caller that has ALREADY walked the vault (the shared
1015
+ * export verbs, which split the collected pages through the egress
1016
+ * content-class policy before composition) had no way to keep the change
1017
+ * log without a second walk. Composing from the caller's page array
1018
+ * closes that double-walk window: between the caller's walk and a
1019
+ * re-walk here, a page can change or appear, and the bundle would mix
1020
+ * the two reads - or, with the class policy applied to the first walk
1021
+ * only, re-admit a page the policy had just left out. The pages are
1022
+ * written as given.
1023
+ *
1024
+ * The `log` argument is the change log to fold in, already read (and
1025
+ * already filtered through the caller's content-class policy) by
1026
+ * {@link buildLog}. Omitted, the log is read here unfiltered - the
1027
+ * whole-log behavior the callers that have no split in hand rely on - so
1028
+ * a verb that needs the filtered log passes its {@link buildLog} result
1029
+ * through rather than re-reading the vault a second time.
1030
+ */
1031
+ export function buildOkfBundleFromPages(
1032
+ vault: string,
1033
+ pages: ReadonlyArray<OkfPage>,
1034
+ log: Pick<OkfLog, "contents" | "days" | "privateEntries"> = buildLog(vault),
1035
+ ): OkfBundle {
1036
+ return assembleOkfBundle(vault, pages, log);
1037
+ }
1038
+
1039
+ function assembleOkfBundle(
1040
+ vault: string,
1041
+ pages: ReadonlyArray<OkfPage>,
1042
+ log: Pick<OkfLog, "contents" | "days" | "privateEntries"> | null,
1043
+ ): OkfBundle {
1044
+ // ONE instant for the whole bundle: the manifest's `generated_at` and
1045
+ // every page's `generated.at` share it, so whole-bundle byte equality
1046
+ // modulo that single value stays the determinism contract.
1047
+ const generatedAt = isoSecond();
1048
+ const resolveSource = sourceResolver(pages);
1049
+ const derived = pages.map((p) => ({ page: p, sources: translateSources(p, resolveSource) }));
1050
+ const manifest: OkfManifest = {
1051
+ schema: OKF_SCHEMA_VERSION,
1052
+ producer: OKF_PRODUCER,
1053
+ generated_at: generatedAt,
1054
+ vault_basename: vaultDisplayName(vault),
1055
+ pages: derived.map(({ page, sources }) => ({
1056
+ id: page.id,
1057
+ path: page.path,
1058
+ class: page.cls,
1059
+ bundle_path: page.bundle_path,
1060
+ kind: page.kind,
1061
+ citations: page.citations,
1062
+ status: page.status,
1063
+ sources,
1064
+ aliases: page.aliases,
1065
+ freshness: page.freshness,
1066
+ foreign_type: page.foreign_type,
1067
+ producer_meta: page.producer_meta,
1068
+ })),
1069
+ log_days: log?.days ?? 0,
1070
+ log_private_omitted: log?.privateEntries ?? 0,
1071
+ };
1072
+
1073
+ const files: OkfBundleFile[] = [
1074
+ { path: OKF_MANIFEST_FILENAME, contents: renderOkfManifest(manifest) },
1075
+ { path: OKF_INDEX_FILENAME, contents: renderIndex(manifest) },
1076
+ ];
1077
+ if (log !== null) files.push({ path: "log.md", contents: log.contents });
1078
+ for (const { page, sources } of derived) {
1079
+ files.push({ path: page.bundle_path, contents: renderOkfPageFile(page, sources, generatedAt) });
1080
+ }
1081
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
1082
+ return { manifest, files };
1083
+ }
1084
+
1085
+ /**
1086
+ * Write a bundle to `dir`. Refuses to clobber a non-empty existing
1087
+ * directory unless `force` is set. Creates parent subdirectories as
1088
+ * needed; each file is written atomically.
1089
+ */
1090
+ export function writeOkfBundle(
1091
+ dir: string,
1092
+ bundle: OkfBundle,
1093
+ opts: { force?: boolean } = {},
1094
+ ): void {
1095
+ if (existsSync(dir)) {
1096
+ let existing: string[] = [];
1097
+ try {
1098
+ existing = readdirSync(dir);
1099
+ } catch {
1100
+ /* treat unreadable as empty */
1101
+ }
1102
+ if (existing.length > 0 && !opts.force) {
1103
+ throw new OkfError(`${dir} is not empty; pass --force to overwrite`);
1104
+ }
1105
+ }
1106
+ for (const file of bundle.files) {
1107
+ const abs = ensureInsideVault(resolve(dir, file.path), dir);
1108
+ mkdirSync(dirname(abs), { recursive: true });
1109
+ atomicWriteFileSync(abs, file.contents);
1110
+ }
1111
+ }
1112
+
1113
+ // ----- Import ---------------------------------------------------------------
1114
+
1115
+ /** Raised when an OKF bundle is structurally invalid or unsupported. */
1116
+ export class OkfError extends Error {
1117
+ constructor(message: string) {
1118
+ super(message);
1119
+ this.name = "OkfError";
1120
+ }
1121
+ }
1122
+
1123
+ /** A page parsed back out of a bundle on disk. */
1124
+ export interface ParsedOkfPage {
1125
+ readonly entry: OkfManifestPage;
1126
+ readonly frontmatter: FrontmatterMap;
1127
+ readonly body: string;
1128
+ }
1129
+
1130
+ export interface ParsedOkfBundle {
1131
+ readonly manifest: OkfManifest;
1132
+ /** True when the bundle was produced by some tool other than OSB. */
1133
+ readonly foreign: boolean;
1134
+ readonly pages: ReadonlyArray<ParsedOkfPage>;
1135
+ }
1136
+
1137
+ interface ManifestInput {
1138
+ readonly schema?: unknown;
1139
+ readonly producer?: unknown;
1140
+ readonly generated_at?: unknown;
1141
+ readonly vault_basename?: unknown;
1142
+ readonly log_days?: unknown;
1143
+ readonly log_private_omitted?: unknown;
1144
+ readonly pages?: unknown;
1145
+ }
1146
+
1147
+ /** Parse a manifest `sources` entry; entries without a resource are dropped. */
1148
+ function asOkfSource(value: unknown): OkfSource | null {
1149
+ if (value === null || typeof value !== "object") return null;
1150
+ const resource = (value as Record<string, unknown>)["resource"];
1151
+ if (typeof resource !== "string" || resource.length === 0) return null;
1152
+ const id = (value as Record<string, unknown>)["id"];
1153
+ return typeof id === "string" && id.length > 0 ? { resource, id } : { resource };
1154
+ }
1155
+
1156
+ function asManifestPage(value: unknown): OkfManifestPage | null {
1157
+ if (value === null || typeof value !== "object") return null;
1158
+ const v = value as Record<string, unknown>;
1159
+ if (typeof v["bundle_path"] !== "string" || typeof v["path"] !== "string") return null;
1160
+ const cls = v["class"];
1161
+ const klass: OkfPageClass =
1162
+ cls === "query" || cls === "reference" || cls === "concept" ? cls : "concept";
1163
+ const status = v["status"];
1164
+ return {
1165
+ id: typeof v["id"] === "string" ? v["id"] : stem(v["path"]),
1166
+ path: v["path"],
1167
+ class: klass,
1168
+ bundle_path: v["bundle_path"],
1169
+ kind: typeof v["kind"] === "string" ? v["kind"] : DEFAULT_KIND,
1170
+ citations: Array.isArray(v["citations"]) ? (v["citations"] as string[]) : [],
1171
+ status: status === "draft" || status === "deprecated" ? status : "stable",
1172
+ sources: Array.isArray(v["sources"])
1173
+ ? v["sources"].map(asOkfSource).filter((s): s is OkfSource => s !== null)
1174
+ : [],
1175
+ aliases: Array.isArray(v["aliases"]) ? (v["aliases"] as string[]) : [],
1176
+ freshness: typeof v["freshness"] === "string" ? v["freshness"] : null,
1177
+ foreign_type: typeof v["foreign_type"] === "string" ? v["foreign_type"] : null,
1178
+ producer_meta:
1179
+ v["producer_meta"] && typeof v["producer_meta"] === "object"
1180
+ ? (v["producer_meta"] as Record<string, string>)
1181
+ : {},
1182
+ };
1183
+ }
1184
+
1185
+ /**
1186
+ * Read the bundle-root index's `okf_version` declaration, or null when
1187
+ * the index is missing, unreadable, or declares no version. Consulted
1188
+ * only when the manifest does not carry the dialect schema, so the
1189
+ * schema-"1" path (sealed knowledge-pack halves included) never grows a
1190
+ * dependency on an index file being present.
1191
+ */
1192
+ function indexOkfVersion(dir: string): string | null {
1193
+ let raw: string;
1194
+ try {
1195
+ raw = readFileSync(join(dir, "index.md"), "utf8");
1196
+ } catch {
1197
+ return null;
1198
+ }
1199
+ const [meta] = parseFrontmatterText(raw);
1200
+ const value = meta["okf_version"];
1201
+ return typeof value === "string" && value.length > 0 ? value : null;
1202
+ }
1203
+
1204
+ /**
1205
+ * The bundle-directory names that map onto page classes, derived from
1206
+ * {@link CLASS_DIR} so the export's lanes and the import's reading of
1207
+ * them cannot drift.
1208
+ */
1209
+ const SPEC_DIR_CLASS: Readonly<Record<string, OkfPageClass>> = Object.freeze(
1210
+ Object.fromEntries(Object.entries(CLASS_DIR).map(([cls, dir]) => [dir, cls as OkfPageClass])),
1211
+ );
1212
+
1213
+ /**
1214
+ * Reserved bundle-root files per the OKF v0.2 spec: the version-
1215
+ * declaring index and the change log. The reservation is a ROOT one -
1216
+ * the spec reserves the two names at the top of the bundle tree, so a
1217
+ * foreign bundle's nested `concepts/index.md` or a per-project
1218
+ * `notes/log.md` is a real page. The walk matches these against the
1219
+ * page's full bundle-relative path, lowercased - never the basename,
1220
+ * which would skip real pages at any depth.
1221
+ */
1222
+ const SPEC_RESERVED_PATHS: ReadonlySet<string> = new Set([OKF_INDEX_FILENAME, "log.md"]);
1223
+
1224
+ /**
1225
+ * The producer label a manifest-less spec bundle reports: there is no
1226
+ * manifest to declare one, so the parsed manifest names the walk
1227
+ * honestly instead of guessing a producer from the tree. Named because
1228
+ * the bundle is FOREIGN by construction - a walk with no manifest can
1229
+ * never be this system's own dialect - and the old inline comparison
1230
+ * against {@link OKF_PRODUCER} restated that fact as a tautology.
1231
+ */
1232
+ const SPEC_BUNDLE_PRODUCER = "unknown";
1233
+
1234
+ /**
1235
+ * Read a manifest-less, spec-shaped OKF v0.2 bundle: the spec defines a
1236
+ * bundle as a plain directory tree of markdown and requires NO machine
1237
+ * manifest, so the page list is built by walking the tree. Reserved
1238
+ * bundle-root files (index.md, log.md) are skipped, the class comes from
1239
+ * the page's top-level directory when it names a class lane (concepts /
1240
+ * queries / references) and defaults to `concept` everywhere else, and
1241
+ * each walked page's own `type` frontmatter is recorded as its foreign
1242
+ * type - the producer's raw type value, which the import's provenance
1243
+ * stamp preserves. There is no manifest to declare a producer, so the
1244
+ * parsed manifest reports {@link SPEC_BUNDLE_PRODUCER} and the bundle is
1245
+ * FOREIGN by construction: every page imports through the foreign path
1246
+ * (machinery stripped, raw keys shed, provenance stamped, review-staged
1247
+ * by default) - the walk never restores machinery keys on a spec
1248
+ * bundle's word.
1249
+ */
1250
+ function readSpecOkfBundle(dir: string): ParsedOkfBundle {
1251
+ const producer = SPEC_BUNDLE_PRODUCER;
1252
+ const entries: OkfManifestPage[] = [];
1253
+ const pages: ParsedOkfPage[] = [];
1254
+ for (const abs of listMarkdown(dir, [])) {
1255
+ const rel = relative(dir, abs).split(/[\\/]/).join(posix.sep);
1256
+ if (SPEC_RESERVED_PATHS.has(rel.toLowerCase())) continue;
1257
+ // Same wall the manifest path applies: a walked file that is not
1258
+ // (symlink-)inside the bundle is skipped, never read.
1259
+ try {
1260
+ ensureInsideVault(abs, dir);
1261
+ } catch {
1262
+ continue;
1263
+ }
1264
+ let raw: string;
1265
+ try {
1266
+ raw = readFileSync(abs, "utf8");
1267
+ } catch {
1268
+ continue;
1269
+ }
1270
+ const [frontmatter, body] = parseFrontmatterText(raw);
1271
+ const topDir = rel.includes("/") ? rel.slice(0, rel.indexOf("/")) : "";
1272
+ const entry: OkfManifestPage = {
1273
+ id: stem(rel),
1274
+ path: rel,
1275
+ class: SPEC_DIR_CLASS[topDir] ?? "concept",
1276
+ bundle_path: rel,
1277
+ kind: stringField(frontmatter, "kind") ?? DEFAULT_KIND,
1278
+ citations: [],
1279
+ status: "stable",
1280
+ sources: [],
1281
+ aliases: [],
1282
+ freshness: null,
1283
+ foreign_type: stringField(frontmatter, "type"),
1284
+ producer_meta: {},
1285
+ };
1286
+ entries.push(entry);
1287
+ pages.push({ entry, frontmatter, body });
1288
+ }
1289
+ return {
1290
+ manifest: {
1291
+ schema: "",
1292
+ producer,
1293
+ generated_at: "",
1294
+ vault_basename: "",
1295
+ pages: entries,
1296
+ log_days: 0,
1297
+ log_private_omitted: 0,
1298
+ },
1299
+ // No manifest, no own-producer claim to honour: the walk's output is
1300
+ // foreign by construction - stating it directly instead of resting
1301
+ // on a literal-vs-constant comparison that could only ever be true.
1302
+ foreign: true,
1303
+ pages,
1304
+ };
1305
+ }
1306
+
1307
+ /**
1308
+ * Read an OKF bundle directory: parse `okf.json`, validate the schema,
1309
+ * then parse each manifest-listed page file. Three bundle generations
1310
+ * are accepted: a manifest carrying the Open Second Brain dialect
1311
+ * `schema: "1"`, a bundle whose manifest declares NO schema while its
1312
+ * bundle-root `index.md` declares `okf_version: "0.2"` (the OKF v0.2
1313
+ * marker this export writes beside the dialect schema), and - the spec
1314
+ * shape - a bundle with NO manifest at all whose bundle-root index
1315
+ * declares the same version, which is read by walking the tree (see
1316
+ * {@link readSpecOkfBundle}). A PRESENT non-dialect schema is refused
1317
+ * whatever the index says: this export's own index always declares the
1318
+ * version, so treating the declaration as sufficient on its own would
1319
+ * admit every future dialect bump under v1 assumptions. Everything else
1320
+ * is refused by name. A page whose file is missing or unreadable is
1321
+ * skipped (the manifest is the source of truth for what *should* be
1322
+ * there; a partial bundle still imports what it has). An unsupported
1323
+ * schema or an absent manifest without a v0.2 index declaration throws
1324
+ * {@link OkfError}.
1325
+ */
1326
+ export function readOkfBundle(dir: string): ParsedOkfBundle {
1327
+ const manifestPath = join(dir, OKF_MANIFEST_FILENAME);
1328
+ if (!existsSync(manifestPath)) {
1329
+ // No manifest at all. The v0.2 spec requires none, so the spec shape
1330
+ // - a v0.2 declaration on the bundle-root index - is accepted and
1331
+ // read as a tree; everything else is refused exactly as before.
1332
+ if (indexOkfVersion(dir) === OKF_VERSION) return readSpecOkfBundle(dir);
1333
+ throw new OkfError(`not an OKF bundle: ${manifestPath} is missing`);
1334
+ }
1335
+ let parsed: ManifestInput;
1336
+ try {
1337
+ parsed = JSON.parse(readFileSync(manifestPath, "utf8")) as ManifestInput;
1338
+ } catch (exc) {
1339
+ throw new OkfError(`okf.json is not valid JSON: ${(exc as Error).message ?? exc}`);
1340
+ }
1341
+ if (parsed === null || typeof parsed !== "object") {
1342
+ throw new OkfError("okf.json must be a JSON object");
1343
+ }
1344
+ // A null schema declares nothing, exactly like an absent or empty one:
1345
+ // a writer that nulls the field is not naming a schema, and falling
1346
+ // through to the by-name refusal would report "expected 1, got null"
1347
+ // even beside a v0.2 index declaration.
1348
+ const schemaAbsent =
1349
+ parsed.schema === undefined || parsed.schema === null || parsed.schema === "";
1350
+ if (parsed.schema === OKF_SCHEMA_VERSION) {
1351
+ // The dialect path. Sealed knowledge-pack halves exported before
1352
+ // v0.2 emission take it, so it never depends on an index file.
1353
+ } else if (schemaAbsent && indexOkfVersion(dir) === OKF_VERSION) {
1354
+ // The version-declaration path: no manifest schema, and the bundle
1355
+ // root says OKF v0.2. Version-level only - the gate never reads the
1356
+ // producer.
1357
+ } else if (schemaAbsent) {
1358
+ throw new OkfError(
1359
+ `unsupported OKF schema: no schema ${OKF_SCHEMA_VERSION} in ${OKF_MANIFEST_FILENAME} ` +
1360
+ `and no okf_version ${OKF_VERSION} declaration in index.md`,
1361
+ );
1362
+ } else {
1363
+ throw new OkfError(
1364
+ `unsupported OKF schema: expected ${OKF_SCHEMA_VERSION}, got ${String(parsed.schema)}`,
1365
+ );
1366
+ }
1367
+ const producer = typeof parsed.producer === "string" ? parsed.producer : "unknown";
1368
+ const rawPages = Array.isArray(parsed.pages) ? parsed.pages : [];
1369
+ const entries = rawPages.map(asManifestPage).filter((p): p is OkfManifestPage => p !== null);
1370
+
1371
+ const pages: ParsedOkfPage[] = [];
1372
+ for (const entry of entries) {
1373
+ // Validate the bundle-relative path stays inside the bundle dir
1374
+ // before reading — a hostile manifest cannot make us read outside.
1375
+ let abs: string;
1376
+ try {
1377
+ abs = ensureInsideVault(join(dir, entry.bundle_path), dir);
1378
+ } catch {
1379
+ continue;
1380
+ }
1381
+ let raw: string;
1382
+ try {
1383
+ raw = readFileSync(abs, "utf8");
1384
+ } catch {
1385
+ continue;
1386
+ }
1387
+ const [frontmatter, body] = parseFrontmatterText(raw);
1388
+ pages.push({ entry, frontmatter, body });
1389
+ }
1390
+
1391
+ return {
1392
+ manifest: {
1393
+ // Preserve the ON-DISK schema value rather than stamping this
1394
+ // module's constant: a reader inspecting the parsed manifest must
1395
+ // see which declaration the bundle actually made (a v0.2-accepted
1396
+ // bundle may name a non-dialect schema, or none at all).
1397
+ schema: typeof parsed.schema === "string" ? parsed.schema : "",
1398
+ producer,
1399
+ // Preserve the bundle's own metadata instead of synthesizing
1400
+ // placeholders: readOkfBundle is a reader, and a caller that
1401
+ // inspects the parsed manifest should see what is on disk.
1402
+ generated_at: typeof parsed.generated_at === "string" ? parsed.generated_at : "",
1403
+ vault_basename: typeof parsed.vault_basename === "string" ? parsed.vault_basename : "",
1404
+ pages: entries,
1405
+ log_days:
1406
+ typeof parsed.log_days === "number" && Number.isFinite(parsed.log_days)
1407
+ ? parsed.log_days
1408
+ : 0,
1409
+ log_private_omitted:
1410
+ typeof parsed.log_private_omitted === "number" &&
1411
+ Number.isFinite(parsed.log_private_omitted)
1412
+ ? parsed.log_private_omitted
1413
+ : 0,
1414
+ },
1415
+ foreign: producer !== OKF_PRODUCER,
1416
+ pages,
1417
+ };
1418
+ }
1419
+
1420
+ export interface OkfImportOptions {
1421
+ /**
1422
+ * When true, write each page directly to its recorded vault-relative
1423
+ * path (a true round-trip). When false (default), stage every page
1424
+ * under `OKF Review/` with `okf_review: pending` so the live vault is
1425
+ * untouched until an operator promotes the candidates.
1426
+ *
1427
+ * This flag is the operator's vouch, and the only one the import
1428
+ * honours: without it machinery frontmatter (`_status`, `owner`,
1429
+ * `origin_channel`, ...) is stripped and the Brain page lanes are not
1430
+ * writable, whatever `producer` the bundle's manifest declares.
1431
+ */
1432
+ readonly trusted?: boolean;
1433
+ /** Wall clock for the import stamp. Tests pin this. */
1434
+ readonly now?: Date;
1435
+ /**
1436
+ * Server-side provenance written onto every landed page AFTER the
1437
+ * machinery strip, so the bundle can neither supply nor forge it. The
1438
+ * knowledge-pack installer passes its `knowledge_pack` stamp here.
1439
+ */
1440
+ readonly provenance?: Readonly<Record<string, string>>;
1441
+ }
1442
+
1443
+ export interface OkfImportResult {
1444
+ /** Vault-relative paths written. */
1445
+ readonly written: ReadonlyArray<string>;
1446
+ /** Paths skipped because the target already existed (review mode). */
1447
+ readonly skipped: ReadonlyArray<string>;
1448
+ readonly errors: ReadonlyArray<{ path: string; message: string }>;
1449
+ /** True when the bundle producer was foreign (provenance was stamped). */
1450
+ readonly foreign: boolean;
1451
+ /** `"trusted"` (direct write) or `"review"` (staged). */
1452
+ readonly mode: "trusted" | "review";
1453
+ }
1454
+
1455
+ /**
1456
+ * Frontmatter keys an imported page may not carry across the trust
1457
+ * boundary. These are the machinery fields this system's own writers
1458
+ * stamp server-side - the `_status`/`_confidence` lifecycle, the
1459
+ * `_revision`/`_content_hash` write accounting, the `origin_channel`
1460
+ * transport stamp, the `owner` scope claim, and the `okf_review` staging
1461
+ * marker - so a bundle supplying them verbatim would mint pages that
1462
+ * read as system-authored the moment an operator promotes them out of
1463
+ * the review lane.
1464
+ *
1465
+ * Stripped on every import the operator did not vouch for with
1466
+ * `--trusted`, whatever the manifest's `producer` says: the producer
1467
+ * field is bundle-supplied and a forged `open-second-brain` must not
1468
+ * carry `_status: confirmed` through. A trusted import of a bundle that
1469
+ * declares a foreign producer strips them too - nothing a foreign tool
1470
+ * wrote is this system's machinery. The one lossless path is a trusted
1471
+ * import of a bundle that declares this producer: the operator's own
1472
+ * round-trip, vouched for by the operator, not by the bundle.
1473
+ *
1474
+ * `visibility` is deliberately NOT in this set. It is the page's
1475
+ * read-scope, and every token it can carry only NARROWS reach (a page
1476
+ * with no `visibility:` is reachable by every consumer; see
1477
+ * `graph/visibility.ts`). Stripping it could only widen what a page
1478
+ * exposes - a private page in the operator's own bundle would land
1479
+ * public in the review lane - while preserving it can at worst hide a
1480
+ * staged page from a remote read, which the review lane survives.
1481
+ */
1482
+ const FOREIGN_MACHINERY_KEYS: ReadonlySet<string> = new Set([
1483
+ "_status",
1484
+ "_confidence",
1485
+ "_confidence_value",
1486
+ "_revision",
1487
+ "_content_hash",
1488
+ "_force_confirmed_via",
1489
+ "origin_channel",
1490
+ "owner",
1491
+ "okf_review",
1492
+ // The knowledge-pack provenance stamp: written by the pack installer
1493
+ // after this strip, so a bundle cannot enrol a page in a pack's uninstall.
1494
+ KNOWLEDGE_PACK_FIELD,
1495
+ // The staged page's install-time fingerprint, same rule as the stamp.
1496
+ KNOWLEDGE_PACK_SHA_FIELD,
1497
+ ]);
1498
+
1499
+ /**
1500
+ * A copy of `meta` without this system's machinery keys (see
1501
+ * {@link FOREIGN_MACHINERY_KEYS}). The knowledge-pack export runs every
1502
+ * selected page through it: a pack is handed to someone else, and this
1503
+ * vault's lifecycle, write-accounting, transport and owner stamps are not
1504
+ * knowledge the recipient can use - the recipient's import strips them
1505
+ * anyway, so leaving them in would only widen what the file leaks.
1506
+ */
1507
+ export function stripOkfMachinery(meta: FrontmatterMap): FrontmatterMap {
1508
+ const out: FrontmatterMap = { ...meta };
1509
+ for (const key of FOREIGN_MACHINERY_KEYS) delete out[key];
1510
+ return out;
1511
+ }
1512
+
1513
+ /**
1514
+ * The Brain directories an OKF bundle carries pages for: exactly the two
1515
+ * lanes {@link buildOkfBundle} exports (`sources/` as references,
1516
+ * `reports/` as queries).
1517
+ */
1518
+ const OKF_BRAIN_PAGE_LANES: ReadonlyArray<string> = Object.freeze([
1519
+ BRAIN_SOURCES_REL,
1520
+ BRAIN_REPORTS_REL,
1521
+ ]);
1522
+
1523
+ /**
1524
+ * The refusal reason for a recorded page path, or `null` when the path may
1525
+ * proceed into its lane. Two walls:
1526
+ *
1527
+ * 1. A recorded path is a vault-relative POSIX path: absolute, empty,
1528
+ * backslash, `.`, and `..` segments are refused before any join.
1529
+ * Refusing `..` is what keeps the review lane unescapable -
1530
+ * `posix.join("OKF Review", "../Brain/standing-rules.md")` normalizes
1531
+ * to `Brain/standing-rules.md`, which would let a hostile manifest
1532
+ * plant machinery files straight into the live vault. Backslash is
1533
+ * refused as a character because it is a separator on the Windows
1534
+ * filesystems this project ships on, where a posix-string check would
1535
+ * not see the escape.
1536
+ * 2. In trusted mode `Brain/` is machinery, not pages: only the two page
1537
+ * lanes the exporter emits (`sources/`, `reports/`) are writable, and
1538
+ * only because the operator passed `--trusted` - the bundle's
1539
+ * `producer` claim plays no part. The Brain segment is compared
1540
+ * case-insensitively (`brain/` opens `Brain/` on macOS and Windows).
1541
+ * Review mode needs no such wall - wall 1 already guarantees staging
1542
+ * stays under `OKF Review/`, where a Brain-shaped subpath is inert.
1543
+ */
1544
+ function okfTargetRefusal(entryPath: string, trusted: boolean): string | null {
1545
+ if (
1546
+ entryPath.length === 0 ||
1547
+ entryPath.startsWith("/") ||
1548
+ entryPath.includes("\\") ||
1549
+ entryPath.split("/").some((s) => s.length === 0 || s === "." || s === "..")
1550
+ ) {
1551
+ return `recorded path must be a relative POSIX path with no empty, '.', '..', or backslash segments: ${entryPath}`;
1552
+ }
1553
+ if (trusted && isUnderBrainRoot(entryPath) && !isInBrainLane(entryPath, OKF_BRAIN_PAGE_LANES)) {
1554
+ return (
1555
+ `trusted import refuses Brain machinery paths except the ` +
1556
+ `${BRAIN_SOURCES_REL}/ and ${BRAIN_REPORTS_REL}/ page lanes: ${entryPath}`
1557
+ );
1558
+ }
1559
+ return null;
1560
+ }
1561
+
1562
+ /**
1563
+ * Read the native-key coverage a page's {@link RAW_CARRY_KEY} marker
1564
+ * declares. A bare `true` - the shape every exporter stamped before the
1565
+ * marker could carry a list - covers exactly the old three-key set
1566
+ * ({@link RAW_CARRY_TRUE_NATIVES}); a list of native names covers what
1567
+ * it names, so an exporter managing a different set declares it instead
1568
+ * of the import guessing. An unrecognized shape still says legacy
1569
+ * raw-carrying. An ABSENT marker (a page whose raw keys survived while
1570
+ * the marker was lost) declares nothing extra: the present raw keys
1571
+ * restore their own pairs, and nothing else is dropped.
1572
+ */
1573
+ function rawCarryDeclaredNatives(marker: FrontmatterValue | undefined): ReadonlySet<string> {
1574
+ if (marker === undefined) return new Set();
1575
+ if (Array.isArray(marker)) {
1576
+ return new Set(marker.filter((item): item is string => typeof item === "string"));
1577
+ }
1578
+ return RAW_CARRY_TRUE_NATIVES;
1579
+ }
1580
+
1581
+ /**
1582
+ * Restore the native frontmatter an own-producer export carried under
1583
+ * the producer namespace (the `okf_*_raw` keys), dropping the derived
1584
+ * v0.2 block the export wrote beside it. The operator's round-trip is
1585
+ * "restore the recorded state": a page quarantined before export lands
1586
+ * quarantined again instead of silently promoted to the enum's
1587
+ * `stable`, a completion status comes back itself, user-written sources
1588
+ * survive, and a page that never carried a status (or sources) again
1589
+ * does not. A raw key restores its native verbatim; a MISSING raw key
1590
+ * drops its derived value only when the page's marker declared that
1591
+ * pair (see {@link rawCarryDeclaredNatives}) - a fresh-export plain
1592
+ * page comes back without the derived status it never had, while a
1593
+ * legacy marker-bearing page keeps the native `type` its export rode
1594
+ * verbatim beside a marker that predates the type pair.
1595
+ *
1596
+ * The restore runs only on a page that declares raw-carrying: the
1597
+ * {@link RAW_CARRY_KEY} marker, or - saying the same thing when the
1598
+ * marker went missing - any present raw key, which no legacy bundle
1599
+ * ever wrote. A page with NEITHER is a legacy bundle's (exported
1600
+ * before the raw-carrying declaration existed - sealed knowledge-pack
1601
+ * halves accepted on purpose included), its natives are the
1602
+ * frontmatter already in place, and reading their absence as "never
1603
+ * had a value" deleted them. The restore is skipped for such a page,
1604
+ * so a legacy quarantine survives its own round-trip; a page that kept
1605
+ * its raw keys but lost the marker is restored anyway, instead of
1606
+ * stranding the keys beside the derived block they were written to
1607
+ * replace.
1608
+ */
1609
+ function restoreRawOkfKeys(meta: FrontmatterMap): void {
1610
+ const marked =
1611
+ meta[RAW_CARRY_KEY] !== undefined || RAW_OKF_KEYS.some(({ raw }) => meta[raw] !== undefined);
1612
+ if (!marked) return;
1613
+ const declared = rawCarryDeclaredNatives(meta[RAW_CARRY_KEY]);
1614
+ delete meta[RAW_CARRY_KEY];
1615
+ for (const { raw, native } of RAW_OKF_KEYS) {
1616
+ // Presence, not shape: the raw value round-tripped through the page
1617
+ // file is whatever the export carried, and the restore replaces the
1618
+ // derived value with it verbatim - a numeric or whitespace status
1619
+ // included.
1620
+ if (meta[raw] !== undefined) meta[native] = meta[raw];
1621
+ else if (declared.has(native)) delete meta[native];
1622
+ delete meta[raw];
1623
+ }
1624
+ }
1625
+
1626
+ /**
1627
+ * Compose the frontmatter a page lands with. Standard fields are taken
1628
+ * from the bundle file verbatim. This system's machinery keys (they are
1629
+ * server-stamped, not caller-supplied - see
1630
+ * {@link FOREIGN_MACHINERY_KEYS}) are stripped unless the operator
1631
+ * vouched for an own-producer bundle with `--trusted`. The native values
1632
+ * the export carried under the producer namespace are restored on every
1633
+ * OWN-producer path - the trusted round-trip and review staging alike,
1634
+ * where the staged page's `okf_review: pending` already keeps it out of
1635
+ * the live vault (see {@link restoreRawOkfKeys}). A bundle that declares
1636
+ * a foreign producer imports verbatim instead, shedding the raw keys so
1637
+ * no foreign page lands speaking this system's machinery namespace, and
1638
+ * gets provenance stamped (producer + raw foreign type) without
1639
+ * clobbering any such key the page already carries - preserving, never
1640
+ * overwriting, producer-specific metadata. Review-staged pages also get
1641
+ * `okf_review: pending`.
1642
+ */
1643
+ function importFrontmatter(
1644
+ page: ParsedOkfPage,
1645
+ producer: string,
1646
+ foreign: boolean,
1647
+ trusted: boolean,
1648
+ nowIso: string,
1649
+ ): FrontmatterMap {
1650
+ const meta: FrontmatterMap = { ...page.frontmatter };
1651
+ if (!trusted || foreign) {
1652
+ for (const key of FOREIGN_MACHINERY_KEYS) delete meta[key];
1653
+ }
1654
+ if (!foreign) {
1655
+ // The raw keys are this system's namespace, so the restore keys on
1656
+ // the producer alone - not on the operator's vouch. A forged
1657
+ // own-producer claim without --trusted still lands in the review
1658
+ // lane, where restoring the recorded status promotes nothing.
1659
+ restoreRawOkfKeys(meta);
1660
+ } else {
1661
+ // A foreign bundle's pages shed the raw keys and the raw-carry
1662
+ // marker: honoured on no path, kept on none either - a foreign
1663
+ // bundle must not plant stray restore machinery into the vault.
1664
+ for (const { raw } of RAW_OKF_KEYS) delete meta[raw];
1665
+ delete meta[RAW_CARRY_KEY];
1666
+ }
1667
+ if (foreign) {
1668
+ if (meta[PRODUCER_KEY] === undefined) meta[PRODUCER_KEY] = producer;
1669
+ // Preserve the raw foreign type: prefer the bundle's recorded
1670
+ // foreign_type, else the page's declared kind at import time.
1671
+ if (meta[FOREIGN_TYPE_KEY] === undefined) {
1672
+ meta[FOREIGN_TYPE_KEY] = page.entry.foreign_type ?? page.entry.kind;
1673
+ }
1674
+ meta[IMPORTED_AT_KEY] = nowIso;
1675
+ }
1676
+ if (!trusted) meta[REVIEW_KEY] = "pending";
1677
+ return meta;
1678
+ }
1679
+
1680
+ /**
1681
+ * Import a parsed bundle into the vault. See {@link OkfImportOptions} for
1682
+ * the trust gradient. Each target path is funnelled through
1683
+ * {@link ensureInsideVault} so a hostile recorded path cannot escape the
1684
+ * vault root. In review mode an existing target is left untouched
1685
+ * (reported under `skipped`); in trusted mode it is overwritten (the
1686
+ * round-trip contract is "restore the recorded state").
1687
+ */
1688
+ export function importOkfBundle(
1689
+ vault: string,
1690
+ bundle: ParsedOkfBundle,
1691
+ opts: OkfImportOptions = {},
1692
+ ): OkfImportResult {
1693
+ // Lane write guard: the vault identity guard on an unswitched machine.
1694
+ // Every page this import writes lands in the user's vault (OKF Review/
1695
+ // or a trusted user path), so a store-only machine runs the vault
1696
+ // adapter's guard once up front too: a frozen or swapped vault is
1697
+ // refused before the walk, as it is unswitched.
1698
+ assertLaneWrite(vault);
1699
+ if (lanePagesInStore(vault)) assertNoteVaultForWrite(vault, "okf import");
1700
+ const trusted = opts.trusted === true;
1701
+ const nowIso = isoSecond(opts.now ?? new Date());
1702
+ const written: string[] = [];
1703
+ const skipped: string[] = [];
1704
+ const errors: { path: string; message: string }[] = [];
1705
+
1706
+ for (const page of bundle.pages) {
1707
+ // The lane check runs BEFORE any join: a recorded path that is not a
1708
+ // clean vault-relative POSIX path (or, in trusted mode, reaches into
1709
+ // Brain machinery) is reported as an error and never touches disk.
1710
+ const refusal = okfTargetRefusal(page.entry.path, trusted);
1711
+ if (refusal !== null) {
1712
+ errors.push({ path: page.entry.path, message: refusal });
1713
+ continue;
1714
+ }
1715
+ const targetRel = trusted ? page.entry.path : posix.join(OKF_REVIEW_REL, page.entry.path);
1716
+ let abs: string;
1717
+ try {
1718
+ abs = ensureInsideVault(join(vault, targetRel), vault);
1719
+ } catch (exc) {
1720
+ errors.push({ path: targetRel, message: (exc as Error).message ?? String(exc) });
1721
+ continue;
1722
+ }
1723
+ if (!trusted && lanePageExists(vault, abs)) {
1724
+ skipped.push(targetRel);
1725
+ continue;
1726
+ }
1727
+ const meta: FrontmatterMap = {
1728
+ ...importFrontmatter(page, bundle.manifest.producer, bundle.foreign, trusted, nowIso),
1729
+ ...opts.provenance,
1730
+ };
1731
+ try {
1732
+ // overwrite: trusted closes the TOCTOU window in review mode: if a
1733
+ // file appears between the existence check above and this write,
1734
+ // the exclusive create throws EEXIST instead of clobbering it. A
1735
+ // `Brain/` page is a lane record once switched; a user page is a
1736
+ // file, behind the vault adapter's guard.
1737
+ writeLanePage(vault, abs, meta, page.body, { overwrite: trusted });
1738
+ written.push(targetRel);
1739
+ } catch (exc) {
1740
+ if (!trusted && (exc as NodeJS.ErrnoException).code === "EEXIST") {
1741
+ skipped.push(targetRel);
1742
+ continue;
1743
+ }
1744
+ errors.push({ path: targetRel, message: (exc as Error).message ?? String(exc) });
1745
+ }
1746
+ }
1747
+
1748
+ return {
1749
+ written,
1750
+ skipped,
1751
+ errors,
1752
+ foreign: bundle.foreign,
1753
+ mode: trusted ? "trusted" : "review",
1754
+ };
1755
+ }