somora 2026.930.1

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 (404) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/bin/node-version.d.mts +3 -0
  4. package/bin/node-version.mjs +45 -0
  5. package/bin/somora.mjs +77 -0
  6. package/config.example.yaml +896 -0
  7. package/docs/agents.md +677 -0
  8. package/docs/api.md +3194 -0
  9. package/docs/browser.md +317 -0
  10. package/docs/builder.md +331 -0
  11. package/docs/cache-strategy.md +373 -0
  12. package/docs/compaction.md +253 -0
  13. package/docs/display.md +154 -0
  14. package/docs/dream-phases.md +891 -0
  15. package/docs/files.md +387 -0
  16. package/docs/imagegen.md +366 -0
  17. package/docs/images/somora-hero.png +0 -0
  18. package/docs/images/somora-mobile-2026-05-23.png +0 -0
  19. package/docs/images/somora-tui-2026-05-23.png +0 -0
  20. package/docs/images/somora-web-2026-05-23.png +0 -0
  21. package/docs/index.md +178 -0
  22. package/docs/lsp.md +93 -0
  23. package/docs/mcp.md +332 -0
  24. package/docs/memory.md +407 -0
  25. package/docs/mobile.md +310 -0
  26. package/docs/models.md +379 -0
  27. package/docs/projects.md +425 -0
  28. package/docs/realtime-voice.md +293 -0
  29. package/docs/resources.md +230 -0
  30. package/docs/sampling.md +128 -0
  31. package/docs/security.md +189 -0
  32. package/docs/sentinel.md +295 -0
  33. package/docs/setup.md +1217 -0
  34. package/docs/skills.md +501 -0
  35. package/docs/team.md +189 -0
  36. package/docs/thinking.md +463 -0
  37. package/docs/tmux.md +399 -0
  38. package/docs/tools.md +117 -0
  39. package/docs/videogen.md +191 -0
  40. package/docs/voice.md +288 -0
  41. package/docs/web.md +893 -0
  42. package/docs/wiki.md +583 -0
  43. package/npm-shrinkwrap.json +5670 -0
  44. package/package.json +116 -0
  45. package/src/attachments/store.ts +196 -0
  46. package/src/browser/change-stream.ts +31 -0
  47. package/src/browser/display.ts +108 -0
  48. package/src/browser/policy.ts +121 -0
  49. package/src/browser/screencast.ts +374 -0
  50. package/src/browser/service.ts +1337 -0
  51. package/src/browser/session.ts +15 -0
  52. package/src/browser/snapshot.ts +40 -0
  53. package/src/cli/auth.ts +117 -0
  54. package/src/cli/codex.ts +41 -0
  55. package/src/cli/lsp.ts +71 -0
  56. package/src/cli/resolvers/clawhub.ts +400 -0
  57. package/src/cli/setup.ts +835 -0
  58. package/src/cli/skill.ts +619 -0
  59. package/src/cli/somora.ts +548 -0
  60. package/src/cli/systemd-unit.ts +72 -0
  61. package/src/cli/team.ts +148 -0
  62. package/src/cli/tui/activity-stream.ts +121 -0
  63. package/src/cli/tui/api.ts +479 -0
  64. package/src/cli/tui/app.tsx +1169 -0
  65. package/src/cli/tui/autocomplete.tsx +55 -0
  66. package/src/cli/tui/commands.ts +913 -0
  67. package/src/cli/tui/dream-glyphs.ts +22 -0
  68. package/src/cli/tui/footer.tsx +15 -0
  69. package/src/cli/tui/format.ts +28 -0
  70. package/src/cli/tui/header.tsx +279 -0
  71. package/src/cli/tui/index.tsx +120 -0
  72. package/src/cli/tui/markdown.tsx +63 -0
  73. package/src/cli/tui/sampling.ts +162 -0
  74. package/src/cli/tui/separator.tsx +13 -0
  75. package/src/cli/tui/state.ts +42 -0
  76. package/src/cli/tui/stream.ts +330 -0
  77. package/src/cli/tui/thinking-text.ts +54 -0
  78. package/src/cli/tui/turn-views.tsx +499 -0
  79. package/src/cli/tui/types.ts +410 -0
  80. package/src/cli/tui/work-queue.ts +161 -0
  81. package/src/cli/update-args.ts +55 -0
  82. package/src/cli/wiki.ts +406 -0
  83. package/src/compaction/index.ts +28 -0
  84. package/src/compaction/midturn.ts +210 -0
  85. package/src/compaction/policy.ts +154 -0
  86. package/src/compaction/summarize.ts +691 -0
  87. package/src/compaction/template.ts +90 -0
  88. package/src/compaction/types.ts +148 -0
  89. package/src/config/loader.ts +276 -0
  90. package/src/config/reload.ts +43 -0
  91. package/src/config/types.ts +2292 -0
  92. package/src/dream/deep-actions.ts +324 -0
  93. package/src/dream/deep-dispatcher.ts +237 -0
  94. package/src/dream/deep-llm.ts +388 -0
  95. package/src/dream/deep-prompts.ts +106 -0
  96. package/src/dream/deep-runner.ts +757 -0
  97. package/src/dream/deep-skip-cache.ts +199 -0
  98. package/src/dream/deep-worker.ts +229 -0
  99. package/src/dream/json-salvage.ts +34 -0
  100. package/src/dream/judge.ts +188 -0
  101. package/src/dream/loop-state.ts +286 -0
  102. package/src/dream/lucid-actions.ts +303 -0
  103. package/src/dream/lucid-batches.ts +94 -0
  104. package/src/dream/lucid-prompt.ts +82 -0
  105. package/src/dream/lucid-runner.ts +744 -0
  106. package/src/dream/lucid-storage.ts +277 -0
  107. package/src/dream/lucid-structure.ts +102 -0
  108. package/src/dream/lucid-types.ts +137 -0
  109. package/src/dream/lucid-worker.ts +224 -0
  110. package/src/dream/rem-dedup.ts +502 -0
  111. package/src/dream/rem-extract.ts +782 -0
  112. package/src/dream/rem-reset-run.ts +67 -0
  113. package/src/dream/rem-runner.ts +696 -0
  114. package/src/dream/rem-worker.ts +527 -0
  115. package/src/dream/review-window.ts +71 -0
  116. package/src/dream/scheduler-state.ts +129 -0
  117. package/src/dream/storage.ts +497 -0
  118. package/src/dream/types.ts +133 -0
  119. package/src/dream/wiki-context.ts +133 -0
  120. package/src/engine/a2a.ts +33 -0
  121. package/src/engine/availability.ts +63 -0
  122. package/src/engine/claude-cli.ts +969 -0
  123. package/src/engine/codex-app-server-client.ts +294 -0
  124. package/src/engine/codex-bin.ts +49 -0
  125. package/src/engine/codex-cli.ts +1014 -0
  126. package/src/engine/codex-dynamic-tools.ts +239 -0
  127. package/src/engine/codex-home.ts +63 -0
  128. package/src/engine/codex-thread-config.ts +74 -0
  129. package/src/engine/context-budget.ts +257 -0
  130. package/src/engine/engine-meta-labels.ts +211 -0
  131. package/src/engine/grok-cli.ts +941 -0
  132. package/src/engine/inline-think.ts +59 -0
  133. package/src/engine/model-availability.ts +105 -0
  134. package/src/engine/openai-compatible.ts +2464 -0
  135. package/src/engine/reasoning-retry.ts +83 -0
  136. package/src/engine/registry.ts +13 -0
  137. package/src/engine/replay.ts +195 -0
  138. package/src/engine/sampling.ts +90 -0
  139. package/src/engine/thinking-params.ts +264 -0
  140. package/src/engine/types.ts +269 -0
  141. package/src/engine/user-tag.ts +24 -0
  142. package/src/imagegen/aspect.ts +128 -0
  143. package/src/imagegen/generate.ts +642 -0
  144. package/src/imagegen/references.ts +75 -0
  145. package/src/imagegen/types.ts +154 -0
  146. package/src/lsp/client.ts +183 -0
  147. package/src/lsp/fake-server.helper.mjs +42 -0
  148. package/src/lsp/format.ts +29 -0
  149. package/src/lsp/index.ts +21 -0
  150. package/src/lsp/manager.ts +238 -0
  151. package/src/lsp/registry.ts +151 -0
  152. package/src/mcp/config.ts +117 -0
  153. package/src/mcp/hub/audit.ts +55 -0
  154. package/src/mcp/hub/bridge.ts +115 -0
  155. package/src/mcp/hub/catalog.ts +69 -0
  156. package/src/mcp/hub/credentials.ts +406 -0
  157. package/src/mcp/hub/env-expand.ts +14 -0
  158. package/src/mcp/hub/manager.ts +770 -0
  159. package/src/mcp/hub/normalize.ts +213 -0
  160. package/src/mcp/server.ts +368 -0
  161. package/src/mcp/tool-schema.ts +20 -0
  162. package/src/media/capabilities.ts +392 -0
  163. package/src/media/records.ts +175 -0
  164. package/src/media/store.ts +217 -0
  165. package/src/media/types.ts +69 -0
  166. package/src/memory/chunking.ts +168 -0
  167. package/src/memory/embeddings.ts +262 -0
  168. package/src/memory/index.ts +15 -0
  169. package/src/memory/inject.ts +197 -0
  170. package/src/memory/manager.ts +996 -0
  171. package/src/memory/registry.ts +176 -0
  172. package/src/memory/rescan.ts +101 -0
  173. package/src/memory/retrieval.ts +586 -0
  174. package/src/memory/shared-index.ts +372 -0
  175. package/src/memory/slug.ts +39 -0
  176. package/src/memory/storage.ts +385 -0
  177. package/src/memory/watcher.ts +134 -0
  178. package/src/multimodal/blocks.ts +101 -0
  179. package/src/multimodal/dimensions.ts +214 -0
  180. package/src/multimodal/load.ts +86 -0
  181. package/src/multimodal/mime.ts +135 -0
  182. package/src/multimodal/pdf-render.ts +80 -0
  183. package/src/multimodal/user-content.ts +266 -0
  184. package/src/persona/files.ts +144 -0
  185. package/src/persona/loader.ts +598 -0
  186. package/src/persona/skill-gating-store.ts +59 -0
  187. package/src/persona/tool-gating-store.ts +113 -0
  188. package/src/projects/focus.ts +186 -0
  189. package/src/projects/prompt-block.ts +106 -0
  190. package/src/projects/scheme.ts +107 -0
  191. package/src/projects/store.ts +144 -0
  192. package/src/projects/types.ts +73 -0
  193. package/src/sentinel/dispatcher.ts +97 -0
  194. package/src/sentinel/schedule.ts +271 -0
  195. package/src/sentinel/scheduler.ts +840 -0
  196. package/src/sentinel/store.ts +259 -0
  197. package/src/sentinel/types.ts +221 -0
  198. package/src/server/activity-stream.ts +160 -0
  199. package/src/server/ask-calls.ts +137 -0
  200. package/src/server/ask-wait-graph.ts +171 -0
  201. package/src/server/async-tasks.ts +199 -0
  202. package/src/server/builder-busy.ts +86 -0
  203. package/src/server/builder-prompt.ts +204 -0
  204. package/src/server/builder-questions.ts +117 -0
  205. package/src/server/builder-session.ts +249 -0
  206. package/src/server/chat-aborts.ts +83 -0
  207. package/src/server/claude-config-dir.ts +71 -0
  208. package/src/server/claude-credential-sync.ts +454 -0
  209. package/src/server/env-file.ts +100 -0
  210. package/src/server/env.ts +115 -0
  211. package/src/server/heal-session.ts +151 -0
  212. package/src/server/history-page.ts +46 -0
  213. package/src/server/index.ts +7244 -0
  214. package/src/server/lockfile.ts +89 -0
  215. package/src/server/logger.ts +67 -0
  216. package/src/server/logs.ts +187 -0
  217. package/src/server/loopback-fetch.ts +130 -0
  218. package/src/server/openai-client.ts +89 -0
  219. package/src/server/prompt-assembly.ts +334 -0
  220. package/src/server/restart-reconcile.ts +139 -0
  221. package/src/server/run-turn-fallback.ts +275 -0
  222. package/src/server/run-turn-types.ts +91 -0
  223. package/src/server/run-turn.ts +1474 -0
  224. package/src/server/sanitize-assistant-text.ts +112 -0
  225. package/src/server/session-export.ts +220 -0
  226. package/src/server/session-queue.ts +376 -0
  227. package/src/server/session-workdir.ts +49 -0
  228. package/src/server/sse-h2-safe.ts +61 -0
  229. package/src/server/sse-liveness.ts +162 -0
  230. package/src/server/sse-serializer.ts +161 -0
  231. package/src/server/start-turn.ts +249 -0
  232. package/src/server/steer-inbox.ts +107 -0
  233. package/src/server/tls-keeper.ts +153 -0
  234. package/src/server/tool-format.ts +167 -0
  235. package/src/server/turn-framing.ts +52 -0
  236. package/src/server/turn-origin-kind.ts +74 -0
  237. package/src/server/turn-origin.ts +40 -0
  238. package/src/server/work-ledger.ts +975 -0
  239. package/src/server/workspace.ts +114 -0
  240. package/src/setup/config-edit.ts +201 -0
  241. package/src/setup/presets.ts +71 -0
  242. package/src/setup/prompt.ts +163 -0
  243. package/src/setup/tailscale.ts +44 -0
  244. package/src/skills/bin-checks.ts +227 -0
  245. package/src/skills/bootstrap.ts +347 -0
  246. package/src/skills/env-scope.ts +175 -0
  247. package/src/skills/gating.ts +71 -0
  248. package/src/skills/lint.ts +202 -0
  249. package/src/skills/load.ts +368 -0
  250. package/src/skills/path-helpers.ts +102 -0
  251. package/src/skills/registry.ts +178 -0
  252. package/src/ssh/exec.ts +142 -0
  253. package/src/ssh/index.ts +12 -0
  254. package/src/ssh/known-hosts.ts +109 -0
  255. package/src/ssh/pool.ts +307 -0
  256. package/src/storage/sessions.ts +602 -0
  257. package/src/team/render.ts +149 -0
  258. package/src/team/resolve.ts +122 -0
  259. package/src/team/store.ts +124 -0
  260. package/src/team/types.ts +111 -0
  261. package/src/team/write.ts +95 -0
  262. package/src/testing/isolated-home.mts +46 -0
  263. package/src/tmux/attention-watcher.ts +272 -0
  264. package/src/tmux/attention.ts +336 -0
  265. package/src/tmux/list.ts +91 -0
  266. package/src/tmux/origin-store.ts +102 -0
  267. package/src/tmux/tui-markers.ts +267 -0
  268. package/src/tools/agents/ask-cancel.ts +94 -0
  269. package/src/tools/agents/ask-result.ts +235 -0
  270. package/src/tools/agents/ask.ts +704 -0
  271. package/src/tools/agents/builder-dispatch.ts +217 -0
  272. package/src/tools/agents/images.ts +104 -0
  273. package/src/tools/agents/index.ts +42 -0
  274. package/src/tools/agents/long-task-timeouts.ts +39 -0
  275. package/src/tools/agents/session-list.ts +136 -0
  276. package/src/tools/agents/session-model.ts +106 -0
  277. package/src/tools/agents/spawn.ts +845 -0
  278. package/src/tools/agents/status.ts +589 -0
  279. package/src/tools/browser/index.ts +6 -0
  280. package/src/tools/browser/ops.ts +145 -0
  281. package/src/tools/browser/tools.ts +184 -0
  282. package/src/tools/builder/short-descriptions.ts +80 -0
  283. package/src/tools/builder/tools.ts +222 -0
  284. package/src/tools/docs/index.ts +1 -0
  285. package/src/tools/docs/tools.ts +228 -0
  286. package/src/tools/dream/index.ts +11 -0
  287. package/src/tools/dream/tools.ts +1002 -0
  288. package/src/tools/exec/allowlist.ts +233 -0
  289. package/src/tools/exec/background-detach.helper.mts +27 -0
  290. package/src/tools/exec/blacklist.ts +336 -0
  291. package/src/tools/exec/concurrency.ts +150 -0
  292. package/src/tools/exec/fit-output.ts +82 -0
  293. package/src/tools/exec/index.ts +7 -0
  294. package/src/tools/exec/internal-env.ts +89 -0
  295. package/src/tools/exec/job-store.ts +403 -0
  296. package/src/tools/exec/local.ts +649 -0
  297. package/src/tools/exec/remote.ts +399 -0
  298. package/src/tools/exec/tools.ts +934 -0
  299. package/src/tools/file/analyze.ts +378 -0
  300. package/src/tools/file/index.ts +2 -0
  301. package/src/tools/file/local.ts +707 -0
  302. package/src/tools/file/lsp-hook.ts +72 -0
  303. package/src/tools/file/persona-guard.ts +61 -0
  304. package/src/tools/file/policy.ts +292 -0
  305. package/src/tools/file/read-format.ts +129 -0
  306. package/src/tools/file/remote.ts +680 -0
  307. package/src/tools/file/replace.ts +507 -0
  308. package/src/tools/file/search-window.ts +224 -0
  309. package/src/tools/file/tools.ts +658 -0
  310. package/src/tools/file/write-scope.ts +182 -0
  311. package/src/tools/gating.ts +106 -0
  312. package/src/tools/image/budget.ts +82 -0
  313. package/src/tools/image/index.ts +7 -0
  314. package/src/tools/image/tools.ts +601 -0
  315. package/src/tools/index.ts +99 -0
  316. package/src/tools/memory/index.ts +12 -0
  317. package/src/tools/memory/tools.ts +399 -0
  318. package/src/tools/projects/index.ts +1 -0
  319. package/src/tools/projects/tools.ts +643 -0
  320. package/src/tools/registry.ts +427 -0
  321. package/src/tools/resources/index.ts +8 -0
  322. package/src/tools/resources/tools.ts +176 -0
  323. package/src/tools/resources/visibility.ts +60 -0
  324. package/src/tools/sentinel/index.ts +1 -0
  325. package/src/tools/sentinel/tools.ts +592 -0
  326. package/src/tools/skill/index.ts +4 -0
  327. package/src/tools/skill/tools.ts +285 -0
  328. package/src/tools/time/index.ts +5 -0
  329. package/src/tools/time/tools.ts +123 -0
  330. package/src/tools/tmux/index.ts +1 -0
  331. package/src/tools/tmux/local.ts +277 -0
  332. package/src/tools/tmux/remote.ts +168 -0
  333. package/src/tools/tmux/tools.ts +1064 -0
  334. package/src/tools/tool-output.ts +97 -0
  335. package/src/tools/types.ts +227 -0
  336. package/src/tools/video/index.ts +1 -0
  337. package/src/tools/video/tools.ts +425 -0
  338. package/src/tools/web/fetch.ts +337 -0
  339. package/src/tools/web/index.ts +4 -0
  340. package/src/tools/web/tools.ts +186 -0
  341. package/src/tools/wiki/index.ts +1 -0
  342. package/src/tools/wiki/tools.ts +445 -0
  343. package/src/tts/cache-gc.ts +128 -0
  344. package/src/tts/prepare-for-tts.ts +114 -0
  345. package/src/tts/service.ts +332 -0
  346. package/src/types/events.ts +695 -0
  347. package/src/types/turn-origin.ts +53 -0
  348. package/src/version.ts +21 -0
  349. package/src/videogen/dialects.ts +222 -0
  350. package/src/videogen/generate.ts +484 -0
  351. package/src/videogen/jobs.ts +178 -0
  352. package/src/videogen/runner.ts +125 -0
  353. package/src/videogen/wake.ts +119 -0
  354. package/src/voice/realtime/call.ts +948 -0
  355. package/src/voice/realtime/consult.ts +293 -0
  356. package/src/voice/realtime/fake-provider.ts +134 -0
  357. package/src/voice/realtime/manager.ts +384 -0
  358. package/src/voice/realtime/openai-provider.ts +471 -0
  359. package/src/voice/realtime/persona.ts +227 -0
  360. package/src/voice/realtime/session-match.ts +116 -0
  361. package/src/voice/realtime/types.ts +182 -0
  362. package/src/wiki/conflict.ts +113 -0
  363. package/src/wiki/explorer.ts +578 -0
  364. package/src/wiki/index-builder.ts +172 -0
  365. package/src/wiki/language.ts +134 -0
  366. package/src/wiki/log-builder.ts +150 -0
  367. package/src/wiki/map.ts +258 -0
  368. package/src/wiki/migration/analyze.ts +304 -0
  369. package/src/wiki/migration/execute.ts +689 -0
  370. package/src/wiki/migration/refine.ts +402 -0
  371. package/src/wiki/migration/store.ts +100 -0
  372. package/src/wiki/move-page.ts +57 -0
  373. package/src/wiki/structure-file.ts +192 -0
  374. package/src/wiki/taxonomy.ts +140 -0
  375. package/src/wiki/templates.ts +163 -0
  376. package/src/wiki/types.ts +133 -0
  377. package/templates/skills/README.md +24 -0
  378. package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
  379. package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
  380. package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
  381. package/templates/skills/_templates/default/SKILL.md +25 -0
  382. package/templates/skills/builder-handover/SKILL.md +96 -0
  383. package/templates/skills/builder-handover/assets/ORDER.md +12 -0
  384. package/templates/skills/skill-author/SKILL.md +110 -0
  385. package/tsconfig.json +22 -0
  386. package/web/dist/assets/index-BaVv6pB2.js +631 -0
  387. package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
  388. package/web/dist/assets/index-V3FV3Z25.css +32 -0
  389. package/web/dist/favicon.svg +8 -0
  390. package/web/dist/index.html +20 -0
  391. package/web/package.json +36 -0
  392. package/web/tsconfig.json +25 -0
  393. package/web-mobile/dist/apple-touch-icon.png +0 -0
  394. package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
  395. package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
  396. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
  397. package/web-mobile/dist/favicon.svg +8 -0
  398. package/web-mobile/dist/icon-192.png +0 -0
  399. package/web-mobile/dist/icon-512.png +0 -0
  400. package/web-mobile/dist/index.html +27 -0
  401. package/web-mobile/dist/manifest.webmanifest +32 -0
  402. package/web-mobile/dist/service-worker.js +90 -0
  403. package/web-mobile/package.json +28 -0
  404. package/web-mobile/tsconfig.json +25 -0
