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,696 @@
1
+ // Dream-Mode runner. The universal driver that orchestrates extraction +
2
+ // storage + status transitions. Used by both manual triggers (/reset) and
3
+ // the future auto-trigger idle worker. Differences between the two reduce
4
+ // to: the trigger field on the DreamMeta, and whether an AbortSignal is
5
+ // passed (auto = signal cancels on user activity; manual = no signal,
6
+ // runs to completion regardless).
7
+
8
+ import { readFile, unlink } from 'node:fs/promises';
9
+ import type { Config, ResolvedModel } from '../config/types.ts';
10
+ import type { MemoryManager } from '../memory/manager.ts';
11
+ import type { RemConfig } from '../persona/loader.ts';
12
+ import { logger } from '../server/logger.ts';
13
+ import { getHistory } from '../storage/sessions.ts';
14
+ import {
15
+ dreamFilePath,
16
+ dreamIdFor,
17
+ pruneFailedDreams,
18
+ readDreamById,
19
+ transitionDreamStatus,
20
+ writeDreamFile,
21
+ } from './storage.ts';
22
+ import { extractFromSession, resolveDreamModel } from './rem-extract.ts';
23
+ import type { DreamFile, DreamMeta, DreamTriggerKind } from './types.ts';
24
+ import { modelRef, modelUnavailable, unavailableReason } from '../engine/model-availability.ts';
25
+ import { effectiveJudgeModel, resolveJudgeModel } from './judge.ts';
26
+ import { applyRemDedup } from './rem-dedup.ts';
27
+ import { loadWikiContext } from './wiki-context.ts';
28
+ import { excludeReviewWindows } from './review-window.ts';
29
+ import { resolveObsidianSource } from '../memory/registry.ts';
30
+ import { join } from 'node:path';
31
+
32
+ export interface RunDreamArgs {
33
+ agent: string;
34
+ /** Source session whose JSONL delta to analyze. */
35
+ sourceSession: string;
36
+ trigger: DreamTriggerKind;
37
+ /**
38
+ * Lower bound (inclusive) of the JSONL range to extract. Use 0 for
39
+ * "from the start of the session". Auto-trigger passes the session's
40
+ * dreamReadThroughTs marker; manual /reset usually passes the same.
41
+ */
42
+ rangeFromTs: number;
43
+ /** Upper bound (inclusive). Date.now() for "all events up to now". */
44
+ rangeThroughTs: number;
45
+ /** Resolved per-agent dream config (model, chunk sizes, timeouts). */
46
+ rem: RemConfig;
47
+ /** Loaded server config — used to resolve dream.model to a ResolvedModel. */
48
+ config: Config;
49
+ /** Per-agent memory manager (already initialized). */
50
+ mgr: MemoryManager;
51
+ /**
52
+ * Optional AbortSignal — auto-trigger sets one and aborts on user
53
+ * activity; manual trigger leaves undefined (run to completion).
54
+ */
55
+ signal?: AbortSignal;
56
+ }
57
+
58
+ /**
59
+ * Build a single combined search query from all user messages in the
60
+ * range. Used to find which vault notes would have been referenced by
61
+ * the runtime auto-inject for this conversation. Approximation but
62
+ * cheaper than re-running search per user message.
63
+ */
64
+ /** Bounds for the vault/wiki recall query. It used to be EVERY user
65
+ * message of the range joined together — 900 messages / 275k chars on
66
+ * one reset, which the FTS layer then turned into ~50k OR-terms and
67
+ * the server stood still for minutes (2026-09-03). The recall only
68
+ * needs the gist of what the conversation was about: the most recent
69
+ * messages, human ones only (A2A traffic and injected blocks are
70
+ * persisted as user_message too), capped in characters. */
71
+ export const RECALL_QUERY_MAX_MESSAGES = 20;
72
+ export const RECALL_QUERY_MAX_CHARS = 4000;
73
+
74
+ export function buildVaultRecallQuery(
75
+ events: ReadonlyArray<{ kind: string; text?: string; from_agent?: string }>,
76
+ limits: { maxMessages?: number; maxChars?: number } = {},
77
+ ): string {
78
+ const maxMessages = limits.maxMessages ?? RECALL_QUERY_MAX_MESSAGES;
79
+ const maxChars = limits.maxChars ?? RECALL_QUERY_MAX_CHARS;
80
+ const texts = events
81
+ .filter((e) => e.kind === 'user_message' && !e.from_agent && typeof e.text === 'string' && e.text.trim().length > 0)
82
+ .map((e) => e.text as string)
83
+ .slice(-maxMessages);
84
+ // Newest first so the tail of the conversation survives the char cap.
85
+ const out: string[] = [];
86
+ let chars = 0;
87
+ for (let i = texts.length - 1; i >= 0; i--) {
88
+ const t = texts[i]!;
89
+ if (chars + t.length > maxChars) {
90
+ const room = maxChars - chars;
91
+ if (room > 40) out.unshift(t.slice(t.length - room));
92
+ break;
93
+ }
94
+ out.unshift(t);
95
+ chars += t.length + 1;
96
+ }
97
+ return out.join(' ');
98
+ }
99
+
100
+ /**
101
+ * Render the human-readable Markdown body for a completed dream.
102
+ * Optional sources block lets the caller surface which memory + vault
103
+ * notes were considered as input — useful to verify the extractor saw
104
+ * the right source material.
105
+ */
106
+ function renderBody(
107
+ meta: DreamMeta,
108
+ sourceTitle: string,
109
+ sources?: {
110
+ memorySlugs: string[];
111
+ vaultSlugsWithScore: string[]; // pre-formatted "slug@0.74"
112
+ wikiSlugs?: string[]; // Phase 4
113
+ },
114
+ ): string {
115
+ const triggerWord = meta.trigger === 'manual' ? 'manual' : 'auto';
116
+ const lines: string[] = [
117
+ `# Dream — ${sourceTitle} (${triggerWord})`,
118
+ '',
119
+ `Source session: \`${meta.source_session}\` `,
120
+ `Range: \`${new Date(meta.range_from_ts).toISOString()}\` → \`${new Date(meta.range_through_ts).toISOString()}\` `,
121
+ `Worker model: \`${meta.worker_model_ref}\`${meta.worker_fallback_ref ? ` (backup: \`${meta.worker_fallback_ref}\`)` : ''} `,
122
+ ...(meta.worker_switch
123
+ ? [
124
+ `Worker switched: \`${meta.worker_switch.from}\` → \`${meta.worker_switch.to}\` from chunk ${meta.worker_switch.at_chunk} on — ${meta.worker_switch.reason} `,
125
+ ]
126
+ : []),
127
+ `Created: \`${meta.created_at}\` `,
128
+ `Status: **${meta.status}**`,
129
+ '',
130
+ ];
131
+ if (meta.error) {
132
+ lines.push(`> ⚠️ ${meta.error}`, '');
133
+ }
134
+ if (sources) {
135
+ lines.push('## Sources analyzed', '');
136
+ lines.push(
137
+ `- Memory notes (full content): ${sources.memorySlugs.length === 0 ? '_none_' : sources.memorySlugs.map((s) => `\`${s}\``).join(', ')}`,
138
+ );
139
+ lines.push(
140
+ `- Vault notes (recall hits): ${sources.vaultSlugsWithScore.length === 0 ? '_none_' : sources.vaultSlugsWithScore.map((s) => `\`${s}\``).join(', ')}`,
141
+ );
142
+ if (sources.wikiSlugs && sources.wikiSlugs.length > 0) {
143
+ lines.push(
144
+ `- Wiki pages (stub-derived + recall): ${sources.wikiSlugs.map((s) => `\`wiki/${s}\``).join(', ')}`,
145
+ );
146
+ }
147
+ lines.push('');
148
+ }
149
+ if (meta.findings.length === 0) {
150
+ if ((meta.chunks_failed ?? 0) > 0 || meta.status === 'failed') {
151
+ lines.push(
152
+ 'Extraction did NOT complete cleanly — no findings is a failure artifact, ' +
153
+ 'not an empty result. The range will be retried.',
154
+ '',
155
+ );
156
+ } else {
157
+ lines.push('No memory-worthy findings extracted from this range.', '');
158
+ }
159
+ } else {
160
+ lines.push('## Findings', '');
161
+ for (const f of meta.findings) {
162
+ const statusBadge =
163
+ f.status === 'applied'
164
+ ? '✓ applied'
165
+ : f.status === 'dismissed'
166
+ ? '✗ dismissed'
167
+ : f.status === 'resolved_manually'
168
+ ? '✔ resolved manually'
169
+ : '· pending';
170
+ const dupBadge = f.likely_duplicate ? ' ⚠️ likely-duplicate' : '';
171
+ lines.push(`### ${f.id}. \`${f.action}\` → \`${f.slug}\` (${statusBadge})${dupBadge}`);
172
+ lines.push('');
173
+ if (f.likely_duplicate && f.duplicate_of) {
174
+ lines.push(
175
+ f.novel_details
176
+ ? `> ⚠️ Topic matches \`${f.duplicate_of}\` — but the finding carries concrete ` +
177
+ `details (numbers/dates) NOT found there. Likely a NEW fact on a known topic; ` +
178
+ `do not batch-dismiss.`
179
+ : `> ⚠️ Near-duplicate of \`${f.duplicate_of}\` — review with dismissal in mind.`,
180
+ );
181
+ if (f.matched_excerpt) {
182
+ lines.push(`> Matched text: "${f.matched_excerpt}"`);
183
+ }
184
+ lines.push('');
185
+ }
186
+ lines.push(f.reason);
187
+ lines.push('');
188
+ if (f.current_excerpt) {
189
+ lines.push('> Current memory:');
190
+ lines.push('');
191
+ lines.push('```');
192
+ lines.push(f.current_excerpt);
193
+ lines.push('```');
194
+ lines.push('');
195
+ }
196
+ if (f.proposed_content) {
197
+ lines.push('> Proposed content:');
198
+ lines.push('');
199
+ lines.push('```markdown');
200
+ lines.push(f.proposed_content);
201
+ lines.push('```');
202
+ lines.push('');
203
+ }
204
+ }
205
+ }
206
+ return lines.join('\n');
207
+ }
208
+
209
+ /**
210
+ * Main entry. Creates a `running` dream file, runs extraction, updates the
211
+ * file to `paused` / `failed` / `completed` based on outcome.
212
+ *
213
+ * Errors in extraction are caught and result in a `failed` dream — never
214
+ * thrown to the caller. The caller (server-side trigger) just fires this
215
+ * and forgets. Diagnostic output goes to the Pino log.
216
+ */
217
+ export async function runDream(args: RunDreamArgs): Promise<{ id: string; finalStatus: DreamMeta['status'] }> {
218
+ const startedAt = new Date().toISOString();
219
+ const id = dreamIdFor(args.agent, args.sourceSession, args.trigger);
220
+
221
+ // Resolve worker model first — fail-loud per design (RemConfig requires
222
+ // an explicit model when enabled, no fallback).
223
+ let workerModel: ResolvedModel;
224
+ // The fallback chain in config order, primary and duplicates dropped.
225
+ const fallbackModels: ResolvedModel[] = [];
226
+ let startSwitch: { from: string; to: string; reason: string; at_chunk: number } | undefined;
227
+ // The coverage judge's model (rem.dedup.judge): the worker unless a
228
+ // ref is named; validated here so a typo fails the run at its start.
229
+ let judgeModel: ResolvedModel | undefined;
230
+ try {
231
+ workerModel = resolveDreamModel(args.config, args.rem.model);
232
+ if (args.config.rem.dedup.judge.enabled) {
233
+ judgeModel = resolveJudgeModel(args.config, args.config.rem.dedup.judge.model, workerModel);
234
+ }
235
+ // The backup is validated up front too: a typo in `rem.fallback`
236
+ // must surface now, not on the day the primary is down.
237
+ const refs = args.rem.fallback ? (Array.isArray(args.rem.fallback) ? args.rem.fallback : [args.rem.fallback]) : [];
238
+ for (const ref of refs) {
239
+ const m = resolveDreamModel(args.config, ref);
240
+ const same = (a: ResolvedModel, b: ResolvedModel) => a.providerName === b.providerName && a.modelId === b.modelId;
241
+ if (same(m, workerModel)) {
242
+ logger.warn({ msg: 'dream.worker_fallback_is_primary', agent: args.agent, ref });
243
+ continue;
244
+ }
245
+ if (fallbackModels.some((f) => same(f, m))) continue;
246
+ fallbackModels.push(m);
247
+ }
248
+ // A worker marked unavailable (model-availability.ts) is not knocked
249
+ // on again: the run starts on the first backup that is not marked,
250
+ // recorded as a switch at chunk 0 so the file and the judge follow.
251
+ const startMark = modelUnavailable(modelRef(workerModel));
252
+ if (startMark) {
253
+ const idx = fallbackModels.findIndex((m) => !modelUnavailable(modelRef(m)));
254
+ if (idx >= 0) {
255
+ const to = fallbackModels[idx]!;
256
+ startSwitch = { from: modelRef(workerModel), to: modelRef(to), reason: unavailableReason(startMark), at_chunk: 0 };
257
+ logger.info({ msg: 'dream.worker_start_on_fallback', agent: args.agent, ...startSwitch });
258
+ const rest = fallbackModels.slice(idx + 1);
259
+ fallbackModels.length = 0;
260
+ fallbackModels.push(...rest);
261
+ workerModel = to;
262
+ }
263
+ }
264
+ } catch (err) {
265
+ logger.error({
266
+ msg: 'dream.worker_resolve_failed',
267
+ agent: args.agent,
268
+ err: (err as Error).message,
269
+ });
270
+ // Persist a failed dream so the user sees something rather than silent skip.
271
+ const meta: DreamMeta = {
272
+ id,
273
+ agent: args.agent,
274
+ source_session: args.sourceSession,
275
+ trigger: args.trigger,
276
+ status: 'failed',
277
+ range_from_ts: args.rangeFromTs,
278
+ range_through_ts: args.rangeThroughTs,
279
+ created_at: startedAt,
280
+ error: (err as Error).message,
281
+ chunks_done: 0,
282
+ chunks_total: 0,
283
+ worker_model_ref: args.rem.model,
284
+ findings: [],
285
+ };
286
+ // No `sources` block here — we never got past resolveDreamModel,
287
+ // there's nothing to attribute.
288
+ await writeDreamFile(args.agent, { meta, body: renderBody(meta, args.sourceSession) });
289
+ return { id, finalStatus: 'failed' };
290
+ }
291
+
292
+ // Pull source events.
293
+ const events = await getHistory(args.agent, args.sourceSession);
294
+ // Review-loop windows are found on the FULL history, not the range:
295
+ // a loop that started before rangeFromTs and ends inside it must
296
+ // still be recognised as a window.
297
+ const review = excludeReviewWindows(events);
298
+ if (review.dropped > 0) {
299
+ logger.info({
300
+ msg: 'dream.rem.review_windows_skipped',
301
+ agent: args.agent,
302
+ session: args.sourceSession,
303
+ windows: review.windows.map((w) => ({
304
+ fromTs: w.fromTs,
305
+ throughTs: Number.isFinite(w.throughTs) ? w.throughTs : null,
306
+ })),
307
+ dropped: review.dropped,
308
+ hint: 'facts clarified inside a dream_review loop are written to the wiki directly; REM must not re-extract them',
309
+ });
310
+ }
311
+ const eventsInRange = review.events.filter(
312
+ (e) => e.ts > args.rangeFromTs && e.ts <= args.rangeThroughTs,
313
+ );
314
+
315
+ // Memory snapshot.
316
+ const noteSummaries = await args.mgr.listNotes();
317
+ const existingMemory: Array<{ slug: string; markdown: string }> = [];
318
+ for (const n of noteSummaries) {
319
+ try {
320
+ const note = await args.mgr.getNote(n.slug);
321
+ if (note) existingMemory.push({ slug: n.slug, markdown: note.markdown });
322
+ } catch (err) {
323
+ logger.warn({ msg: 'dream.memory_read_failed', slug: n.slug, err: (err as Error).message });
324
+ }
325
+ }
326
+
327
+ // Vault references — single combined query. We bump the limit (40) high
328
+ // enough that vault hits don't get crowded out by memory hits in the
329
+ // mixed search results: existing memory is already passed in full (see
330
+ // listNotes() above), so memory-source hits in this search are
331
+ // effectively duplicates and we drop them. Up to 15 vault notes pass
332
+ // through to the extractor.
333
+ const referencedVault: Array<{ slug: string; markdown: string; score: number }> = [];
334
+ const recallQuery = buildVaultRecallQuery(eventsInRange);
335
+ // Logged BEFORE the two synchronous searches so a slow recall is
336
+ // visible in the log instead of a silent gap before dream.start.
337
+ logger.info({
338
+ msg: 'dream.recall_query',
339
+ agent: args.agent,
340
+ sourceSession: args.sourceSession,
341
+ eventsInRange: eventsInRange.length,
342
+ queryChars: recallQuery.length,
343
+ });
344
+ if (recallQuery.trim().length > 0) {
345
+ try {
346
+ const hits = await args.mgr.search(recallQuery, { limit: 40, minScore: 0.4 });
347
+ const vaultHits = hits.filter((h) => h.source === 'vault').slice(0, 15);
348
+ const seenSlugs = new Set<string>();
349
+ for (const h of vaultHits) {
350
+ if (seenSlugs.has(h.slug)) continue;
351
+ seenSlugs.add(h.slug);
352
+ try {
353
+ const raw = await readFile(h.filePath, 'utf8');
354
+ referencedVault.push({ slug: h.slug, markdown: raw, score: h.score });
355
+ } catch (err) {
356
+ logger.debug({
357
+ msg: 'dream.vault_read_failed',
358
+ slug: h.slug,
359
+ err: (err as Error).message,
360
+ });
361
+ }
362
+ }
363
+ } catch (err) {
364
+ logger.warn({ msg: 'dream.vault_recall_failed', err: (err as Error).message });
365
+ }
366
+ }
367
+
368
+ // Wiki context for dedup (v2.5): index.md (topology) + top-N
369
+ // embedding-matched wiki pages with full bodies. REM uses this to
370
+ // decide "is this fact already in the long-term wiki?" — Wiki is
371
+ // canonical, Memory is volatile inbox.
372
+ let wikiIndex = '';
373
+ const referencedWiki: Array<{ slug: string; markdown: string }> = [];
374
+ if (args.config.wiki.enabled) {
375
+ try {
376
+ const obs = resolveObsidianSource(args.config.obsidian);
377
+ const wikiAbs = obs?.vaultPath
378
+ ? join(obs.vaultPath, args.config.wiki.vaultSubfolder)
379
+ : null;
380
+ const ctx = await loadWikiContext({
381
+ mgr: args.mgr,
382
+ query: recallQuery,
383
+ wikiAbs,
384
+ });
385
+ wikiIndex = ctx.indexSummary;
386
+ for (const p of ctx.relevantPages) {
387
+ referencedWiki.push({ slug: p.slug, markdown: p.markdown });
388
+ }
389
+ } catch (err) {
390
+ logger.warn({ msg: 'dream.wiki_ctx.load_failed', agent: args.agent, err: (err as Error).message });
391
+ }
392
+ }
393
+
394
+ // Sources block — used by renderBody for the audit section in the
395
+ // dream file's Markdown body. Same shape across all subsequent
396
+ // renderBody calls so the file always shows what was considered.
397
+ const sources = {
398
+ memorySlugs: existingMemory.map((m) => m.slug),
399
+ vaultSlugsWithScore: referencedVault.map((v) => `${v.slug}@${v.score.toFixed(2)}`),
400
+ wikiSlugs: referencedWiki.map((w) => w.slug),
401
+ };
402
+
403
+ // Initial running file. chunks_total is set after the first chunk-plan
404
+ // happens inside extractFromSession; we backfill once we know.
405
+ const meta: DreamMeta = {
406
+ id,
407
+ agent: args.agent,
408
+ source_session: args.sourceSession,
409
+ trigger: args.trigger,
410
+ status: 'running',
411
+ range_from_ts: args.rangeFromTs,
412
+ range_through_ts: args.rangeThroughTs,
413
+ created_at: startedAt,
414
+ chunks_done: 0,
415
+ chunks_total: 0,
416
+ worker_model_ref: `${workerModel.providerName}/${workerModel.modelId}`,
417
+ ...(fallbackModels.length > 0
418
+ ? { worker_fallback_ref: fallbackModels.map((f) => `${f.providerName}/${f.modelId}`).join(', ') }
419
+ : {}),
420
+ ...(startSwitch ? { worker_switch: startSwitch } : {}),
421
+ findings: [],
422
+ };
423
+ let file: DreamFile = {
424
+ meta,
425
+ body: renderBody(meta, args.sourceSession, sources),
426
+ };
427
+ await writeDreamFile(args.agent, file);
428
+
429
+ logger.info({
430
+ msg: 'dream.start',
431
+ agent: args.agent,
432
+ id,
433
+ trigger: args.trigger,
434
+ sourceSession: args.sourceSession,
435
+ eventsInRange: eventsInRange.length,
436
+ existingMemoryCount: existingMemory.length,
437
+ existingMemorySlugs: existingMemory.map((m) => m.slug),
438
+ referencedVaultCount: referencedVault.length,
439
+ referencedVaultSlugs: referencedVault.map((v) => `${v.slug}@${v.score.toFixed(2)}`),
440
+ referencedWikiCount: referencedWiki.length,
441
+ referencedWikiSlugs: referencedWiki.map((w) => w.slug),
442
+ workerModel: meta.worker_model_ref,
443
+ workerFallback: meta.worker_fallback_ref ?? null,
444
+ });
445
+
446
+ try {
447
+ const result = await extractFromSession({
448
+ agent: args.agent,
449
+ events: eventsInRange,
450
+ existingMemory,
451
+ referencedVault,
452
+ wikiIndex,
453
+ relevantWikiPages: referencedWiki,
454
+ workerModel,
455
+ ...(fallbackModels.length > 0 ? { fallbackModels } : {}),
456
+ chunkTimeoutMs: args.rem.chunkTimeoutMs,
457
+ chunkTokens: args.rem.chunkTokens,
458
+ thinking: args.rem.thinking,
459
+ signal: args.signal,
460
+ onChunkComplete: async ({ chunkIndex, totalChunks }) => {
461
+ // Persist progress so a crash mid-flight leaves a recoverable file.
462
+ meta.chunks_done = chunkIndex;
463
+ meta.chunks_total = totalChunks;
464
+ file = { meta, body: renderBody(meta, args.sourceSession, sources) };
465
+ await writeDreamFile(args.agent, file);
466
+ },
467
+ onWorkerSwitch: async (sw) => {
468
+ // Persist the switch before the retried chunk runs, so a crash
469
+ // right after still shows which worker was in charge.
470
+ meta.worker_switch = { from: sw.from, to: sw.to, reason: sw.reason, at_chunk: sw.atChunk };
471
+ file = { meta, body: renderBody(meta, args.sourceSession, sources) };
472
+ await writeDreamFile(args.agent, file);
473
+ },
474
+ });
475
+
476
+ // Mechanical dedup against already-persisted knowledge — the worker
477
+ // model gets the same context in its prompt but small models don't
478
+ // reliably act on it (buffet 2026-07-06: 26/27 findings were
479
+ // repeats). Exact slug collisions are dropped, near-duplicates are
480
+ // marked for batch-dismissal. See rem-dedup.ts.
481
+ const dedup = await applyRemDedup({
482
+ agent: args.agent,
483
+ dreamId: id,
484
+ findings: result.findings,
485
+ existingMemorySlugs: existingMemory.map((m) => m.slug),
486
+ loadedWikiSlugs: referencedWiki.map((w) => w.slug),
487
+ mgr: args.mgr,
488
+ config: args.config.rem.dedup,
489
+ ...(judgeModel
490
+ ? {
491
+ judge: {
492
+ // The judge follows the worker: when the run switched to
493
+ // rem.fallback, the primary is unreachable for the judge
494
+ // too — unless the config names a judge model of its own.
495
+ model: effectiveJudgeModel(
496
+ args.config.rem.dedup.judge.model ? judgeModel : undefined,
497
+ meta.worker_switch?.to,
498
+ workerModel,
499
+ fallbackModels,
500
+ ),
501
+ config: args.config.rem.dedup.judge,
502
+ ...(args.config.rem.dedup.judge.thinking ? { thinking: args.config.rem.dedup.judge.thinking } : {}),
503
+ },
504
+ }
505
+ : {}),
506
+ });
507
+
508
+ meta.findings = dedup.findings;
509
+ meta.chunks_done = result.chunksProcessed;
510
+ meta.chunks_total = result.totalChunks;
511
+ if (result.failedChunks > 0) meta.chunks_failed = result.failedChunks;
512
+
513
+ // Failed ≠ empty (bug report 2026-07-24): a run with errored chunks
514
+ // must never take the completed/processed path — that would mask
515
+ // backend failures as "no findings" and (via the caller's watermark
516
+ // stamp) permanently mark the range as dreamed. Land as `failed`,
517
+ // stay in .dreams/ root (visible in dream_list), and because the
518
+ // caller only advances the watermark on completed/processed, the
519
+ // same range is retried on the next trigger.
520
+ if (result.completed && result.failedChunks > 0) {
521
+ meta.error =
522
+ `${result.failedChunks}/${result.totalChunks} extraction chunk(s) failed — ` +
523
+ 'range NOT marked as dreamed; it will be retried on the next REM trigger. ' +
524
+ 'Partial findings (if any) are preserved below for audit.';
525
+ await transitionDreamStatus(
526
+ args.agent,
527
+ // Body rendered from a status-patched copy so the human-readable
528
+ // status line matches the frontmatter; `meta` itself keeps the
529
+ // CURRENT status — transitionDreamStatus derives the old file
530
+ // path from it.
531
+ { meta, body: renderBody({ ...meta, status: 'failed' }, args.sourceSession, sources) },
532
+ 'failed',
533
+ { error: meta.error, completed_at: new Date().toISOString() },
534
+ );
535
+ // Keep only this newest failure per session — retries would
536
+ // otherwise pile up one failed file per idle cycle.
537
+ await pruneFailedDreams(args.agent, args.sourceSession, { keepId: id });
538
+ logger.warn({
539
+ msg: 'dream.failed_chunks',
540
+ agent: args.agent,
541
+ id,
542
+ failedChunks: result.failedChunks,
543
+ totalChunks: result.totalChunks,
544
+ partialFindings: meta.findings.length,
545
+ });
546
+ return { id, finalStatus: 'failed' };
547
+ }
548
+
549
+ if (result.completed) {
550
+ meta.completed_at = new Date().toISOString();
551
+ // Zero-findings dreams have nothing to review — short-circuit straight
552
+ // to processed/ so they don't loiter forever in .dreams/ active state
553
+ // (dream_apply/dismiss can't fire on an empty findings array). Audit
554
+ // trail is preserved in processed/.
555
+ if (meta.findings.length === 0) {
556
+ meta.processed_at = meta.completed_at;
557
+ await transitionDreamStatus(
558
+ args.agent,
559
+ { meta, body: renderBody(meta, args.sourceSession, sources) },
560
+ 'processed',
561
+ { completed_at: meta.completed_at, processed_at: meta.processed_at },
562
+ );
563
+ // A clean run supersedes earlier failed attempts on this session
564
+ // — but only as far as it actually read.
565
+ await pruneFailedDreams(args.agent, args.sourceSession, {
566
+ coveredThroughTs: meta.range_through_ts,
567
+ });
568
+ logger.info({
569
+ msg: 'dream.completed_empty',
570
+ agent: args.agent,
571
+ id,
572
+ note: 'no findings — auto-archived to processed/',
573
+ });
574
+ return { id, finalStatus: 'processed' };
575
+ }
576
+ await transitionDreamStatus(
577
+ args.agent,
578
+ { meta, body: renderBody(meta, args.sourceSession, sources) },
579
+ 'completed',
580
+ { completed_at: meta.completed_at },
581
+ );
582
+ await pruneFailedDreams(args.agent, args.sourceSession, {
583
+ coveredThroughTs: meta.range_through_ts,
584
+ });
585
+ logger.info({
586
+ msg: 'dream.completed',
587
+ agent: args.agent,
588
+ id,
589
+ findings: meta.findings.length,
590
+ });
591
+ return { id, finalStatus: 'completed' };
592
+ }
593
+ // Cancelled mid-way — only auto-trigger should hit this path.
594
+ await transitionDreamStatus(
595
+ args.agent,
596
+ { meta, body: renderBody(meta, args.sourceSession, sources) },
597
+ 'paused',
598
+ );
599
+ logger.info({
600
+ msg: 'dream.paused',
601
+ agent: args.agent,
602
+ id,
603
+ chunksDone: meta.chunks_done,
604
+ chunksTotal: meta.chunks_total,
605
+ });
606
+ return { id, finalStatus: 'paused' };
607
+ } catch (err) {
608
+ meta.error = (err as Error).message;
609
+ await transitionDreamStatus(
610
+ args.agent,
611
+ { meta, body: renderBody(meta, args.sourceSession, sources) },
612
+ 'failed',
613
+ { error: meta.error },
614
+ );
615
+ await pruneFailedDreams(args.agent, args.sourceSession, { keepId: id });
616
+ logger.error({
617
+ msg: 'dream.failed',
618
+ agent: args.agent,
619
+ id,
620
+ err: meta.error,
621
+ });
622
+ return { id, finalStatus: 'failed' };
623
+ }
624
+ }
625
+
626
+ /**
627
+ * Resume a previously-paused dream from where it left off. Reads the
628
+ * current state from disk, picks up at chunks_done + 1.
629
+ */
630
+ export async function resumeDream(args: {
631
+ agent: string;
632
+ id: string;
633
+ rem: RemConfig;
634
+ config: Config;
635
+ mgr: MemoryManager;
636
+ signal?: AbortSignal;
637
+ }): Promise<{ finalStatus: DreamMeta['status']; rangeThroughTs: number }> {
638
+ const file = await readDreamById(args.agent, args.id);
639
+ if (!file) throw new Error(`dream '${args.id}' not found`);
640
+ if (file.meta.status !== 'paused') {
641
+ throw new Error(`dream '${args.id}' is ${file.meta.status}, not paused — can't resume`);
642
+ }
643
+
644
+ // Delete the old paused file BEFORE kicking off the rerun. Without this,
645
+ // the stale paused file accumulated indefinitely: runDream generates a
646
+ // fresh timestamp-based id (dreamIdFor()), so a resume creates a new
647
+ // `<new-id>.dream.running.md` and the original `<old-id>.dream.paused.md`
648
+ // was never cleaned up. If the new run got aborted again (typical on
649
+ // active accounts), the result was N+1 paused files instead of N. Across
650
+ // a couple of days of idle cycles + user activity, paused dreams piled up
651
+ // (bug report 2026-05-05: 5 paused, 0 findings, all from the same
652
+ // source-session). Re-run-from-scratch was a deliberate v1 simplification
653
+ // (see comment below) — we just have to take responsibility for the old
654
+ // file's cleanup as part of resume's contract.
655
+ const oldPath = dreamFilePath(args.agent, args.id, 'paused');
656
+ try {
657
+ await unlink(oldPath);
658
+ logger.info({
659
+ msg: 'dream.resume.unlink_old',
660
+ agent: args.agent,
661
+ id: args.id,
662
+ sourceSession: file.meta.source_session,
663
+ });
664
+ } catch (err) {
665
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
666
+ logger.warn({
667
+ msg: 'dream.resume.unlink_old_failed',
668
+ agent: args.agent,
669
+ id: args.id,
670
+ err: (err as Error).message,
671
+ });
672
+ }
673
+ }
674
+
675
+ // For v1 we re-run from scratch on resume (don't preserve partial findings).
676
+ // Reason: partial findings without dedup across the full range can produce
677
+ // duplicates we'd then have to reconcile. Cheap for the chunk-cost; not a
678
+ // hot path in any case (auto-trigger gives small deltas).
679
+ return runDream({
680
+ agent: args.agent,
681
+ sourceSession: file.meta.source_session,
682
+ trigger: file.meta.trigger,
683
+ rangeFromTs: file.meta.range_from_ts,
684
+ rangeThroughTs: file.meta.range_through_ts,
685
+ rem: args.rem,
686
+ config: args.config,
687
+ mgr: args.mgr,
688
+ signal: args.signal,
689
+ }).then((r) => ({
690
+ finalStatus: r.finalStatus,
691
+ // The caller stamps the session's dreamed-marker with the range that
692
+ // was ACTUALLY analyzed — for a resume that's the original range end,
693
+ // not "now" (everything after it still needs its own dream).
694
+ rangeThroughTs: file.meta.range_through_ts,
695
+ }));
696
+ }