@@ -0,0 +1,996 @@
1
+ // Per-agent memory manager. Public surface for memory operations:
2
+ // - init() / close() — lifecycle
3
+ // - reindex(file) — read markdown + chunk + embed + store
4
+ // - reindexAll() — full sweep over watched roots
5
+ // - search(query, opts) — hybrid retrieval
6
+ // - listNotes(filter?) — list memory notes (no content)
7
+ // - getNote(slug) — read one note's markdown
8
+ // - writeNote(slug, body, frontmatter?) — create/replace memory note
9
+ // - deleteNote(slug) — remove memory note
10
+ //
11
+ // One instance per (agent, source-set). Server constructs one for each
12
+ // agent on first reference and caches it.
13
+
14
+ import { createHash } from 'node:crypto';
15
+ import { isStructureFileName } from '../wiki/structure-file.ts';
16
+
17
+ /** `reportsFolder()` in src/wiki/migration/execute.ts, per language. */
18
+ const REPORT_ARCHIVE_DIRS = ['berichte', 'reports'];
19
+ import { mkdir, readFile, readdir, stat, unlink, writeFile } from 'node:fs/promises';
20
+ import { homedir } from 'node:os';
21
+ import { dirname, join, relative } from 'node:path';
22
+ import matter from 'gray-matter';
23
+ import type { MemoryConfig } from '../config/types.ts';
24
+ import { logger } from '../server/logger.ts';
25
+ import { chunkMarkdown } from './chunking.ts';
26
+ import { resolveEmbeddingProvider, type EmbeddingProvider } from './embeddings.ts';
27
+ import { blendEmbeddings, contentTerms, hybridSearch, type Hit, type SearchTarget } from './retrieval.ts';
28
+ import type { SharedIndex } from './shared-index.ts';
29
+ import {
30
+ closeMemoryDb,
31
+ deleteFile as dbDeleteFile,
32
+ ensureVecTable,
33
+ listAllFiles,
34
+ openMemoryDb,
35
+ pruneOrphanVecRows,
36
+ replaceFileChunks,
37
+ upsertFile,
38
+ type MemoryDb,
39
+ } from './storage.ts';
40
+ import { RescanLoop } from './rescan.ts';
41
+ import { MarkdownWatcher, type FileEvent } from './watcher.ts';
42
+
43
+ const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
44
+
45
+ const SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
46
+
47
+ /** Per-entry description budget in the stage-2 wiki overview. */
48
+ const WIKI_OVERVIEW_DESC_CHARS = 100;
49
+
50
+ /** `## Heading` — starts a section of the wiki index. */
51
+ const WIKI_INDEX_SECTION_RE = /^##\s+(.+?)\s*$/;
52
+
53
+ /**
54
+ * A wiki-index list item: `- [[pfad/seite]] — description`.
55
+ *
56
+ * Anchored, and it captures only the FIRST wikilink of the line. Links
57
+ * further along are prose (`… gehört zu [[personen/xy|Renes]] Team`),
58
+ * not pages.
59
+ */
60
+ const WIKI_INDEX_ENTRY_RE = /^[-*]\s*(\[\[[^\]|]+(?:\|[^\]]*)?\]\])\s*(?:[—–-]\s*)?(.*)$/;
61
+
62
+ /** One `## Section` of the wiki index plus the pages listed under it. */
63
+ interface WikiIndexSection {
64
+ title: string;
65
+ entries: Array<{ link: string; desc: string }>;
66
+ }
67
+
68
+ /**
69
+ * Parse a Dream-B `index.md` into sections and page entries.
70
+ *
71
+ * The shortener this replaced ran a global `/\[\[[^\]]+\]\]/g` over each
72
+ * line, which counted description prose as pages. On the reference wiki
73
+ * (2026-07-22, 258 pages in 25 sections) that turned a 30-slot budget
74
+ * into 22 distinct pages from 7 sections — `Projekte` (60 pages),
75
+ * `Wissen` (75) and `Infrastruktur` (26) never appeared at all, because
76
+ * the sections are emitted alphabetically and the budget ran out at "B".
77
+ * Matching only the leading link removes the duplicates by construction.
78
+ *
79
+ * Returns [] when the file isn't in this shape; the caller falls back to
80
+ * a plain truncation rather than inventing structure.
81
+ */
82
+ function parseWikiIndex(raw: string): WikiIndexSection[] {
83
+ const sections: WikiIndexSection[] = [];
84
+ let current: WikiIndexSection | null = null;
85
+ for (const line of raw.split('\n')) {
86
+ const trimmed = line.trim();
87
+ const heading = WIKI_INDEX_SECTION_RE.exec(trimmed);
88
+ if (heading) {
89
+ current = { title: heading[1]!, entries: [] };
90
+ sections.push(current);
91
+ continue;
92
+ }
93
+ if (!current) continue;
94
+ const entry = WIKI_INDEX_ENTRY_RE.exec(trimmed);
95
+ if (entry) current.entries.push({ link: entry[1]!, desc: entry[2]!.trim() });
96
+ }
97
+ return sections.filter((s) => s.entries.length > 0);
98
+ }
99
+
100
+ function clip(s: string, max: number): string {
101
+ return s.length <= max ? s : `${s.slice(0, max).trimEnd()}…`;
102
+ }
103
+
104
+ /**
105
+ * Shorten a wiki `index.md` to fit `maxChars`. Pure — exported so the
106
+ * stage ladder is testable without a MemoryManager instance.
107
+ *
108
+ * Four stages, each a strictly lower information density than the last,
109
+ * but every one of them covering the WHOLE wiki:
110
+ *
111
+ * 1. index.md verbatim (small wiki)
112
+ * 2. sections + pages + clipped descriptions
113
+ * 3. sections + bare page links
114
+ * 4. section names + page counts (very large wiki)
115
+ *
116
+ * Stage 4 is a taxonomy, not a sample, and that is the point. Knowing
117
+ * "there is a Projekte section with 60 pages" is what makes an agent
118
+ * reach for `memory_search`; a partial list of page names implies the
119
+ * listed pages are all there is, which is worse than no overview.
120
+ */
121
+ export function renderWikiOverview(
122
+ raw: string,
123
+ opts: { maxChars: number; topNSlugs: number },
124
+ ): string {
125
+ // Stage 1 — fits as-is.
126
+ if (raw.length <= opts.maxChars) return raw.trimEnd();
127
+
128
+ const sections = parseWikiIndex(raw);
129
+ if (sections.length === 0) {
130
+ // Index isn't in the conventional Dream-B shape. Hard-truncate
131
+ // instead of guessing: the head of the file is at least structured
132
+ // markdown, which is more use than a bag of extracted tokens.
133
+ return `${raw.slice(0, opts.maxChars).trimEnd()}\n…`;
134
+ }
135
+
136
+ // Stage 2 — everything, descriptions clipped.
137
+ const withDesc = sections
138
+ .map((s) =>
139
+ [
140
+ `## ${s.title}`,
141
+ ...s.entries.map(
142
+ (e) => `- ${e.link}${e.desc ? ` — ${clip(e.desc, WIKI_OVERVIEW_DESC_CHARS)}` : ''}`,
143
+ ),
144
+ ].join('\n'),
145
+ )
146
+ .join('\n\n');
147
+ if (withDesc.length <= opts.maxChars) return withDesc;
148
+
149
+ // Stage 3 — every page still named, descriptions dropped.
150
+ const bare = sections
151
+ .map((s) => `## ${s.title}\n${s.entries.map((e) => e.link).join(' ')}`)
152
+ .join('\n\n');
153
+ if (bare.length <= opts.maxChars) return bare;
154
+
155
+ // Stage 4 — taxonomy + counts. topNSlugs caps how many sections
156
+ // survive; the largest ones win, then they're re-sorted by name so the
157
+ // block reads like the index it stands in for.
158
+ const total = sections.reduce((n, s) => n + s.entries.length, 0);
159
+ const ranked = [...sections]
160
+ .sort((a, b) => b.entries.length - a.entries.length)
161
+ .slice(0, opts.topNSlugs)
162
+ .sort((a, b) => a.title.localeCompare(b.title));
163
+ const dropped = sections.length - ranked.length;
164
+ const taxonomy = [
165
+ `# Wiki sections (${total} pages)`,
166
+ ...ranked.map((s) => `- ${s.title} (${s.entries.length})`),
167
+ ...(dropped > 0 ? [`- … and ${dropped} smaller sections`] : []),
168
+ ].join('\n');
169
+ return taxonomy.length <= opts.maxChars
170
+ ? taxonomy
171
+ : `${taxonomy.slice(0, opts.maxChars).trimEnd()}\n…`;
172
+ }
173
+
174
+ export interface ObsidianSource {
175
+ vaultPath: string;
176
+ }
177
+
178
+ /**
179
+ * Server-global wiki layer (Phase 4) — a designated subfolder inside the
180
+ * vault that Dream-B writes to and all agents share. Files here index
181
+ * with `source: 'wiki'` instead of `source: 'vault'` so retrieval can
182
+ * apply a higher boost. See `private/wiki-design.md`.
183
+ */
184
+ export interface WikiSource {
185
+ /** Absolute path to <vault>/<wikiSubfolder>. */
186
+ absPath: string;
187
+ }
188
+
189
+ /** Source label written to the chunks table and surfaced in hits. */
190
+ export type ChunkSource = 'memory' | 'vault' | 'wiki';
191
+
192
+ export interface ManagerOptions {
193
+ agent: string;
194
+ config: MemoryConfig;
195
+ /** Optional Obsidian read-source. */
196
+ obsidian?: ObsidianSource;
197
+ /** Optional somora-wiki layer (a subfolder of the vault). Only set
198
+ * when config.wiki.enabled is true and obsidian is configured. */
199
+ wiki?: WikiSource;
200
+ /** Optional per-source score multipliers for retrieval. Wired up
201
+ * from config.wiki.search when wiki is enabled. */
202
+ searchBoosts?: { wiki: number; memory: number; vault: number };
203
+ /** Override for the DB file (default `agents/<agent>/memory.db`).
204
+ * The shared index points this at `index/shared.db`. */
205
+ dbPath?: string;
206
+ /** Override for the memory-notes root (default `agents/<agent>/memory`).
207
+ * The shared index points this at an always-empty directory. */
208
+ memoryRoot?: string;
209
+ /**
210
+ * Whether THIS manager sweeps, watches and writes vault/wiki rows.
211
+ * Since the shared index (2026-09) only the shared instance does;
212
+ * agent managers keep `source='memory'` only and read vault/wiki
213
+ * through `shared`. Default false.
214
+ */
215
+ indexVault?: boolean;
216
+ /** `init()` opens the DB and loads the embedder, nothing more — no
217
+ * sweep, no watcher. The shared index uses this so its seed can run
218
+ * before the first sweep; a reader process never sweeps at all. */
219
+ openOnly?: boolean;
220
+ /** Accessor for the shared vault/wiki index. Read at query time, so
221
+ * a manager created while the index was still building switches
222
+ * over the moment it becomes ready. */
223
+ shared?: () => SharedIndex | null;
224
+ }
225
+
226
+ export interface NoteSummary {
227
+ slug: string;
228
+ source: ChunkSource;
229
+ path: string;
230
+ description?: string;
231
+ tags?: string[];
232
+ updatedAt: number;
233
+ }
234
+
235
+ export class MemoryManager {
236
+ private memDb: MemoryDb | null = null;
237
+ private embedder: EmbeddingProvider | null = null;
238
+ private watcher: MarkdownWatcher | null = null;
239
+ private rescan: RescanLoop | null = null;
240
+ private agent: string;
241
+ private cfg: MemoryConfig;
242
+ private obsidian?: ObsidianSource;
243
+ private wiki?: WikiSource;
244
+ private searchBoosts?: { wiki: number; memory: number; vault: number };
245
+ private dbPathOverride?: string;
246
+ private memoryRootOverride?: string;
247
+ private indexVault: boolean;
248
+ private openOnly: boolean;
249
+ private shared?: () => SharedIndex | null;
250
+ private lastEmbedderRetry = 0;
251
+ /** True once ensureEmbedder() failed at least once for this manager —
252
+ * a later success then triggers a reindex sweep so chunks written
253
+ * vector-less while the embedder was down get their embeddings. */
254
+ private embedderWasDown = false;
255
+
256
+ constructor(opts: ManagerOptions) {
257
+ this.agent = opts.agent;
258
+ this.cfg = opts.config;
259
+ this.obsidian = opts.obsidian;
260
+ this.wiki = opts.wiki;
261
+ this.searchBoosts = opts.searchBoosts;
262
+ this.dbPathOverride = opts.dbPath;
263
+ this.memoryRootOverride = opts.memoryRoot;
264
+ this.indexVault = opts.indexVault ?? false;
265
+ this.openOnly = opts.openOnly ?? false;
266
+ this.shared = opts.shared;
267
+ }
268
+
269
+ /** The vault/wiki DB to read from, when the shared index is ready.
270
+ * Null = answer vault/wiki from this manager's own DB (pre-split
271
+ * rows, or this IS the shared instance). */
272
+ private sharedDb(): MemoryDb | null {
273
+ if (this.indexVault || !this.shared) return null;
274
+ const idx = this.shared();
275
+ return idx && idx.ready ? idx.db() : null;
276
+ }
277
+
278
+ /** The DB behind this manager — the shared index reads its counts
279
+ * and build state through this. */
280
+ rawDb(): MemoryDb | null {
281
+ return this.memDb;
282
+ }
283
+
284
+ get memoryRoot(): string {
285
+ if (this.memoryRootOverride) return this.memoryRootOverride;
286
+ // Flat layout: user-facing notes live directly under memory/<slug>.md.
287
+ // Automation-generated stuff (future Dream-findings, internal caches)
288
+ // lives in dot-prefixed subdirs (`memory/.dreams/`, `memory/.cache/`)
289
+ // which the watcher and walker skip by convention.
290
+ return join(SOMORA_HOME, 'agents', this.agent, 'memory');
291
+ }
292
+ get dbPath(): string {
293
+ return this.dbPathOverride ?? join(SOMORA_HOME, 'agents', this.agent, 'memory.db');
294
+ }
295
+
296
+ async init(): Promise<void> {
297
+ if (this.memDb) return;
298
+ await mkdir(this.memoryRoot, { recursive: true });
299
+ this.memDb = openMemoryDb(this.dbPath);
300
+
301
+ // Lazy-init embedder. If it fails (model download blocked, ONNX
302
+ // missing, transient network), we degrade to FTS-only — but
303
+ // ensureEmbedder() will retry on subsequent searches so we recover
304
+ // automatically once the underlying issue is resolved.
305
+ await this.ensureEmbedder();
306
+ if (this.openOnly) return;
307
+
308
+ // Agent managers sweep only their memory notes — a handful of files,
309
+ // instant. The vault (hundreds of files, 85 s to embed for a new
310
+ // agent) is the shared index's job.
311
+ await this.reindexAll();
312
+ this.startWatcher();
313
+ this.startRescan();
314
+ }
315
+
316
+ /** Periodic full sweep (memory.rescanMinutes) for the manager that
317
+ * owns the vault/wiki rows: catches files written on another
318
+ * machine, which arrive on a network share without a watcher event.
319
+ * Idempotent; a no-op for agent managers (their notes are local and
320
+ * watched) and when the interval is 0. */
321
+ startRescan(): void {
322
+ if (this.rescan || !this.indexVault) return;
323
+ const minutes = this.cfg.rescanMinutes ?? 0;
324
+ if (minutes <= 0) return;
325
+ this.rescan = new RescanLoop({
326
+ intervalMs: minutes * 60_000,
327
+ run: () => this.reindexAll(),
328
+ logCtx: { agent: this.agent, roots: this.walkRoots() },
329
+ });
330
+ this.rescan.start();
331
+ }
332
+
333
+ /** Watch this manager's roots for changes. Idempotent. */
334
+ startWatcher(): void {
335
+ if (this.watcher) return;
336
+ const roots = this.walkRoots();
337
+ const ignored = this.buildIgnored();
338
+ this.watcher = new MarkdownWatcher({
339
+ roots,
340
+ ignored,
341
+ onEvent: (e) => this.handleFileEvent(e),
342
+ });
343
+ this.watcher.start();
344
+ }
345
+
346
+ /** Roots this manager indexes: always the memory notes, plus the
347
+ * vault only when it owns the vault/wiki rows. */
348
+ private walkRoots(): string[] {
349
+ const roots = [this.memoryRoot];
350
+ if (this.indexVault && this.obsidian?.vaultPath) roots.push(this.obsidian.vaultPath);
351
+ return roots;
352
+ }
353
+
354
+ private buildIgnored(): Array<(path: string) => boolean> {
355
+ // chokidar 5 evaluates `ignored` against absolute paths. A naive
356
+ // dotfile-regex like `/(^|[\\/])\../` blocks the entire ~/.somora tree
357
+ // because `.somora` itself contains a dot. We therefore go function-
358
+ // based and only exclude components RELATIVE to a watched root.
359
+ const roots = this.walkRoots();
360
+
361
+ return [
362
+ (path: string) => {
363
+ // Never exclude the watched root itself.
364
+ if (roots.includes(path)) return false;
365
+ for (const root of roots) {
366
+ if (path.startsWith(root + '/')) {
367
+ const rel = path.slice(root.length + 1);
368
+ const parts = rel.split('/');
369
+ // Skip dot-prefixed components below the root (.dreams, .cache,
370
+ // .obsidian/, .trash/, .git/, …)
371
+ if (parts.some((c) => c.startsWith('.'))) return true;
372
+ if (isStructureFileName(parts[parts.length - 1]!)) return true;
373
+ if (this.isArchivedReport(path)) return true;
374
+ return false;
375
+ }
376
+ }
377
+ return false;
378
+ },
379
+ ];
380
+ }
381
+
382
+ async close(): Promise<void> {
383
+ if (this.rescan) {
384
+ this.rescan.stop();
385
+ this.rescan = null;
386
+ }
387
+ if (this.watcher) {
388
+ await this.watcher.stop();
389
+ this.watcher = null;
390
+ }
391
+ if (this.memDb) {
392
+ closeMemoryDb(this.memDb);
393
+ this.memDb = null;
394
+ }
395
+ }
396
+
397
+ private requireDb(): MemoryDb {
398
+ if (!this.memDb) throw new Error('MemoryManager not initialized — call init() first');
399
+ return this.memDb;
400
+ }
401
+
402
+ /**
403
+ * Make sure the embedder is loaded. Throttled so a permanent failure
404
+ * (e.g. broken model alias) doesn't hammer retries on every search;
405
+ * but a transient failure (network blip during first-ever download,
406
+ * config change between turns) recovers within ~60s.
407
+ */
408
+ private async ensureEmbedder(): Promise<boolean> {
409
+ if (this.embedder) return true;
410
+ if (!this.memDb) return false;
411
+ const now = Date.now();
412
+ if (now - this.lastEmbedderRetry < 60_000) return false;
413
+ this.lastEmbedderRetry = now;
414
+ try {
415
+ const provider = await resolveEmbeddingProvider(this.cfg.embedding);
416
+ ensureVecTable(this.memDb, provider.dim, provider.name);
417
+ this.embedder = provider;
418
+ logger.info({
419
+ msg: 'memory.embedder_ready',
420
+ agent: this.agent,
421
+ model: provider.name,
422
+ dim: provider.dim,
423
+ });
424
+ if (this.embedderWasDown) {
425
+ // Late recovery (embedder came up on a search, not at init):
426
+ // indexFile()'s `reembed_missing_vec` self-heal only runs inside
427
+ // a reindex sweep, so kick one off now instead of waiting for the
428
+ // next restart or file event. Fire-and-forget: the search that
429
+ // triggered ensureEmbedder() must not block on a full sweep.
430
+ this.embedderWasDown = false;
431
+ logger.info({ msg: 'memory.embedder_recovered_reindex', agent: this.agent });
432
+ void this.reindexAll().catch((err) => {
433
+ logger.warn({
434
+ msg: 'memory.embedder_recovered_reindex_failed',
435
+ agent: this.agent,
436
+ err: (err as Error).message,
437
+ });
438
+ });
439
+ }
440
+ return true;
441
+ } catch (err) {
442
+ this.embedderWasDown = true;
443
+ logger.warn({
444
+ msg: 'memory.embedder_unavailable',
445
+ agent: this.agent,
446
+ err: (err as Error).message,
447
+ hint: 'falling back to FTS-only retrieval; will retry in 60s on next search — see GET /health → memoryEmbedder',
448
+ });
449
+ this.embedder = null;
450
+ return false;
451
+ }
452
+ }
453
+
454
+ private classifySource(path: string): ChunkSource | null {
455
+ if (path.startsWith(this.memoryRoot)) {
456
+ // Memory notes are FLAT by design: only files directly under
457
+ // memoryRoot are memory notes. A note in a subdirectory would get a
458
+ // `sub--note` slug the read/write/delete API can't address (it
459
+ // reconstructs a flat `sub--note.md` path), so a write would create
460
+ // a colliding second file. Ignore subdir files entirely — memory
461
+ // doesn't support folders. (Dot-dirs like `.dreams`/`.cache` are
462
+ // already skipped by the walker; this also covers any non-dot subdir,
463
+ // and — since it's in classifySource — the watcher path too.)
464
+ return isFlatMemoryFile(path, this.memoryRoot) ? 'memory' : null;
465
+ }
466
+ // Vault/wiki rows are written only by the manager that owns them
467
+ // (the shared index). An agent manager ignores vault paths — its
468
+ // watcher never sees them anyway (walkRoots), this is belt and braces.
469
+ if (!this.indexVault) return null;
470
+ // Wiki check goes BEFORE vault since the wiki subfolder lives
471
+ // inside the vault. Order matters: vaultPath would also match.
472
+ if (this.wiki && path.startsWith(this.wiki.absPath)) return 'wiki';
473
+ if (this.obsidian && path.startsWith(this.obsidian.vaultPath)) {
474
+ return 'vault';
475
+ }
476
+ return null;
477
+ }
478
+
479
+ private async handleFileEvent(e: FileEvent): Promise<void> {
480
+ const source = this.classifySource(e.path);
481
+ if (!source) return;
482
+ if (e.kind === 'unlink') {
483
+ dbDeleteFile(this.requireDb(), e.path);
484
+ logger.info({ msg: 'memory.unindex', agent: this.agent, path: e.path });
485
+ return;
486
+ }
487
+ try {
488
+ await this.indexFile(e.path, source);
489
+ } catch (err) {
490
+ logger.warn({
491
+ msg: 'memory.index_failed',
492
+ agent: this.agent,
493
+ path: e.path,
494
+ err: (err as Error).message,
495
+ });
496
+ }
497
+ }
498
+
499
+ /** The wiki migration keeps the pages it folded into others under
500
+ * `<wiki>/logs/berichte/` (`logs/reports/`): their substance now
501
+ * lives in the target pages, so the archive stays out of the search
502
+ * index — otherwise every fact would come back twice. */
503
+ private isArchivedReport(path: string): boolean {
504
+ if (!this.wiki) return false;
505
+ return REPORT_ARCHIVE_DIRS.some((d) => path.startsWith(join(this.wiki!.absPath, 'logs', d) + '/'));
506
+ }
507
+
508
+ /** Walk a directory and yield .md file paths. */
509
+ private async *walkMarkdown(root: string): AsyncGenerator<string> {
510
+ let entries;
511
+ try {
512
+ entries = await readdir(root, { withFileTypes: true });
513
+ } catch (err) {
514
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return;
515
+ throw err;
516
+ }
517
+ for (const e of entries) {
518
+ const full = join(root, e.name);
519
+ if (e.name.startsWith('.')) continue;
520
+ if (e.isDirectory()) {
521
+ yield* this.walkMarkdown(full);
522
+ } else if (e.isFile() && e.name.endsWith('.md')) {
523
+ if (isStructureFileName(e.name)) continue; // the wiki's folder map, not a note
524
+ if (this.isArchivedReport(full)) continue;
525
+ yield full;
526
+ }
527
+ }
528
+ }
529
+
530
+ async reindexAll(): Promise<{ indexed: number; skipped: number }> {
531
+ const memDb = this.requireDb();
532
+ let indexed = 0;
533
+ let skipped = 0;
534
+
535
+ const seen = new Set<string>();
536
+ // Walk memory and vault. Files inside the wiki-subfolder are tagged
537
+ // 'wiki' via classifySource — not via a separate walk root, since
538
+ // the wiki lives inside the vault and would otherwise be visited
539
+ // twice. classifySource checks wiki BEFORE vault.
540
+ const roots = this.walkRoots();
541
+ for (const root of roots) {
542
+ for await (const path of this.walkMarkdown(root)) {
543
+ seen.add(path);
544
+ const source = this.classifySource(path);
545
+ if (!source) continue;
546
+ try {
547
+ const r = await this.indexFile(path, source);
548
+ if (r === 'indexed') indexed++;
549
+ else skipped++;
550
+ } catch (err) {
551
+ logger.warn({
552
+ msg: 'memory.reindex_file_failed',
553
+ path,
554
+ err: (err as Error).message,
555
+ });
556
+ }
557
+ }
558
+ }
559
+
560
+ // Drop rows for files that vanished between runs. An agent manager
561
+ // (indexVault=false) only judges its memory rows: the vault/wiki
562
+ // rows an agent DB carries from before the shared index are not in
563
+ // `seen` because the vault was not walked — they are deliberately
564
+ // left in place (design decision 2026-09-08), just never read.
565
+ for (const f of listAllFiles(memDb, this.indexVault ? undefined : 'memory')) {
566
+ if (!seen.has(f.path)) {
567
+ dbDeleteFile(memDb, f.path);
568
+ logger.info({ msg: 'memory.unindex_stale', path: f.path });
569
+ }
570
+ }
571
+
572
+ // Sweep leftover vector rows whose chunk is gone (ghosts left by a
573
+ // prior FTS-only process that deleted chunks it couldn't purge from
574
+ // chunks_vec). Safe no-op unless the vec extension is loaded.
575
+ const prunedVec = pruneOrphanVecRows(memDb);
576
+ if (prunedVec > 0) {
577
+ logger.info({ msg: 'memory.vec_orphans_pruned', agent: this.agent, pruned: prunedVec });
578
+ }
579
+
580
+ logger.info({ msg: 'memory.reindex_done', agent: this.agent, indexed, skipped });
581
+ return { indexed, skipped };
582
+ }
583
+
584
+ private async indexFile(path: string, source: ChunkSource): Promise<'indexed' | 'skipped'> {
585
+ const memDb = this.requireDb();
586
+ const buf = await readFile(path);
587
+ const stats = await stat(path);
588
+ const hash = createHash('sha256').update(buf).digest('hex').slice(0, 16);
589
+ // Hash check WITHOUT committing — the file row (hash) is written only
590
+ // AFTER the chunks landed. Committing the hash first left a poisoned
591
+ // state on partial failure: hash new + chunks stale → hash-match skips
592
+ // the file forever and the stale chunks never heal.
593
+ const existing = memDb.db
594
+ .prepare(`SELECT hash FROM files WHERE path = ?`)
595
+ .get(path) as { hash: string } | undefined;
596
+ if (existing && existing.hash === hash) {
597
+ // Defensive self-heal: a file row may exist with the current hash
598
+ // while the chunks for it are missing — initial index crashed
599
+ // mid-walk, a schema migration dropped the chunks table without
600
+ // bumping mtimes, or someone manually wiped chunks. Returning
601
+ // 'skipped' on hash-match alone would leave that file stuck
602
+ // forever (next run keeps seeing the same hash). Verify a chunk
603
+ // actually exists; if not, fall through to rebuild. Discovered
604
+ // 2026-05-21 on buffet (238 files indexed, 0 chunks).
605
+ const firstChunk = memDb.db
606
+ .prepare(`SELECT id FROM chunks WHERE file_path = ? LIMIT 1`)
607
+ .get(path) as { id: number } | undefined;
608
+ // An empty page (two 0-byte vault stubs, 2026-09-26) has no chunk
609
+ // row by design — without this it counted as "indexed" on every
610
+ // ten-minute sweep.
611
+ if (!firstChunk && chunkMarkdown(buf.toString('utf8'), this.cfg.chunking).length === 0) return 'skipped';
612
+ if (firstChunk) {
613
+ // Second self-heal: chunks indexed while the embedder was down
614
+ // (or before one was configured) have no vec rows. Hash-match
615
+ // skipped them forever → hybrid search stayed silently BM25-only
616
+ // for those files. Embeddings are all-or-none per file, so
617
+ // point-probing the first chunk's rowid suffices (vec0 supports
618
+ // rowid point queries, same pattern as the delete path).
619
+ const wantsVec = Boolean(this.embedder && memDb.hasVec);
620
+ const hasVecRow = wantsVec
621
+ ? memDb.db
622
+ .prepare(`SELECT rowid FROM chunks_vec WHERE rowid = ?`)
623
+ .get(BigInt(firstChunk.id))
624
+ : null;
625
+ if (!wantsVec || hasVecRow) return 'skipped';
626
+ logger.info({ msg: 'memory.reembed_missing_vec', path });
627
+ }
628
+ }
629
+
630
+ const text = buf.toString('utf8');
631
+ const chunks = chunkMarkdown(text, this.cfg.chunking);
632
+ if (chunks.length === 0) {
633
+ // One transaction: file row (FK parent) + chunk wipe commit or roll
634
+ // back together — see the comment on the main path below.
635
+ memDb.db.transaction(() => {
636
+ upsertFile(memDb, { path, source, hash, mtime: stats.mtimeMs, size: stats.size });
637
+ replaceFileChunks(memDb, path, [], null);
638
+ })();
639
+ return 'indexed';
640
+ }
641
+ // Slug is path relative to the source-root (memory: memoryRoot;
642
+ // wiki: wiki absPath so subfolder name is stripped; vault: vaultPath).
643
+ // Hit-format uses `[source/slug]` so the slug should be stable across
644
+ // sources without redundant prefixes.
645
+ //
646
+ // Wiki preserves `/` separators (e.g. `personen/anna`) to match the
647
+ // Wikilinks Dream-B writes; vault and memory keep the historic `--`
648
+ // convention so existing references don't break.
649
+ const slug = source === 'memory'
650
+ ? slugFromPath(path, this.memoryRoot)
651
+ : source === 'wiki'
652
+ ? slugFromPath(path, this.wiki!.absPath, { keepSeparators: true })
653
+ : slugFromPath(path, this.obsidian!.vaultPath);
654
+
655
+ let embeddings: Float32Array[] | null = null;
656
+ if (this.embedder && memDb.hasVec) {
657
+ try {
658
+ embeddings = await this.embedder.embed(chunks.map((c) => c.text));
659
+ } catch (err) {
660
+ logger.warn({
661
+ msg: 'memory.embed_failed',
662
+ path,
663
+ err: (err as Error).message,
664
+ });
665
+ embeddings = null;
666
+ }
667
+ }
668
+
669
+ // Record the embedder name only when embeddings were actually written —
670
+ // an embed failure falls back to FTS-only rows, and the model column
671
+ // should say so (the vec self-heal above re-embeds them next pass).
672
+ const modelName = embeddings ? this.embedder!.name : 'fts-only';
673
+ // File row + chunk replacement in ONE transaction (replaceFileChunks'
674
+ // inner transaction becomes a savepoint). The file row must come first
675
+ // — chunks.file_path has a FK on files(path) — and atomicity is what
676
+ // prevents the poisoned hash-new/chunks-stale state on crash: either
677
+ // both commit or the old hash stays and the next pass redoes the file.
678
+ memDb.db.transaction(() => {
679
+ upsertFile(memDb, { path, source, hash, mtime: stats.mtimeMs, size: stats.size });
680
+ replaceFileChunks(
681
+ memDb,
682
+ path,
683
+ chunks.map((c) => ({
684
+ file_path: path,
685
+ source,
686
+ slug,
687
+ start_line: c.startLine,
688
+ end_line: c.endLine,
689
+ hash,
690
+ model: modelName,
691
+ text: c.text,
692
+ })),
693
+ embeddings,
694
+ );
695
+ })();
696
+ return 'indexed';
697
+ }
698
+
699
+ // ── Public query surface ──────────────────────────────────────────────
700
+
701
+ async search(
702
+ query: string,
703
+ opts?: {
704
+ limit?: number;
705
+ minScore?: number;
706
+ /** Restrict to specific sources. Undefined or 'all' = no filter. */
707
+ sources?: ChunkSource[] | 'all';
708
+ /**
709
+ * Conversation context that should NUDGE the vector query, not
710
+ * define it: embedded separately and blended into the query
711
+ * embedding at `contextWeight` (default autoInject.historyWeight).
712
+ * BM25 never sees it — keywords come from `query` alone.
713
+ */
714
+ context?: string;
715
+ contextWeight?: number;
716
+ /** With `context`: also run the message-only vector query and
717
+ * keep the better score per chunk (see hybridSearch). Auto-inject
718
+ * sets this whenever the message has a content word. */
719
+ alsoQueryAlone?: boolean;
720
+ /** Override the fusion's BM25 share for this query (vector share
721
+ * is the remainder). Auto-inject raises it for one/two-word
722
+ * questions where the exact match is the whole point. */
723
+ bm25Weight?: number;
724
+ },
725
+ ): Promise<Hit[]> {
726
+ const memDb = this.requireDb();
727
+ // Best-effort retry — recovers from a degraded init the next time the
728
+ // user actually searches.
729
+ await this.ensureEmbedder();
730
+ const limit = opts?.limit ?? this.cfg.autoInject.maxResults;
731
+ const minScore = opts?.minScore ?? this.cfg.autoInject.minScore;
732
+ const sourceFilter =
733
+ opts?.sources && opts.sources !== 'all' && opts.sources.length > 0
734
+ ? opts.sources
735
+ : undefined;
736
+ let queryEmbedding: Float32Array | Float32Array[] | null = null;
737
+ if (this.embedder) {
738
+ try {
739
+ const context = opts?.context?.trim();
740
+ const weight = opts?.contextWeight ?? this.cfg.autoInject.historyWeight;
741
+ if (context && weight > 0) {
742
+ const [q, c] = await this.embedder.embed([query, context]);
743
+ if (q) {
744
+ const blended = blendEmbeddings(q, c ?? null, weight);
745
+ queryEmbedding = opts?.alsoQueryAlone && blended !== q ? [q, blended] : blended;
746
+ }
747
+ } else {
748
+ const [emb] = await this.embedder.embed([query]);
749
+ queryEmbedding = emb ?? null;
750
+ }
751
+ } catch (err) {
752
+ logger.warn({ msg: 'memory.query_embed_failed', err: (err as Error).message });
753
+ }
754
+ }
755
+ // Two DBs once the shared index is ready: own memory notes + the
756
+ // shared vault/wiki. Own DB restricted to 'memory' because a DB
757
+ // from before the split still carries (inert) vault/wiki rows.
758
+ // Until then — or with no vault at all — the own DB answers alone,
759
+ // exactly as before the split.
760
+ const sharedDb = this.sharedDb();
761
+ const targets: SearchTarget[] = sharedDb
762
+ ? [{ memDb, sources: ['memory'] }, { memDb: sharedDb, sources: ['vault', 'wiki'] }]
763
+ : [{ memDb }];
764
+ const bm25Weight = opts?.bm25Weight ?? this.cfg.hybrid.bm25Weight;
765
+ const vectorWeight = opts?.bm25Weight !== undefined ? 1 - opts.bm25Weight : this.cfg.hybrid.vectorWeight;
766
+ return hybridSearch(targets, query, queryEmbedding, {
767
+ vectorWeight,
768
+ bm25Weight,
769
+ queryTerms: contentTerms(query),
770
+ slugMatchBoost: this.cfg.hybrid.slugMatchBoost,
771
+ maxResults: limit,
772
+ minScore,
773
+ ...(this.searchBoosts ? { sourceBoosts: this.searchBoosts } : {}),
774
+ ...(sourceFilter ? { sourceFilter } : {}),
775
+ });
776
+ }
777
+
778
+ async listNotes(filter?: {
779
+ tag?: string;
780
+ /** Restrict to one or more sources. Default: 'memory' (preserves
781
+ * pre-Phase-4 behavior). Pass 'all' for the full union. */
782
+ sources?: ChunkSource[] | 'all';
783
+ /** Filter by slug-prefix. Useful for browsing a wiki subfolder
784
+ * ("personen/") or a vault directory. */
785
+ pathPrefix?: string;
786
+ }): Promise<NoteSummary[]> {
787
+ const memDb = this.requireDb();
788
+ const sources: ChunkSource[] =
789
+ !filter?.sources
790
+ ? ['memory']
791
+ : filter.sources === 'all'
792
+ ? ['memory', 'wiki', 'vault']
793
+ : filter.sources;
794
+
795
+ const sharedDb = this.sharedDb();
796
+ const out: NoteSummary[] = [];
797
+ for (const source of sources) {
798
+ const files = listAllFiles(source !== 'memory' && sharedDb ? sharedDb : memDb, source);
799
+ for (const f of files) {
800
+ try {
801
+ const slug =
802
+ source === 'memory'
803
+ ? slugFromPath(f.path, this.memoryRoot)
804
+ : source === 'wiki'
805
+ ? slugFromPath(f.path, this.wiki!.absPath, { keepSeparators: true })
806
+ : slugFromPath(f.path, this.obsidian!.vaultPath);
807
+ if (filter?.pathPrefix && !slug.startsWith(filter.pathPrefix)) continue;
808
+ const raw = await readFile(f.path, 'utf8');
809
+ const parsed = matter(raw);
810
+ const tags = Array.isArray(parsed.data.tags) ? (parsed.data.tags as string[]) : undefined;
811
+ if (filter?.tag && (!tags || !tags.includes(filter.tag))) continue;
812
+ out.push({
813
+ slug,
814
+ source,
815
+ path: f.path,
816
+ description: typeof parsed.data.description === 'string' ? parsed.data.description : undefined,
817
+ tags,
818
+ updatedAt: f.mtime,
819
+ });
820
+ } catch {
821
+ // Skip unreadable files; don't error the whole list.
822
+ }
823
+ }
824
+ }
825
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
826
+ }
827
+
828
+ /**
829
+ * Read and shorten the wiki's index.md into the topology overview that
830
+ * run-turn snapshots into the session's system prompt. Returns null if
831
+ * the wiki is disabled or has no index.md yet.
832
+ *
833
+ * Shortening ladder lives in `renderWikiOverview`.
834
+ */
835
+ async getWikiOverview(opts: {
836
+ maxChars: number;
837
+ topNSlugs: number;
838
+ }): Promise<string | null> {
839
+ if (!this.wiki) return null;
840
+ const indexPath = join(this.wiki.absPath, 'index.md');
841
+ let raw: string;
842
+ try {
843
+ raw = await readFile(indexPath, 'utf8');
844
+ } catch (err) {
845
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
846
+ throw err;
847
+ }
848
+ return renderWikiOverview(raw, opts);
849
+ }
850
+
851
+ async getNote(slug: string): Promise<{ path: string; markdown: string } | null> {
852
+ if (!SLUG_RE.test(slug)) return null;
853
+ const path = join(this.memoryRoot, `${slug}.md`);
854
+ try {
855
+ const raw = await readFile(path, 'utf8');
856
+ return { path, markdown: raw };
857
+ } catch (err) {
858
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
859
+ throw err;
860
+ }
861
+ }
862
+
863
+ /**
864
+ * Create or replace a memory note. `created` is preserved across rewrites;
865
+ * `updated` is always refreshed. Caller-provided frontmatter merges over
866
+ * existing values. Throws if `opts.mustExist` is set and the file isn't there.
867
+ */
868
+ async writeNote(
869
+ slug: string,
870
+ body: string,
871
+ frontmatter?: Record<string, unknown>,
872
+ opts?: { mustExist?: boolean },
873
+ ): Promise<{ path: string; created: boolean; mode: 'overwrite' }> {
874
+ if (!SLUG_RE.test(slug)) {
875
+ throw new Error(`invalid slug '${slug}' — must match ${SLUG_RE.source}`);
876
+ }
877
+ const path = join(this.memoryRoot, `${slug}.md`);
878
+
879
+ let existingRaw: string | null = null;
880
+ let existing: Record<string, unknown> = {};
881
+ let exists = false;
882
+ try {
883
+ existingRaw = await readFile(path, 'utf8');
884
+ existing = matter(existingRaw).data ?? {};
885
+ exists = true;
886
+ } catch (err) {
887
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
888
+ }
889
+ if (opts?.mustExist && !exists) {
890
+ throw new Error(`note '${slug}' does not exist — use memory_write to create`);
891
+ }
892
+
893
+ // v2.2: stub-pattern is gone. memory_write on an existing memory
894
+ // slug just rewrites the file (caller-controlled). After Deep
895
+ // consolidates a topic into the wiki, the source memory file is
896
+ // DELETED — so a follow-up memory_write on the same slug is a
897
+ // legitimate fresh write that Deep will pick up next run.
898
+
899
+ const now = new Date().toISOString();
900
+ const fm: Record<string, unknown> = {
901
+ created: existing.created ?? now,
902
+ ...existing,
903
+ ...frontmatter,
904
+ updated: now,
905
+ };
906
+ const fmYaml = matter.stringify(body.trimEnd() + '\n', fm);
907
+ await mkdir(dirname(path), { recursive: true });
908
+ await writeFile(path, fmYaml, 'utf8');
909
+ // Watcher will pick up the change and reindex via debounced handler;
910
+ // we don't reindex synchronously here.
911
+ return { path, created: !exists, mode: 'overwrite' };
912
+ }
913
+
914
+ /**
915
+ * Resolve a recall reference like "memory/auto", "wiki/personen/anna",
916
+ * or "vault/Notizen/Foo--Bar" back to the full file content. Uses the
917
+ * chunks table for path lookup so we don't have to reverse-slugify
918
+ * (collision-safe). All three sources route through the same query.
919
+ */
920
+ async getByReference(reference: string): Promise<{
921
+ reference: string;
922
+ source: ChunkSource;
923
+ slug: string;
924
+ path: string;
925
+ markdown: string;
926
+ frontmatter: Record<string, unknown> | null;
927
+ } | null> {
928
+ const slashIdx = reference.indexOf('/');
929
+ if (slashIdx < 0) return null;
930
+ const source = reference.slice(0, slashIdx);
931
+ const slug = reference.slice(slashIdx + 1);
932
+ if (source !== 'memory' && source !== 'vault' && source !== 'wiki') return null;
933
+
934
+ const memDb = this.requireDb();
935
+ const sharedDb = this.sharedDb();
936
+ const lookup = source !== 'memory' && sharedDb ? sharedDb : memDb;
937
+ const row = lookup.db
938
+ .prepare(`SELECT file_path FROM chunks WHERE source = ? AND slug = ? LIMIT 1`)
939
+ .get(source, slug) as { file_path: string } | undefined;
940
+ if (!row) return null;
941
+
942
+ let raw: string;
943
+ try {
944
+ raw = await readFile(row.file_path, 'utf8');
945
+ } catch {
946
+ return null;
947
+ }
948
+ const parsed = matter(raw);
949
+ const fm = parsed.data ?? {};
950
+ return {
951
+ reference,
952
+ source: source as ChunkSource,
953
+ slug,
954
+ path: row.file_path,
955
+ markdown: raw,
956
+ frontmatter: Object.keys(fm).length > 0 ? (fm as Record<string, unknown>) : null,
957
+ };
958
+ }
959
+
960
+ async deleteNote(slug: string): Promise<boolean> {
961
+ if (!SLUG_RE.test(slug)) return false;
962
+ const path = join(this.memoryRoot, `${slug}.md`);
963
+ try {
964
+ await unlink(path);
965
+ return true;
966
+ } catch (err) {
967
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;
968
+ throw err;
969
+ }
970
+ }
971
+ }
972
+
973
+ /** True iff `path` is a note directly under `memoryRoot` (flat), not in a
974
+ * subdirectory. Memory notes are flat by design — a subdir note would get
975
+ * a `sub--note` slug the read/write/delete API can't round-trip (it
976
+ * reconstructs a flat path), so a write creates a colliding second file.
977
+ * Exported for tests. */
978
+ export function isFlatMemoryFile(path: string, memoryRoot: string): boolean {
979
+ const rel = relative(memoryRoot, path);
980
+ if (rel.length === 0 || rel.startsWith('..')) return false; // outside root
981
+ return !rel.includes('/') && !rel.includes('\\'); // no subdirectory
982
+ }
983
+
984
+ function slugFromPath(path: string, root: string, opts?: { keepSeparators?: boolean }): string {
985
+ const rel = relative(root, path);
986
+ // Strip .md extension; replace path separators with `--` so a vault note
987
+ // at `projects/somora/idea.md` becomes slug `projects--somora--idea`.
988
+ //
989
+ // Wiki source overrides via `keepSeparators: true` to preserve `/` —
990
+ // matches the design-doc reference format `[wiki/personen/anna]` and
991
+ // aligns with Obsidian Wikilinks `[[personen/anna]]` that Dream-B will
992
+ // emit. Without this, references and Wikilinks would diverge and
993
+ // confuse the agent.
994
+ const parts = rel.replace(/\.md$/i, '').split(/[/\\]/).filter((s) => s.length > 0);
995
+ return opts?.keepSeparators ? parts.join('/') : parts.join('--');
996
+ }