rookery-agent 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (670) hide show
  1. package/README.md +467 -367
  2. package/docs/migration.md +88 -88
  3. package/docs/updates.md +112 -0
  4. package/package.json +13 -3
  5. package/packages/cli/dist/commands/config.js +2 -2
  6. package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
  7. package/packages/cli/dist/commands/doctor.js +13 -9
  8. package/packages/cli/dist/commands/doctor.js.map +1 -1
  9. package/packages/cli/dist/commands/memory.js +1 -1
  10. package/packages/cli/dist/commands/org.d.ts +2 -2
  11. package/packages/cli/dist/commands/org.d.ts.map +1 -1
  12. package/packages/cli/dist/commands/org.js +19 -17
  13. package/packages/cli/dist/commands/org.js.map +1 -1
  14. package/packages/cli/dist/commands/serve.js +1 -1
  15. package/packages/cli/dist/commands/serve.js.map +1 -1
  16. package/packages/cli/dist/commands/shared.d.ts.map +1 -1
  17. package/packages/cli/dist/commands/shared.js +2 -1
  18. package/packages/cli/dist/commands/shared.js.map +1 -1
  19. package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
  20. package/packages/cli/dist/commands/tasks.js +25 -11
  21. package/packages/cli/dist/commands/tasks.js.map +1 -1
  22. package/packages/cli/dist/commands/tools.js +1 -1
  23. package/packages/cli/dist/commands/tools.js.map +1 -1
  24. package/packages/cli/dist/index.js +13 -13
  25. package/packages/cli/dist/index.js.map +1 -1
  26. package/packages/cli/dist/repl.d.ts +12 -0
  27. package/packages/cli/dist/repl.d.ts.map +1 -1
  28. package/packages/cli/dist/repl.js +170 -16
  29. package/packages/cli/dist/repl.js.map +1 -1
  30. package/packages/cli/dist/tui/App.d.ts +7 -3
  31. package/packages/cli/dist/tui/App.d.ts.map +1 -1
  32. package/packages/cli/dist/tui/App.js +182 -16
  33. package/packages/cli/dist/tui/App.js.map +1 -1
  34. package/packages/cli/dist/tui/commands.d.ts +7 -0
  35. package/packages/cli/dist/tui/commands.d.ts.map +1 -1
  36. package/packages/cli/dist/tui/commands.js +70 -8
  37. package/packages/cli/dist/tui/commands.js.map +1 -1
  38. package/packages/cli/dist/tui/components/AssignmentsView.js +4 -4
  39. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
  40. package/packages/cli/dist/tui/components/Banner.d.ts +11 -2
  41. package/packages/cli/dist/tui/components/Banner.d.ts.map +1 -1
  42. package/packages/cli/dist/tui/components/Banner.js +7 -10
  43. package/packages/cli/dist/tui/components/Banner.js.map +1 -1
  44. package/packages/cli/dist/tui/components/CodeBlock.js +2 -2
  45. package/packages/cli/dist/tui/components/CodeBlock.js.map +1 -1
  46. package/packages/cli/dist/tui/components/InputBox.d.ts.map +1 -1
  47. package/packages/cli/dist/tui/components/InputBox.js +4 -4
  48. package/packages/cli/dist/tui/components/InputBox.js.map +1 -1
  49. package/packages/cli/dist/tui/components/Logo.d.ts +56 -0
  50. package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -0
  51. package/packages/cli/dist/tui/components/Logo.js +50 -0
  52. package/packages/cli/dist/tui/components/Logo.js.map +1 -0
  53. package/packages/cli/dist/tui/components/Markdown.js +8 -8
  54. package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
  55. package/packages/cli/dist/tui/components/Message.d.ts +1 -1
  56. package/packages/cli/dist/tui/components/Message.d.ts.map +1 -1
  57. package/packages/cli/dist/tui/components/Message.js +5 -4
  58. package/packages/cli/dist/tui/components/Message.js.map +1 -1
  59. package/packages/cli/dist/tui/components/QuestionView.d.ts +29 -0
  60. package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -0
  61. package/packages/cli/dist/tui/components/QuestionView.js +53 -0
  62. package/packages/cli/dist/tui/components/QuestionView.js.map +1 -0
  63. package/packages/cli/dist/tui/components/SlashPalette.d.ts +5 -2
  64. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
  65. package/packages/cli/dist/tui/components/SlashPalette.js +2 -2
  66. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
  67. package/packages/cli/dist/tui/components/StatusLine.d.ts +0 -2
  68. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
  69. package/packages/cli/dist/tui/components/StatusLine.js +8 -5
  70. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
  71. package/packages/cli/dist/tui/components/ToolGroup.js +2 -2
  72. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
  73. package/packages/cli/dist/tui/components/WatchView.d.ts +21 -0
  74. package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -0
  75. package/packages/cli/dist/tui/components/WatchView.js +36 -0
  76. package/packages/cli/dist/tui/components/WatchView.js.map +1 -0
  77. package/packages/cli/dist/tui/history.d.ts +20 -0
  78. package/packages/cli/dist/tui/history.d.ts.map +1 -0
  79. package/packages/cli/dist/tui/history.js +105 -0
  80. package/packages/cli/dist/tui/history.js.map +1 -0
  81. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
  82. package/packages/cli/dist/tui/hooks/useSlash.js +3 -2
  83. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
  84. package/packages/cli/dist/tui/hooks/useTurn.d.ts +58 -1
  85. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
  86. package/packages/cli/dist/tui/hooks/useTurn.js +214 -36
  87. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
  88. package/packages/cli/dist/tui/hooks/useWatch.d.ts +52 -0
  89. package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -0
  90. package/packages/cli/dist/tui/hooks/useWatch.js +145 -0
  91. package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -0
  92. package/packages/cli/dist/tui/inkTheme.d.ts +19 -0
  93. package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -0
  94. package/packages/cli/dist/tui/inkTheme.js +81 -0
  95. package/packages/cli/dist/tui/inkTheme.js.map +1 -0
  96. package/packages/cli/dist/tui/theme.d.ts +39 -29
  97. package/packages/cli/dist/tui/theme.d.ts.map +1 -1
  98. package/packages/cli/dist/tui/theme.js +35 -25
  99. package/packages/cli/dist/tui/theme.js.map +1 -1
  100. package/packages/cli/dist/tui/types.d.ts +56 -3
  101. package/packages/cli/dist/tui/types.d.ts.map +1 -1
  102. package/packages/cli/dist/tui/types.js +85 -0
  103. package/packages/cli/dist/tui/types.js.map +1 -1
  104. package/packages/cli/dist/ui/modelNames.d.ts +51 -0
  105. package/packages/cli/dist/ui/modelNames.d.ts.map +1 -0
  106. package/packages/cli/dist/ui/modelNames.js +134 -0
  107. package/packages/cli/dist/ui/modelNames.js.map +1 -0
  108. package/packages/cli/dist/ui/render.d.ts.map +1 -1
  109. package/packages/cli/dist/ui/render.js +17 -8
  110. package/packages/cli/dist/ui/render.js.map +1 -1
  111. package/packages/cli/dist/ui/speech.js +5 -0
  112. package/packages/cli/dist/ui/speech.js.map +1 -1
  113. package/packages/cli/dist/ui/theme.d.ts +33 -9
  114. package/packages/cli/dist/ui/theme.d.ts.map +1 -1
  115. package/packages/cli/dist/ui/theme.js +33 -9
  116. package/packages/cli/dist/ui/theme.js.map +1 -1
  117. package/packages/cli/package.json +1 -1
  118. package/packages/core/dist/agents/persona.d.ts.map +1 -1
  119. package/packages/core/dist/agents/persona.js +5 -2
  120. package/packages/core/dist/agents/persona.js.map +1 -1
  121. package/packages/core/dist/computer/accessibility.d.ts +78 -0
  122. package/packages/core/dist/computer/accessibility.d.ts.map +1 -0
  123. package/packages/core/dist/computer/accessibility.js +270 -0
  124. package/packages/core/dist/computer/accessibility.js.map +1 -0
  125. package/packages/core/dist/computer/assemblies.d.ts +17 -0
  126. package/packages/core/dist/computer/assemblies.d.ts.map +1 -0
  127. package/packages/core/dist/computer/assemblies.js +55 -0
  128. package/packages/core/dist/computer/assemblies.js.map +1 -0
  129. package/packages/core/dist/computer/browser-init.d.ts +9 -0
  130. package/packages/core/dist/computer/browser-init.d.ts.map +1 -0
  131. package/packages/core/dist/computer/browser-init.js +133 -0
  132. package/packages/core/dist/computer/browser-init.js.map +1 -0
  133. package/packages/core/dist/computer/cursor.d.ts +30 -0
  134. package/packages/core/dist/computer/cursor.d.ts.map +1 -0
  135. package/packages/core/dist/computer/cursor.js +30 -0
  136. package/packages/core/dist/computer/cursor.js.map +1 -0
  137. package/packages/core/dist/computer/mcp-server.js +524 -82
  138. package/packages/core/dist/computer/mcp-server.js.map +1 -1
  139. package/packages/core/dist/computer/powershell.d.ts +4 -0
  140. package/packages/core/dist/computer/powershell.d.ts.map +1 -1
  141. package/packages/core/dist/computer/powershell.js +471 -81
  142. package/packages/core/dist/computer/powershell.js.map +1 -1
  143. package/packages/core/dist/computer/screen-text.d.ts +82 -0
  144. package/packages/core/dist/computer/screen-text.d.ts.map +1 -0
  145. package/packages/core/dist/computer/screen-text.js +243 -0
  146. package/packages/core/dist/computer/screen-text.js.map +1 -0
  147. package/packages/core/dist/computer/sketch.d.ts +66 -0
  148. package/packages/core/dist/computer/sketch.d.ts.map +1 -0
  149. package/packages/core/dist/computer/sketch.js +540 -0
  150. package/packages/core/dist/computer/sketch.js.map +1 -0
  151. package/packages/core/dist/computer/tools.d.ts +8 -8
  152. package/packages/core/dist/computer/tools.d.ts.map +1 -1
  153. package/packages/core/dist/computer/tools.js +186 -31
  154. package/packages/core/dist/computer/tools.js.map +1 -1
  155. package/packages/core/dist/computer/validation.d.ts +555 -0
  156. package/packages/core/dist/computer/validation.d.ts.map +1 -0
  157. package/packages/core/dist/computer/validation.js +111 -0
  158. package/packages/core/dist/computer/validation.js.map +1 -0
  159. package/packages/core/dist/computer/windows-cursor.d.ts +14 -0
  160. package/packages/core/dist/computer/windows-cursor.d.ts.map +1 -0
  161. package/packages/core/dist/computer/windows-cursor.js +713 -0
  162. package/packages/core/dist/computer/windows-cursor.js.map +1 -0
  163. package/packages/core/dist/config.d.ts +34 -1
  164. package/packages/core/dist/config.d.ts.map +1 -1
  165. package/packages/core/dist/config.js +362 -11
  166. package/packages/core/dist/config.js.map +1 -1
  167. package/packages/core/dist/cron/scheduler.d.ts +59 -6
  168. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  169. package/packages/core/dist/cron/scheduler.js +295 -27
  170. package/packages/core/dist/cron/scheduler.js.map +1 -1
  171. package/packages/core/dist/cron/store.d.ts +19 -1
  172. package/packages/core/dist/cron/store.d.ts.map +1 -1
  173. package/packages/core/dist/cron/store.js +36 -8
  174. package/packages/core/dist/cron/store.js.map +1 -1
  175. package/packages/core/dist/external/claude-code.d.ts +4 -0
  176. package/packages/core/dist/external/claude-code.d.ts.map +1 -0
  177. package/packages/core/dist/external/claude-code.js +111 -0
  178. package/packages/core/dist/external/claude-code.js.map +1 -0
  179. package/packages/core/dist/external/discovery.d.ts +33 -0
  180. package/packages/core/dist/external/discovery.d.ts.map +1 -0
  181. package/packages/core/dist/external/discovery.js +144 -0
  182. package/packages/core/dist/external/discovery.js.map +1 -0
  183. package/packages/core/dist/external/homes.d.ts +26 -0
  184. package/packages/core/dist/external/homes.d.ts.map +1 -0
  185. package/packages/core/dist/external/homes.js +49 -0
  186. package/packages/core/dist/external/homes.js.map +1 -0
  187. package/packages/core/dist/external/shared.d.ts +201 -0
  188. package/packages/core/dist/external/shared.d.ts.map +1 -0
  189. package/packages/core/dist/external/shared.js +308 -0
  190. package/packages/core/dist/external/shared.js.map +1 -0
  191. package/packages/core/dist/gateway/policy.d.ts +117 -2
  192. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  193. package/packages/core/dist/gateway/policy.js +286 -6
  194. package/packages/core/dist/gateway/policy.js.map +1 -1
  195. package/packages/core/dist/index.d.ts +38 -12
  196. package/packages/core/dist/index.d.ts.map +1 -1
  197. package/packages/core/dist/index.js +66 -12
  198. package/packages/core/dist/index.js.map +1 -1
  199. package/packages/core/dist/memory/db.d.ts +1 -1
  200. package/packages/core/dist/memory/db.d.ts.map +1 -1
  201. package/packages/core/dist/memory/db.js +878 -1
  202. package/packages/core/dist/memory/db.js.map +1 -1
  203. package/packages/core/dist/memory/dream/admission.d.ts +124 -0
  204. package/packages/core/dist/memory/dream/admission.d.ts.map +1 -0
  205. package/packages/core/dist/memory/dream/admission.js +116 -0
  206. package/packages/core/dist/memory/dream/admission.js.map +1 -0
  207. package/packages/core/dist/memory/dream/candidate.d.ts +152 -0
  208. package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -0
  209. package/packages/core/dist/memory/dream/candidate.js +547 -0
  210. package/packages/core/dist/memory/dream/candidate.js.map +1 -0
  211. package/packages/core/dist/memory/dream/evaluate.d.ts +394 -0
  212. package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -0
  213. package/packages/core/dist/memory/dream/evaluate.js +1032 -0
  214. package/packages/core/dist/memory/dream/evaluate.js.map +1 -0
  215. package/packages/core/dist/memory/dream/frame.d.ts +61 -0
  216. package/packages/core/dist/memory/dream/frame.d.ts.map +1 -0
  217. package/packages/core/dist/memory/dream/frame.js +292 -0
  218. package/packages/core/dist/memory/dream/frame.js.map +1 -0
  219. package/packages/core/dist/memory/dream/label.d.ts +370 -0
  220. package/packages/core/dist/memory/dream/label.d.ts.map +1 -0
  221. package/packages/core/dist/memory/dream/label.js +439 -0
  222. package/packages/core/dist/memory/dream/label.js.map +1 -0
  223. package/packages/core/dist/memory/dream/measure.d.ts +114 -0
  224. package/packages/core/dist/memory/dream/measure.d.ts.map +1 -0
  225. package/packages/core/dist/memory/dream/measure.js +205 -0
  226. package/packages/core/dist/memory/dream/measure.js.map +1 -0
  227. package/packages/core/dist/memory/dream/policy.d.ts +21 -0
  228. package/packages/core/dist/memory/dream/policy.d.ts.map +1 -0
  229. package/packages/core/dist/memory/dream/policy.js +157 -0
  230. package/packages/core/dist/memory/dream/policy.js.map +1 -0
  231. package/packages/core/dist/memory/dream/probe.d.ts +202 -0
  232. package/packages/core/dist/memory/dream/probe.d.ts.map +1 -0
  233. package/packages/core/dist/memory/dream/probe.js +671 -0
  234. package/packages/core/dist/memory/dream/probe.js.map +1 -0
  235. package/packages/core/dist/memory/dream/promote.d.ts +312 -0
  236. package/packages/core/dist/memory/dream/promote.d.ts.map +1 -0
  237. package/packages/core/dist/memory/dream/promote.js +528 -0
  238. package/packages/core/dist/memory/dream/promote.js.map +1 -0
  239. package/packages/core/dist/memory/dream/score.d.ts +103 -0
  240. package/packages/core/dist/memory/dream/score.d.ts.map +1 -0
  241. package/packages/core/dist/memory/dream/score.js +334 -0
  242. package/packages/core/dist/memory/dream/score.js.map +1 -0
  243. package/packages/core/dist/memory/dream/slots.d.ts +193 -0
  244. package/packages/core/dist/memory/dream/slots.d.ts.map +1 -0
  245. package/packages/core/dist/memory/dream/slots.js +0 -0
  246. package/packages/core/dist/memory/dream/slots.js.map +1 -0
  247. package/packages/core/dist/memory/dream/trajectory.d.ts +262 -0
  248. package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -0
  249. package/packages/core/dist/memory/dream/trajectory.js +366 -0
  250. package/packages/core/dist/memory/dream/trajectory.js.map +1 -0
  251. package/packages/core/dist/memory/extractor.d.ts +7 -0
  252. package/packages/core/dist/memory/extractor.d.ts.map +1 -1
  253. package/packages/core/dist/memory/extractor.js +35 -12
  254. package/packages/core/dist/memory/extractor.js.map +1 -1
  255. package/packages/core/dist/memory/gate.d.ts +43 -7
  256. package/packages/core/dist/memory/gate.d.ts.map +1 -1
  257. package/packages/core/dist/memory/gate.js +91 -4
  258. package/packages/core/dist/memory/gate.js.map +1 -1
  259. package/packages/core/dist/memory/recall.d.ts +57 -0
  260. package/packages/core/dist/memory/recall.d.ts.map +1 -1
  261. package/packages/core/dist/memory/recall.js +60 -123
  262. package/packages/core/dist/memory/recall.js.map +1 -1
  263. package/packages/core/dist/memory/sleep.d.ts +131 -4
  264. package/packages/core/dist/memory/sleep.d.ts.map +1 -1
  265. package/packages/core/dist/memory/sleep.js +2384 -65
  266. package/packages/core/dist/memory/sleep.js.map +1 -1
  267. package/packages/core/dist/memory/store.d.ts +564 -10
  268. package/packages/core/dist/memory/store.d.ts.map +1 -1
  269. package/packages/core/dist/memory/store.js +1673 -102
  270. package/packages/core/dist/memory/store.js.map +1 -1
  271. package/packages/core/dist/org/controller.d.ts +268 -4
  272. package/packages/core/dist/org/controller.d.ts.map +1 -1
  273. package/packages/core/dist/org/controller.js +2298 -248
  274. package/packages/core/dist/org/controller.js.map +1 -1
  275. package/packages/core/dist/org/ponytail.d.ts +1 -1
  276. package/packages/core/dist/org/ponytail.js +1 -1
  277. package/packages/core/dist/org/project-mcp.d.ts +3 -3
  278. package/packages/core/dist/org/prompts.d.ts +44 -30
  279. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  280. package/packages/core/dist/org/prompts.js +209 -92
  281. package/packages/core/dist/org/prompts.js.map +1 -1
  282. package/packages/core/dist/org/questions.d.ts +104 -0
  283. package/packages/core/dist/org/questions.d.ts.map +1 -0
  284. package/packages/core/dist/org/questions.js +136 -0
  285. package/packages/core/dist/org/questions.js.map +1 -0
  286. package/packages/core/dist/org/review.d.ts +100 -0
  287. package/packages/core/dist/org/review.d.ts.map +1 -0
  288. package/packages/core/dist/org/review.js +256 -0
  289. package/packages/core/dist/org/review.js.map +1 -0
  290. package/packages/core/dist/org/store.d.ts +311 -2
  291. package/packages/core/dist/org/store.d.ts.map +1 -1
  292. package/packages/core/dist/org/store.js +981 -13
  293. package/packages/core/dist/org/store.js.map +1 -1
  294. package/packages/core/dist/org/tools.d.ts +33 -3
  295. package/packages/core/dist/org/tools.d.ts.map +1 -1
  296. package/packages/core/dist/org/tools.js +380 -67
  297. package/packages/core/dist/org/tools.js.map +1 -1
  298. package/packages/core/dist/providers/catalogue.d.ts +1 -1
  299. package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
  300. package/packages/core/dist/providers/catalogue.js +2 -2
  301. package/packages/core/dist/providers/catalogue.js.map +1 -1
  302. package/packages/core/dist/providers/claude-code.d.ts +19 -3
  303. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  304. package/packages/core/dist/providers/claude-code.js +501 -40
  305. package/packages/core/dist/providers/claude-code.js.map +1 -1
  306. package/packages/core/dist/providers/claude-tui.d.ts +288 -0
  307. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -0
  308. package/packages/core/dist/providers/claude-tui.js +1118 -0
  309. package/packages/core/dist/providers/claude-tui.js.map +1 -0
  310. package/packages/core/dist/providers/codex-auth.d.ts +15 -0
  311. package/packages/core/dist/providers/codex-auth.d.ts.map +1 -0
  312. package/packages/core/dist/providers/codex-auth.js +127 -0
  313. package/packages/core/dist/providers/codex-auth.js.map +1 -0
  314. package/packages/core/dist/providers/codex-bridge.d.ts +58 -0
  315. package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -0
  316. package/packages/core/dist/providers/codex-bridge.js +375 -0
  317. package/packages/core/dist/providers/codex-bridge.js.map +1 -0
  318. package/packages/core/dist/providers/codex-translate.d.ts +75 -0
  319. package/packages/core/dist/providers/codex-translate.d.ts.map +1 -0
  320. package/packages/core/dist/providers/codex-translate.js +383 -0
  321. package/packages/core/dist/providers/codex-translate.js.map +1 -0
  322. package/packages/core/dist/providers/model-gateway.d.ts +56 -0
  323. package/packages/core/dist/providers/model-gateway.d.ts.map +1 -0
  324. package/packages/core/dist/providers/model-gateway.js +119 -0
  325. package/packages/core/dist/providers/model-gateway.js.map +1 -0
  326. package/packages/core/dist/providers/process.d.ts +3 -1
  327. package/packages/core/dist/providers/process.d.ts.map +1 -1
  328. package/packages/core/dist/providers/process.js +3 -3
  329. package/packages/core/dist/providers/process.js.map +1 -1
  330. package/packages/core/dist/providers/profiles.d.ts +11 -0
  331. package/packages/core/dist/providers/profiles.d.ts.map +1 -0
  332. package/packages/core/dist/providers/profiles.js +28 -0
  333. package/packages/core/dist/providers/profiles.js.map +1 -0
  334. package/packages/core/dist/providers/provider-catalog.d.ts +72 -0
  335. package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -0
  336. package/packages/core/dist/providers/provider-catalog.js +144 -0
  337. package/packages/core/dist/providers/provider-catalog.js.map +1 -0
  338. package/packages/core/dist/providers/quota.d.ts +40 -1
  339. package/packages/core/dist/providers/quota.d.ts.map +1 -1
  340. package/packages/core/dist/providers/quota.js +288 -25
  341. package/packages/core/dist/providers/quota.js.map +1 -1
  342. package/packages/core/dist/providers/registry.d.ts +46 -3
  343. package/packages/core/dist/providers/registry.d.ts.map +1 -1
  344. package/packages/core/dist/providers/registry.js +148 -13
  345. package/packages/core/dist/providers/registry.js.map +1 -1
  346. package/packages/core/dist/providers/router.d.ts +28 -0
  347. package/packages/core/dist/providers/router.d.ts.map +1 -0
  348. package/packages/core/dist/providers/router.js +88 -0
  349. package/packages/core/dist/providers/router.js.map +1 -0
  350. package/packages/core/dist/providers/user-settings-guard.d.ts +12 -0
  351. package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -0
  352. package/packages/core/dist/providers/user-settings-guard.js +130 -0
  353. package/packages/core/dist/providers/user-settings-guard.js.map +1 -0
  354. package/packages/core/dist/runtime.d.ts +193 -7
  355. package/packages/core/dist/runtime.d.ts.map +1 -1
  356. package/packages/core/dist/runtime.js +1676 -219
  357. package/packages/core/dist/runtime.js.map +1 -1
  358. package/packages/core/dist/skills/builtin.d.ts +34 -0
  359. package/packages/core/dist/skills/builtin.d.ts.map +1 -0
  360. package/packages/core/dist/skills/builtin.js +305 -0
  361. package/packages/core/dist/skills/builtin.js.map +1 -0
  362. package/packages/core/dist/skills/shelf.d.ts +30 -0
  363. package/packages/core/dist/skills/shelf.d.ts.map +1 -0
  364. package/packages/core/dist/skills/shelf.js +159 -0
  365. package/packages/core/dist/skills/shelf.js.map +1 -0
  366. package/packages/core/dist/skills/store.d.ts +66 -4
  367. package/packages/core/dist/skills/store.d.ts.map +1 -1
  368. package/packages/core/dist/skills/store.js +105 -18
  369. package/packages/core/dist/skills/store.js.map +1 -1
  370. package/packages/core/dist/skills/suggest.d.ts +21 -0
  371. package/packages/core/dist/skills/suggest.d.ts.map +1 -0
  372. package/packages/core/dist/skills/suggest.js +150 -0
  373. package/packages/core/dist/skills/suggest.js.map +1 -0
  374. package/packages/core/dist/tools/catalog.d.ts +1 -3
  375. package/packages/core/dist/tools/catalog.d.ts.map +1 -1
  376. package/packages/core/dist/tools/catalog.js +38 -26
  377. package/packages/core/dist/tools/catalog.js.map +1 -1
  378. package/packages/core/dist/tools/hub.d.ts +136 -10
  379. package/packages/core/dist/tools/hub.d.ts.map +1 -1
  380. package/packages/core/dist/tools/hub.js +418 -24
  381. package/packages/core/dist/tools/hub.js.map +1 -1
  382. package/packages/core/dist/turns/journal.d.ts +78 -0
  383. package/packages/core/dist/turns/journal.d.ts.map +1 -0
  384. package/packages/core/dist/turns/journal.js +104 -0
  385. package/packages/core/dist/turns/journal.js.map +1 -0
  386. package/packages/core/dist/types.d.ts +1776 -12
  387. package/packages/core/dist/types.d.ts.map +1 -1
  388. package/packages/core/dist/types.js.map +1 -1
  389. package/packages/core/dist/util/blocks.d.ts +41 -0
  390. package/packages/core/dist/util/blocks.d.ts.map +1 -0
  391. package/packages/core/dist/util/blocks.js +175 -0
  392. package/packages/core/dist/util/blocks.js.map +1 -0
  393. package/packages/core/dist/util/queue.d.ts +12 -0
  394. package/packages/core/dist/util/queue.d.ts.map +1 -1
  395. package/packages/core/dist/util/queue.js +16 -0
  396. package/packages/core/dist/util/queue.js.map +1 -1
  397. package/packages/core/dist/util/time.d.ts +39 -0
  398. package/packages/core/dist/util/time.d.ts.map +1 -0
  399. package/packages/core/dist/util/time.js +71 -0
  400. package/packages/core/dist/util/time.js.map +1 -0
  401. package/packages/core/package.json +1 -1
  402. package/packages/server/dist/auth.d.ts +14 -1
  403. package/packages/server/dist/auth.d.ts.map +1 -1
  404. package/packages/server/dist/auth.js +19 -0
  405. package/packages/server/dist/auth.js.map +1 -1
  406. package/packages/server/dist/context.d.ts +35 -1
  407. package/packages/server/dist/context.d.ts.map +1 -1
  408. package/packages/server/dist/context.js +39 -10
  409. package/packages/server/dist/context.js.map +1 -1
  410. package/packages/server/dist/gateways/attachments.d.ts +32 -0
  411. package/packages/server/dist/gateways/attachments.d.ts.map +1 -0
  412. package/packages/server/dist/gateways/attachments.js +167 -0
  413. package/packages/server/dist/gateways/attachments.js.map +1 -0
  414. package/packages/server/dist/gateways/markdown.d.ts +9 -0
  415. package/packages/server/dist/gateways/markdown.d.ts.map +1 -0
  416. package/packages/server/dist/gateways/markdown.js +170 -0
  417. package/packages/server/dist/gateways/markdown.js.map +1 -0
  418. package/packages/server/dist/gateways/push.d.ts +1 -1
  419. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  420. package/packages/server/dist/gateways/push.js +420 -13
  421. package/packages/server/dist/gateways/push.js.map +1 -1
  422. package/packages/server/dist/gateways/telegram-api.d.ts +70 -1
  423. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
  424. package/packages/server/dist/gateways/telegram-api.js +140 -1
  425. package/packages/server/dist/gateways/telegram-api.js.map +1 -1
  426. package/packages/server/dist/gateways/telegram.d.ts +181 -1
  427. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  428. package/packages/server/dist/gateways/telegram.js +1572 -78
  429. package/packages/server/dist/gateways/telegram.js.map +1 -1
  430. package/packages/server/dist/gateways/threads.d.ts +84 -0
  431. package/packages/server/dist/gateways/threads.d.ts.map +1 -0
  432. package/packages/server/dist/gateways/threads.js +289 -0
  433. package/packages/server/dist/gateways/threads.js.map +1 -0
  434. package/packages/server/dist/index.d.ts +2 -1
  435. package/packages/server/dist/index.d.ts.map +1 -1
  436. package/packages/server/dist/index.js +2 -1
  437. package/packages/server/dist/index.js.map +1 -1
  438. package/packages/server/dist/listeners/imap.d.ts +13 -0
  439. package/packages/server/dist/listeners/imap.d.ts.map +1 -0
  440. package/packages/server/dist/listeners/imap.js +0 -0
  441. package/packages/server/dist/listeners/imap.js.map +1 -0
  442. package/packages/server/dist/listeners/registry.d.ts +18 -0
  443. package/packages/server/dist/listeners/registry.d.ts.map +1 -0
  444. package/packages/server/dist/listeners/registry.js +88 -0
  445. package/packages/server/dist/listeners/registry.js.map +1 -0
  446. package/packages/server/dist/listeners/types.d.ts +55 -0
  447. package/packages/server/dist/listeners/types.d.ts.map +1 -0
  448. package/packages/server/dist/listeners/types.js +2 -0
  449. package/packages/server/dist/listeners/types.js.map +1 -0
  450. package/packages/server/dist/main.js +15 -1
  451. package/packages/server/dist/main.js.map +1 -1
  452. package/packages/server/dist/routes/chat.d.ts +7 -3
  453. package/packages/server/dist/routes/chat.d.ts.map +1 -1
  454. package/packages/server/dist/routes/chat.js +8 -17
  455. package/packages/server/dist/routes/chat.js.map +1 -1
  456. package/packages/server/dist/routes/config.d.ts.map +1 -1
  457. package/packages/server/dist/routes/config.js +66 -7
  458. package/packages/server/dist/routes/config.js.map +1 -1
  459. package/packages/server/dist/routes/cron.d.ts.map +1 -1
  460. package/packages/server/dist/routes/cron.js +65 -8
  461. package/packages/server/dist/routes/cron.js.map +1 -1
  462. package/packages/server/dist/routes/dream.d.ts +22 -0
  463. package/packages/server/dist/routes/dream.d.ts.map +1 -0
  464. package/packages/server/dist/routes/dream.js +152 -0
  465. package/packages/server/dist/routes/dream.js.map +1 -0
  466. package/packages/server/dist/routes/hooks.d.ts +18 -0
  467. package/packages/server/dist/routes/hooks.d.ts.map +1 -0
  468. package/packages/server/dist/routes/hooks.js +62 -0
  469. package/packages/server/dist/routes/hooks.js.map +1 -0
  470. package/packages/server/dist/routes/listeners.d.ts +10 -0
  471. package/packages/server/dist/routes/listeners.d.ts.map +1 -0
  472. package/packages/server/dist/routes/listeners.js +12 -0
  473. package/packages/server/dist/routes/listeners.js.map +1 -0
  474. package/packages/server/dist/routes/memories.d.ts.map +1 -1
  475. package/packages/server/dist/routes/memories.js +55 -3
  476. package/packages/server/dist/routes/memories.js.map +1 -1
  477. package/packages/server/dist/routes/org.d.ts.map +1 -1
  478. package/packages/server/dist/routes/org.js +289 -49
  479. package/packages/server/dist/routes/org.js.map +1 -1
  480. package/packages/server/dist/routes/profile.d.ts.map +1 -1
  481. package/packages/server/dist/routes/profile.js +6 -3
  482. package/packages/server/dist/routes/profile.js.map +1 -1
  483. package/packages/server/dist/routes/providers.d.ts.map +1 -1
  484. package/packages/server/dist/routes/providers.js +66 -7
  485. package/packages/server/dist/routes/providers.js.map +1 -1
  486. package/packages/server/dist/routes/questions.d.ts +45 -0
  487. package/packages/server/dist/routes/questions.d.ts.map +1 -0
  488. package/packages/server/dist/routes/questions.js +73 -0
  489. package/packages/server/dist/routes/questions.js.map +1 -0
  490. package/packages/server/dist/routes/sessions.d.ts.map +1 -1
  491. package/packages/server/dist/routes/sessions.js +26 -6
  492. package/packages/server/dist/routes/sessions.js.map +1 -1
  493. package/packages/server/dist/routes/sleep.d.ts.map +1 -1
  494. package/packages/server/dist/routes/sleep.js +71 -2
  495. package/packages/server/dist/routes/sleep.js.map +1 -1
  496. package/packages/server/dist/routes/terminals.d.ts +25 -0
  497. package/packages/server/dist/routes/terminals.d.ts.map +1 -0
  498. package/packages/server/dist/routes/terminals.js +35 -0
  499. package/packages/server/dist/routes/terminals.js.map +1 -0
  500. package/packages/server/dist/routes/tools.d.ts.map +1 -1
  501. package/packages/server/dist/routes/tools.js +140 -6
  502. package/packages/server/dist/routes/tools.js.map +1 -1
  503. package/packages/server/dist/routes/updates.d.ts +10 -0
  504. package/packages/server/dist/routes/updates.d.ts.map +1 -0
  505. package/packages/server/dist/routes/updates.js +22 -0
  506. package/packages/server/dist/routes/updates.js.map +1 -0
  507. package/packages/server/dist/routes/ws.d.ts +11 -5
  508. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  509. package/packages/server/dist/routes/ws.js +168 -28
  510. package/packages/server/dist/routes/ws.js.map +1 -1
  511. package/packages/server/dist/schemas.d.ts +1177 -215
  512. package/packages/server/dist/schemas.d.ts.map +1 -1
  513. package/packages/server/dist/schemas.js +317 -12
  514. package/packages/server/dist/schemas.js.map +1 -1
  515. package/packages/server/dist/server.d.ts +7 -1
  516. package/packages/server/dist/server.d.ts.map +1 -1
  517. package/packages/server/dist/server.js +210 -3
  518. package/packages/server/dist/server.js.map +1 -1
  519. package/packages/server/dist/services/stream.d.ts +94 -5
  520. package/packages/server/dist/services/stream.d.ts.map +1 -1
  521. package/packages/server/dist/services/stream.js +9 -20
  522. package/packages/server/dist/services/stream.js.map +1 -1
  523. package/packages/server/dist/services/stt.d.ts +65 -0
  524. package/packages/server/dist/services/stt.d.ts.map +1 -0
  525. package/packages/server/dist/services/stt.js +306 -0
  526. package/packages/server/dist/services/stt.js.map +1 -0
  527. package/packages/server/dist/services/turns.d.ts +54 -0
  528. package/packages/server/dist/services/turns.d.ts.map +1 -0
  529. package/packages/server/dist/services/turns.js +186 -0
  530. package/packages/server/dist/services/turns.js.map +1 -0
  531. package/packages/server/dist/services/updates.d.ts +99 -0
  532. package/packages/server/dist/services/updates.d.ts.map +1 -0
  533. package/packages/server/dist/services/updates.js +316 -0
  534. package/packages/server/dist/services/updates.js.map +1 -0
  535. package/packages/server/package.json +1 -1
  536. package/packages/web/dist/app-icon.svg +2 -0
  537. package/packages/web/dist/apple-touch-icon.png +0 -0
  538. package/packages/web/dist/assets/abnfDiagram-O67JEVCF-D7YyFndQ.js +1 -0
  539. package/packages/web/dist/assets/arc-C_Zgk2dJ.js +1 -0
  540. package/packages/web/dist/assets/architectureDiagram-NJMV4G6O-eI0adu1B.js +36 -0
  541. package/packages/web/dist/assets/blockDiagram-BEXU5L5S-WAoOFUA9.js +140 -0
  542. package/packages/web/dist/assets/c4Diagram-YGBWAQC7-DE8Zyhng.js +38 -0
  543. package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
  544. package/packages/web/dist/assets/chunk-2Q5K7J3B-bnqLP2XD.js +1 -0
  545. package/packages/web/dist/assets/chunk-3FUC2YCW-Ck1_SVe0.js +2 -0
  546. package/packages/web/dist/assets/chunk-5VM5RSS4-hDmC41gD.js +15 -0
  547. package/packages/web/dist/assets/chunk-GTNCS2PH-PoWvfCrT.js +88 -0
  548. package/packages/web/dist/assets/chunk-GWA4HPMP-D3V0IG43.js +1 -0
  549. package/packages/web/dist/assets/chunk-JWPE2WC7-BryfpHM5.js +1 -0
  550. package/packages/web/dist/assets/chunk-NETBCI7D-8ic1iEdT.js +1 -0
  551. package/packages/web/dist/assets/chunk-WEXAMYUT-nM8tmQT2.js +1 -0
  552. package/packages/web/dist/assets/chunk-XXDRQBXY-Do28F482.js +1 -0
  553. package/packages/web/dist/assets/classDiagram-v2-NBCMYWYE-Bop9oNNO.js +217 -0
  554. package/packages/web/dist/assets/cose-bilkent-JH36ORCC-a7f_bpnt.js +1 -0
  555. package/packages/web/dist/assets/cynefin-OW5HDTMX-DnArcis_.js +178 -0
  556. package/packages/web/dist/assets/cynefinDiagram-VND7K2PF-vEuTb1GD.js +62 -0
  557. package/packages/web/dist/assets/cytoscape.esm-Ix0LnXOy.js +331 -0
  558. package/packages/web/dist/assets/dagre-6A5THRUB-BgG4MynJ.js +4 -0
  559. package/packages/web/dist/assets/diagram-22UHCM2B-DRCQpafv.js +200 -0
  560. package/packages/web/dist/assets/diagram-3UASUU5V-BKgmAXde.js +24 -0
  561. package/packages/web/dist/assets/diagram-ATOU4E4O-B6Hsy36X.js +3 -0
  562. package/packages/web/dist/assets/diagram-CDSNMT55-JflyfyoB.js +30 -0
  563. package/packages/web/dist/assets/diagram-MLGK6HIB-Dd2QPJjT.js +24 -0
  564. package/packages/web/dist/assets/diagram-MPIPVDR6-DE5QU60x.js +41 -0
  565. package/packages/web/dist/assets/draco_decoder-C32yEggz.wasm +0 -0
  566. package/packages/web/dist/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
  567. package/packages/web/dist/assets/draco_decoder-fzg4nYZr.js +34 -0
  568. package/packages/web/dist/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
  569. package/packages/web/dist/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
  570. package/packages/web/dist/assets/ebnfDiagram-ZINNZB2B-D7AQ741b.js +1 -0
  571. package/packages/web/dist/assets/elk-276RUBZZ-CeewBVLF.js +27 -0
  572. package/packages/web/dist/assets/erDiagram-OPXOYQCR-mLLYkZ5c.js +99 -0
  573. package/packages/web/dist/assets/flowDiagram-KWPJA3E3-DtpSpsQN.js +213 -0
  574. package/packages/web/dist/assets/ganttDiagram-FUAMR5RP-1_lh-3ky.js +292 -0
  575. package/packages/web/dist/assets/gitGraphDiagram-X574FWY7-DoPXZuT5.js +106 -0
  576. package/packages/web/dist/assets/graph-Bn3Yngep.js +1 -0
  577. package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
  578. package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
  579. package/packages/web/dist/assets/infoDiagram-VRGFBTTK-DQpRGGiD.js +2 -0
  580. package/packages/web/dist/assets/ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js +70 -0
  581. package/packages/web/dist/assets/journeyDiagram-ZHPQQLJL-Bg-oeFjb.js +139 -0
  582. package/packages/web/dist/assets/kanban-definition-PNTS6WVX-BnpI4VH8.js +89 -0
  583. package/packages/web/dist/assets/katex-C5jXJg4s.js +257 -0
  584. package/packages/web/dist/assets/mermaid.core-BwBKxlRA.js +313 -0
  585. package/packages/web/dist/assets/mindmap-definition-NLK3R4M7-NBnnxEoO.js +96 -0
  586. package/packages/web/dist/assets/pegDiagram-GJSIUBJH-RrXXbIvO.js +1 -0
  587. package/packages/web/dist/assets/pieDiagram-5QR66LMP-B27q6Gso.js +39 -0
  588. package/packages/web/dist/assets/quadrantDiagram-O4NWA36T-DGDsdur2.js +7 -0
  589. package/packages/web/dist/assets/railroadDiagram-XR7U4H2S-GdjkE3mI.js +1 -0
  590. package/packages/web/dist/assets/requirementDiagram-PLB6GJNP-DjK0GfgO.js +84 -0
  591. package/packages/web/dist/assets/sankeyDiagram-IPEJSGJF-BG_AIkwF.js +40 -0
  592. package/packages/web/dist/assets/scene-D4LPicHk.js +4620 -0
  593. package/packages/web/dist/assets/sequenceDiagram-PO4LG4MO-CIQwUb4y.js +169 -0
  594. package/packages/web/dist/assets/sizeCapture-INFHLROL-bpIoPxdJ.js +1 -0
  595. package/packages/web/dist/assets/stateDiagram-v2-GCMORJYK-8hYXvPPv.js +291 -0
  596. package/packages/web/dist/assets/swimlanes-2SLR337P-gfflUMF9.js +1 -0
  597. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
  598. package/packages/web/dist/assets/timeline-definition-EJHVYXUP-PHMNoGTZ.js +120 -0
  599. package/packages/web/dist/assets/usecaseDiagram-POWQR4AR-B2j5iteO.js +370 -0
  600. package/packages/web/dist/assets/vennDiagram-UO4OBE2U-BzxtZ-_2.js +34 -0
  601. package/packages/web/dist/assets/wardleyDiagram-VNRHLVJA-DL7YbMpY.js +78 -0
  602. package/packages/web/dist/assets/xychartDiagram-PMCCYNJV-CisgP1cT.js +7 -0
  603. package/packages/web/dist/draco/draco_decoder.js +33 -0
  604. package/packages/web/dist/draco/draco_decoder.wasm +0 -0
  605. package/packages/web/dist/draco/draco_wasm_wrapper.js +116 -0
  606. package/packages/web/dist/favicon-16.png +0 -0
  607. package/packages/web/dist/favicon-32.png +0 -0
  608. package/packages/web/dist/favicon-48.png +0 -0
  609. package/packages/web/dist/favicon.ico +0 -0
  610. package/packages/web/dist/favicon.svg +1 -1
  611. package/packages/web/dist/icon-192.png +0 -0
  612. package/packages/web/dist/icon-512.png +0 -0
  613. package/packages/web/dist/index.html +12 -4
  614. package/packages/web/dist/logo-light.svg +1 -1
  615. package/packages/web/dist/logo-mono.svg +2 -0
  616. package/packages/web/dist/logo-stacked-light.svg +2 -0
  617. package/packages/web/dist/logo-stacked.svg +2 -0
  618. package/packages/web/dist/logo-white.svg +2 -0
  619. package/packages/web/dist/logo.svg +1 -1
  620. package/packages/web/dist/mark-light.svg +1 -1
  621. package/packages/web/dist/mark-mono.svg +2 -0
  622. package/packages/web/dist/mark-small-light.svg +2 -0
  623. package/packages/web/dist/mark-small.svg +2 -0
  624. package/packages/web/dist/mark-white.svg +2 -0
  625. package/packages/web/dist/mark.svg +1 -1
  626. package/packages/web/dist/models/LICENSE.txt +5 -0
  627. package/packages/web/dist/models/brain.glb +0 -0
  628. package/packages/web/dist/site.webmanifest +23 -0
  629. package/packages/web/dist/wordmark-light.svg +2 -0
  630. package/packages/web/dist/wordmark.svg +2 -0
  631. package/packages/web/package.json +1 -1
  632. package/scripts/rookery.mjs +204 -122
  633. package/scripts/updater.mjs +227 -0
  634. package/packages/cli/dist/tui/components/Wordmark.d.ts +0 -35
  635. package/packages/cli/dist/tui/components/Wordmark.d.ts.map +0 -1
  636. package/packages/cli/dist/tui/components/Wordmark.js +0 -81
  637. package/packages/cli/dist/tui/components/Wordmark.js.map +0 -1
  638. package/packages/core/dist/agents/orchestrator.d.ts +0 -24
  639. package/packages/core/dist/agents/orchestrator.d.ts.map +0 -1
  640. package/packages/core/dist/agents/orchestrator.js +0 -88
  641. package/packages/core/dist/agents/orchestrator.js.map +0 -1
  642. package/packages/core/dist/agents/roles.d.ts +0 -21
  643. package/packages/core/dist/agents/roles.d.ts.map +0 -1
  644. package/packages/core/dist/agents/roles.js +0 -81
  645. package/packages/core/dist/agents/roles.js.map +0 -1
  646. package/packages/core/dist/agents/team.d.ts +0 -105
  647. package/packages/core/dist/agents/team.d.ts.map +0 -1
  648. package/packages/core/dist/agents/team.js +0 -623
  649. package/packages/core/dist/agents/team.js.map +0 -1
  650. package/packages/core/dist/providers/codex.d.ts +0 -10
  651. package/packages/core/dist/providers/codex.d.ts.map +0 -1
  652. package/packages/core/dist/providers/codex.js +0 -375
  653. package/packages/core/dist/providers/codex.js.map +0 -1
  654. package/packages/core/dist/tools/browser.d.ts +0 -20
  655. package/packages/core/dist/tools/browser.d.ts.map +0 -1
  656. package/packages/core/dist/tools/browser.js +0 -72
  657. package/packages/core/dist/tools/browser.js.map +0 -1
  658. package/packages/server/dist/routes/agents.d.ts +0 -5
  659. package/packages/server/dist/routes/agents.d.ts.map +0 -1
  660. package/packages/server/dist/routes/agents.js +0 -6
  661. package/packages/server/dist/routes/agents.js.map +0 -1
  662. package/packages/server/dist/routes/team.d.ts +0 -11
  663. package/packages/server/dist/routes/team.d.ts.map +0 -1
  664. package/packages/server/dist/routes/team.js +0 -36
  665. package/packages/server/dist/routes/team.js.map +0 -1
  666. package/packages/web/dist/assets/3d-force-graph-BPZmoydi.js +0 -1163
  667. package/packages/web/dist/assets/index-IBSTzK7-.js +0 -1255
  668. package/packages/web/dist/assets/index-qUXUui7W.css +0 -1
  669. package/packages/web/dist/assets/three-spritetext-B9ZIW7c-.js +0 -4
  670. package/packages/web/dist/assets/three.module-cmFfBtHS.js +0 -4228
@@ -2,22 +2,44 @@ import { EventEmitter } from 'node:events';
2
2
  import { ASSISTANT_MEMORY_OWNER, } from '../types.js';
3
3
  import { silentLogger } from '../logger.js';
4
4
  import { entitySlug } from './store.js';
5
- import { smallModelFor } from './extractor.js';
6
- import { linkEntities, normalizeTokens, similarity } from './gate.js';
7
- import { MEMORY_KINDS } from './recall.js';
5
+ import { parseCandidates, smallModelFor } from './extractor.js';
6
+ import { admitCandidates, confirmedBy, linkEntities, normalizeTokens, similarity } from './gate.js';
7
+ import { MEMORY_KINDS, recall } from './recall.js';
8
+ import { admit } from './dream/admission.js';
9
+ import { buildAggregates, proposeCandidates, withIncumbent, } from './dream/candidate.js';
10
+ import { DEFAULT_SPLIT_RATES, agreementReport, renderEvidenceDigest, selectOnTraining, splitPool, } from './dream/evaluate.js';
11
+ import { gainFrom, correctionLabels, locateTurn, mergeLabels } from './dream/label.js';
12
+ import { measure } from './dream/measure.js';
13
+ import { factoryPolicy, resolvePolicy } from './dream/policy.js';
14
+ import { buildGrid, runGridProbe } from './dream/probe.js';
15
+ import { applyPromotion, freezeFor, freezeReasonFor, promotionDecision, renderRationale, } from './dream/promote.js';
16
+ import { pipelineAgent, pipelineAssistant } from './dream/score.js';
17
+ import { NIGHT_PHASES, yieldRates } from './dream/slots.js';
18
+ import { SkillStore, skillSlug } from '../skills/store.js';
8
19
  export class SleepRunner extends EventEmitter {
9
20
  #store;
10
21
  #registry;
11
22
  #config;
12
23
  #log;
24
+ #onPromotion;
13
25
  /** One night at a time per bank. */
14
26
  #running = new Map();
27
+ /**
28
+ * The run-global dream wallet (concept 9.4). With `sleep.scope: 'all'` the
29
+ * runtime runs one night per owner, sequentially, in one loop - so a
30
+ * per-run ceiling would multiply the candidate calls by the number of
31
+ * banks. This counter spans those runs: a window opens with the first
32
+ * dream call and closes after `DREAM_NIGHT_WINDOW_MS` of quiet, which is
33
+ * what "one night" means for a process that has no calendar.
34
+ */
35
+ #dreamCalls = { since: 0, spent: 0 };
15
36
  constructor(options) {
16
37
  super();
17
38
  this.#store = options.store;
18
39
  this.#registry = options.registry;
19
40
  this.#config = options.config;
20
41
  this.#log = options.logger ?? silentLogger;
42
+ this.#onPromotion = options.onPromotion;
21
43
  }
22
44
  isRunning(owner = ASSISTANT_MEMORY_OWNER) {
23
45
  return this.#running.has(owner);
@@ -59,16 +81,53 @@ export class SleepRunner extends EventEmitter {
59
81
  }
60
82
  return owners;
61
83
  }
62
- /** Roll back one night. Delegated to the store, which does it atomically. */
84
+ /**
85
+ * Roll back one night.
86
+ *
87
+ * The bank is the store's job and it does that part atomically. The skills
88
+ * cannot join that transaction - they are files - so they are put back
89
+ * afterwards, from the snapshots the run took before it wrote over them. A
90
+ * snapshot with no content means the skill did not exist that evening, so
91
+ * undoing its creation deletes the folder again.
92
+ *
93
+ * Order matters: the memories go back first. If restoring a file then
94
+ * fails, the bank is already consistent and the skill is the only thing
95
+ * left standing - the opposite order would leave a skill pointing at
96
+ * memories that no longer say what it was rewritten for.
97
+ *
98
+ * `policies` is the night's promotions, demoted inside the store's own
99
+ * transaction (10.4) rather than here: a parameter set that went in force
100
+ * tonight has to come out of force in the same breath as the memories it
101
+ * was measured on. What no undo reaches is the counters - `access_count`
102
+ * and `usefulness` are monotone and carry no history, so the honest
103
+ * sentence stays "reversible in parameters, not in counters" (E11).
104
+ */
63
105
  undo(runId) {
64
106
  const result = this.#store.undoSleepRun(runId);
65
- if (result) {
66
- const run = this.#store.getSleepRun(runId);
67
- if (run)
68
- this.#announce(run, 'undone');
69
- this.#log.info('Sleep run undone', { run: runId, ...result });
107
+ if (!result)
108
+ return null;
109
+ let skills = 0;
110
+ const store = new SkillStore(this.#config.skillsDir);
111
+ const seen = new Set();
112
+ // Oldest snapshot per name: the state as it stood before the night began,
113
+ // even if one run both wrote and later revised the same skill.
114
+ for (const version of this.#store.skillVersionsForRun(runId)) {
115
+ if (seen.has(version.skill))
116
+ continue;
117
+ seen.add(version.skill);
118
+ try {
119
+ if (store.restore(version.skill, version.content))
120
+ skills += 1;
121
+ }
122
+ catch (cause) {
123
+ this.#log.warn('Could not put a skill back', { skill: version.skill, error: cause.message });
124
+ }
70
125
  }
71
- return result;
126
+ const run = this.#store.getSleepRun(runId);
127
+ if (run)
128
+ this.#announce(run, 'undone');
129
+ this.#log.info('Sleep run undone', { run: runId, ...result, skills });
130
+ return { ...result, skills };
72
131
  }
73
132
  /**
74
133
  * One night on one bank. Never throws: a failed phase is recorded on the
@@ -94,15 +153,53 @@ export class SleepRunner extends EventEmitter {
94
153
  this.#log.info('Sleep started', { owner, run: run.id });
95
154
  const counters = {
96
155
  readCount: 0,
156
+ replayedCount: 0,
157
+ learnedCount: 0,
97
158
  mergedCount: 0,
98
159
  dormantCount: 0,
99
160
  edgeCount: 0,
100
161
  insightCount: 0,
162
+ skillCount: 0,
163
+ skillRevisedCount: 0,
101
164
  conflictCount: 0,
102
165
  resolvedCount: 0,
166
+ // The dream counters (fifth of the six places in step): initialised
167
+ // here or `counters.dreamFramesScored` is a type error before anything
168
+ // ever increments it. `dreamCandidates` stays 0 in stage 1 - its writer
169
+ // is the Phase 3 candidate counter, and the column must not quietly
170
+ // change meaning before then.
171
+ dreamTracesSeen: 0,
172
+ dreamFramesScored: 0,
173
+ dreamCandidates: 0,
174
+ // Stage 2's two: what the label writers wrote tonight, and whether a
175
+ // parameter set went in force. Both are 0 with `dream.enabled` off,
176
+ // because with it off nothing that could move them ever runs.
177
+ dreamPromoted: 0,
178
+ dreamLabelsWritten: 0,
103
179
  modelCalls: 0,
104
180
  };
181
+ /**
182
+ * Calls and payoff per phase, as this night actually spent them - the
183
+ * raw material of the `budget` slot (concept 7.1). Measured every night,
184
+ * carried only when `dream.slots` says so.
185
+ */
186
+ const spend = {
187
+ condense: { calls: 0, value: 0 },
188
+ resolve: { calls: 0, value: 0 },
189
+ link: { calls: 0, value: 0 },
190
+ reflect: { calls: 0, value: 0 },
191
+ revise: { calls: 0, value: 0 },
192
+ practise: { calls: 0, value: 0 },
193
+ };
105
194
  let error;
195
+ // The one dream line the stored report carries beyond describeSleep:
196
+ // the import/reindex invalidation notice, whose numbers live only in the
197
+ // probe result (concept 3.3).
198
+ let dreamReportSuffix = '';
199
+ // Label passes that failed and were skipped instead of ending the night
200
+ // (10.5). Counted here because both writers sit inside phases that must
201
+ // go on without them.
202
+ let labelFailures = 0;
106
203
  try {
107
204
  const providerId = await this.#resolveProvider(input.provider);
108
205
  const settings = this.#config.memory.sleep;
@@ -110,10 +207,71 @@ export class SleepRunner extends EventEmitter {
110
207
  const provider = providerId ? this.#registry.get(providerId) : null;
111
208
  const model = providerId ? settings.model.trim() || smallModelFor(providerId) : undefined;
112
209
  const insightModel = settings.insightModel.trim() || model;
113
- counters.readCount = this.#store.liveMemories(owner).length;
210
+ const live = this.#store.liveMemories(owner);
211
+ counters.readCount = live.length;
114
212
  if (!provider) {
115
213
  this.#log.warn('Sleep ran without a provider; only light sleep happened', { owner });
116
214
  }
215
+ // The replay list is measured first, because the read has to happen
216
+ // before anything else: what the night harvests there should be
217
+ // condensed tonight, not tomorrow.
218
+ let budgets = null;
219
+ let replaySessions = [];
220
+ if (provider) {
221
+ replaySessions = owner === ASSISTANT_MEMORY_OWNER ? this.#replayCandidates(owner) : [];
222
+ }
223
+ /* ---- replay: the day, read again and properly. Before the cycles ----
224
+ ---- so tonight's harvest is condensed tonight, not tomorrow. ---- */
225
+ if (provider) {
226
+ this.#phase(run.id, 'replay', counters, 1);
227
+ const replayed = await this.#replay(provider, smallModelFor(providerId), model, owner, run.id, replaySessions, controller.signal);
228
+ counters.replayedCount += replayed.read;
229
+ counters.learnedCount += replayed.learned;
230
+ counters.modelCalls += replayed.calls;
231
+ counters.dreamLabelsWritten += replayed.labels;
232
+ labelFailures += replayed.labelFailures;
233
+ dreamReportSuffix += this.#correctionPrecision(replayed);
234
+ // The bank changed, so the figure the run reports as "looked at" has
235
+ // to be taken after the harvest, not before it.
236
+ counters.readCount = this.#store.liveMemories(owner).length;
237
+ this.#phase(run.id, 'replay', counters, 1);
238
+ this.#throwIfAborted(controller.signal);
239
+ }
240
+ // The night's wallet is filled by need, not by the clock, and it is
241
+ // filled HERE - after the replay, not before it. The re-read grows the
242
+ // bank, surfaces contradictions and pulls corrections out of the day's
243
+ // words, and that is precisely the work the later phases exist to do;
244
+ // a budget measured before the read funds the night for a quieter day
245
+ // than the one it just had. The arithmetic is database-only, but it is
246
+ // not free: #demand clusters the living bank pair by pair, and the
247
+ // dream probe below reads and scores every stored frame. Both carry
248
+ // their own ceilings (#demand's phase budgets, the probe's
249
+ // dream.maxEvalMs), so "measures itself" means "costs up to a declared
250
+ // bound", never "costs nothing".
251
+ if (provider) {
252
+ const demand = this.#demand(owner, this.#store.liveMemories(owner));
253
+ budgets = allocateNightBudget(demand, settings.nightBudget, {
254
+ condense: settings.maxMergeCalls,
255
+ resolve: settings.maxResolveCalls,
256
+ link: settings.maxLinkCalls,
257
+ reflect: settings.insights > 0 ? 2 : 0,
258
+ revise: settings.skillRevisions,
259
+ practise: settings.skills,
260
+ });
261
+ this.#log.info('Night measured', { owner, demand, budgets });
262
+ }
263
+ /* ---- the dream: the measurement of the retrieval policy, and the ----
264
+ ---- one place a parameter set can go in force. Wedged here on ----
265
+ ---- purpose: BEFORE the cycle loop (R7), so that the freshness ----
266
+ ---- side sees the bank the day left rather than the supersessions ----
267
+ ---- #condense is about to write, and ABOVE the provider guard ----
268
+ ---- inside the loop (R8), so the whole of it also runs in a night ----
269
+ ---- without a provider - the one night where it is the only thing ----
270
+ ---- that could run at all. Stage 2 dreams for the assistant's ----
271
+ ---- bank only (R18); agent frames would be cost without a night ----
272
+ ---- that ever scores them. ---- */
273
+ const dreamSettings = this.#config.memory.dream;
274
+ dreamReportSuffix += await this.#dream(owner, run.id, counters, controller.signal);
117
275
  for (let cycle = 1; cycle <= cycles; cycle += 1) {
118
276
  /* -------- light sleep: bookkeeping, no model, costs nothing -------- */
119
277
  this.#phase(run.id, 'light', counters, cycle);
@@ -130,42 +288,109 @@ export class SleepRunner extends EventEmitter {
130
288
  }
131
289
  this.#store.recountEntities(owner);
132
290
  this.#throwIfAborted(controller.signal);
133
- if (!provider)
291
+ if (!provider || !budgets)
134
292
  continue;
135
293
  /* ---- deep sleep: filing. What repeats becomes one, what cannot ----
136
294
  ---- both be true gets decided. ---- */
137
295
  this.#phase(run.id, 'deep', counters, cycle);
138
296
  const clusters = this.#cluster(owner, this.#store.liveMemories(owner));
139
- const condensed = await this.#condense(provider, model, owner, run.id, clusters, controller.signal, share(settings.maxMergeCalls, cycles, cycle, 'early'));
297
+ const condensed = await this.#condense(provider, model, owner, run.id, clusters, controller.signal, share(budgets.condense, cycles, cycle, 'early'));
140
298
  counters.mergedCount += condensed.merged;
141
299
  counters.dormantCount += condensed.retired;
142
300
  counters.modelCalls += condensed.calls;
301
+ counters.dreamLabelsWritten += condensed.labels;
302
+ labelFailures += condensed.labelFailures;
303
+ spend.condense.calls += condensed.calls;
304
+ spend.condense.value += condensed.merged;
143
305
  // Contradictions the previous cycle (or an earlier night) turned up.
144
- const settled = await this.#resolve(provider, model, owner, run.id, controller.signal, share(settings.maxResolveCalls, cycles, cycle, 'late'));
306
+ const settled = await this.#resolve(provider, model, owner, run.id, controller.signal, share(budgets.resolve, cycles, cycle, 'late'));
145
307
  counters.resolvedCount += settled.resolved;
146
308
  counters.dormantCount += settled.retired;
147
309
  counters.mergedCount += settled.merged;
148
310
  counters.modelCalls += settled.calls;
311
+ spend.resolve.calls += settled.calls;
312
+ spend.resolve.value += settled.resolved;
149
313
  this.#phase(run.id, 'deep', counters, cycle);
150
314
  this.#throwIfAborted(controller.signal);
151
315
  /* ---- dream sleep: the loose, associative part. Connections ----
152
316
  ---- across distance, and what the week adds up to. ---- */
153
317
  this.#phase(run.id, 'rem', counters, cycle);
154
- const linked = await this.#link(provider, model, owner, run.id, controller.signal, share(3, cycles, cycle, 'late'));
318
+ const linked = await this.#link(provider, model, owner, run.id, controller.signal, share(budgets.link, cycles, cycle, 'late'));
155
319
  counters.edgeCount += linked.edges;
156
320
  counters.conflictCount += linked.conflicts;
157
321
  counters.modelCalls += linked.calls;
322
+ spend.link.calls += linked.calls;
323
+ spend.link.value += linked.edges;
158
324
  // Insights come last, once the bank is as tidy as it will get tonight.
159
325
  if (cycle === cycles) {
160
- const insight = await this.#reflect(provider, insightModel, owner, run.id, controller.signal);
326
+ const insight = await this.#reflect(provider, insightModel, owner, run.id, controller.signal, budgets.reflect);
161
327
  counters.insightCount += insight.written;
162
328
  counters.edgeCount += insight.edges;
163
329
  counters.modelCalls += insight.calls;
330
+ spend.reflect.calls += insight.calls;
331
+ spend.reflect.value += insight.written;
332
+ /* ---- the candidate writer (concept 6.2, 9.4). Here, and not ----
333
+ ---- earlier: the order is deliberate - first it has to be ----
334
+ ---- settled how well the search control works, then ----
335
+ ---- procedures get rewritten. Its wallet is run-global ----
336
+ ---- (`dream.maxCallsPerNight` across ALL owners), because ----
337
+ ---- with `sleep.scope: 'all'` the runtime runs one night per ----
338
+ ---- bank and a per-run ceiling would multiply by the owner ----
339
+ ---- count. What it writes are proposals, not policies: the ----
340
+ ---- night that measures them is the next one, above the ----
341
+ ---- provider guard, which is what keeps the promotion path ----
342
+ ---- model-free. ---- */
343
+ const proposed = await this.#propose(provider, owner, run.id, controller.signal, this.#dreamBudget());
344
+ counters.dreamCandidates += proposed.written;
345
+ counters.modelCalls += proposed.calls;
346
+ this.#spendDreamCalls(proposed.calls);
347
+ // And after the insights, the two steps that leave something behind
348
+ // outside the bank. Repair comes first on purpose: a procedure that
349
+ // has gone stale is actively misleading whoever opens it next,
350
+ // which is worth more than a ninth procedure nobody asked for.
351
+ const revised = await this.#revise(provider, insightModel, owner, run.id, controller.signal, budgets.revise);
352
+ counters.skillRevisedCount += revised.written;
353
+ counters.modelCalls += revised.calls;
354
+ spend.revise.calls += revised.calls;
355
+ spend.revise.value += revised.written;
356
+ const practised = await this.#practise(provider, insightModel, owner, run.id, controller.signal, budgets.practise);
357
+ counters.skillCount += practised.written;
358
+ counters.modelCalls += practised.calls;
359
+ spend.practise.calls += practised.calls;
360
+ spend.practise.value += practised.written;
164
361
  }
165
362
  this.#phase(run.id, 'rem', counters, cycle);
166
363
  this.#throwIfAborted(controller.signal);
167
364
  }
168
365
  this.#store.recountEntities(owner);
366
+ this.#measureSlots(owner, spend);
367
+ if (labelFailures > 0) {
368
+ // Said out loud rather than swallowed: the consolidation went on,
369
+ // and the night is short of labels it expected to have.
370
+ dreamReportSuffix +=
371
+ ' ' + plural(labelFailures, 'label pass', 'label passes') +
372
+ ' failed and left no labels; the consolidation went on.';
373
+ }
374
+ /* ---- the dream's two retention clocks (concept 8.7, S21). Frames ----
375
+ ---- and the episode index go after `frameRetainDays`, because ----
376
+ ---- both point at verbatim text - a frame quotes the rows it ----
377
+ ---- froze, an episode points straight at journal steps. Traces, ----
378
+ ---- touches, labels and evaluations go after `retainDays`: they ----
379
+ ---- are small, they carry the calibration, and none of them ----
380
+ ---- holds a word anybody wrote. Every sweep runs in batches of ----
381
+ ---- 500 with its own transaction, so the one connection is never ----
382
+ ---- locked for long. Hygiene, not measurement: this runs with ----
383
+ ---- the dream switched off too, because a verbatim store must ----
384
+ ---- not outlive its retention window just because measuring was ----
385
+ ---- turned off (R17). ---- */
386
+ const endedAt = Date.now();
387
+ const frameBefore = endedAt - clampDays(dreamSettings.frameRetainDays) * 24 * 60 * 60 * 1000;
388
+ const traceBefore = endedAt - clampDays(dreamSettings.retainDays) * 24 * 60 * 60 * 1000;
389
+ this.#store.sweepDreamFrames(frameBefore);
390
+ this.#store.sweepDreamEpisodes(frameBefore);
391
+ this.#store.sweepDreamTraces(traceBefore);
392
+ this.#store.sweepDreamLabels(traceBefore);
393
+ this.#store.sweepDreamEvals(traceBefore);
169
394
  }
170
395
  catch (cause) {
171
396
  error = cause.message;
@@ -180,7 +405,7 @@ export class SleepRunner extends EventEmitter {
180
405
  status: error ? 'failed' : 'done',
181
406
  finishedAt: finished,
182
407
  durationMs: finished - run.startedAt,
183
- report: describeSleep(counters),
408
+ report: describeSleep(counters) + dreamReportSuffix,
184
409
  error,
185
410
  }) ?? run;
186
411
  this.#announce(updated, 'finished');
@@ -194,6 +419,242 @@ export class SleepRunner extends EventEmitter {
194
419
  });
195
420
  return updated;
196
421
  }
422
+ /* ------------------------------ phase 0 ------------------------------ */
423
+ /**
424
+ * How much work the night actually has, per phase, in model calls.
425
+ *
426
+ * Everything here is database arithmetic, but arithmetic is not free: the
427
+ * condense demand clusters the living bank pair by pair, and the dream
428
+ * probe that follows the wallet reads and scores every stored frame under
429
+ * its own wall clock (`dream.maxEvalMs`). The numbers are ceilings on what
430
+ * each phase may ask for, not promises: a phase that finds less work than
431
+ * its budget simply stops early, exactly as before. The replay pass is
432
+ * measured separately (`#replayCandidates`), because it runs before this
433
+ * and changes what there is to measure.
434
+ */
435
+ #demand(owner, live) {
436
+ const settings = this.#config.memory.sleep;
437
+ const since = this.#store.lastSleepAt(owner);
438
+ const condense = this.#cluster(owner, live).length;
439
+ const resolve = this.#openContradictions(owner).length;
440
+ const fresh = this.#store
441
+ .listMemories({ owner, since: since || undefined, limit: 150, includeDormant: false })
442
+ .filter((memory) => !memory.supersededBy);
443
+ // One link call reads up to 25 memories in one portion.
444
+ const link = Math.ceil(fresh.length / 25);
445
+ // Two passes over the same pool, on purpose: one looks for patterns in
446
+ // the user, one in the work - neither prompt sees the other's angle.
447
+ const week = Date.now() - settings.insightWindowDays * 24 * 60 * 60 * 1000;
448
+ const reflect = settings.insights > 0 &&
449
+ this.#store
450
+ .listMemories({ owner, since: week, limit: 80, includeDormant: false })
451
+ .filter((memory) => memory.kind !== 'insight').length >= 4
452
+ ? 2
453
+ : 0;
454
+ const revise = this.#skillSuspects(owner).length;
455
+ const practise = settings.skills > 0 && live.length >= 6 ? 1 : 0;
456
+ return { condense, resolve, link, reflect, revise, practise };
457
+ }
458
+ /**
459
+ * The conversations worth reading again tonight, oldest pending first.
460
+ *
461
+ * The scan reaches further back than one night on purpose: a machine that
462
+ * was off for a few days, or a bank whose last night failed halfway,
463
+ * should not silently drop what happened in between. The filter is the
464
+ * same one the deep read applies - at least two real user turns - so the
465
+ * demand number means "conversations that would actually be read".
466
+ */
467
+ #replayCandidates(owner) {
468
+ const budget = this.#config.memory.sleep.replaySessions;
469
+ if (budget <= 0 || owner !== ASSISTANT_MEMORY_OWNER)
470
+ return [];
471
+ const since = this.#store.lastSleepAt(owner);
472
+ const candidates = [];
473
+ for (const session of this.#store.sessionsActiveSince(since, 150)) {
474
+ const spoken = this.#store
475
+ .getMessages(session.id)
476
+ .filter((message) => message.role === 'user' && message.content.trim());
477
+ // Nothing was said, or barely: "thanks" followed by "you're welcome"
478
+ // holds nothing durable no matter how expensively it is read.
479
+ if (spoken.length < 2)
480
+ continue;
481
+ candidates.push(session);
482
+ if (candidates.length >= budget)
483
+ break;
484
+ }
485
+ return candidates;
486
+ }
487
+ /** Contradiction pairs neither side of which has been settled yet. */
488
+ #openContradictions(owner) {
489
+ return this.#store
490
+ .listEdges(owner, 500)
491
+ .filter((edge) => edge.relation === 'contradicts')
492
+ .map((edge) => {
493
+ const a = this.#store.getMemory(edge.srcId);
494
+ const b = this.#store.getMemory(edge.dstId);
495
+ return { edge, a, b };
496
+ })
497
+ .filter((pair) => pair.a && pair.b &&
498
+ !pair.a.dormantAt && !pair.b.dormantAt &&
499
+ !pair.a.forgotten && !pair.b.forgotten)
500
+ .map((pair) => ({ srcId: pair.edge.srcId, dstId: pair.edge.dstId }));
501
+ }
502
+ /**
503
+ * Read the day again.
504
+ *
505
+ * Every conversation is already extracted from once, right after each turn -
506
+ * by the smallest model available, at low effort, with both sides clipped to
507
+ * four thousand characters, capped at three candidates. That pass sees one
508
+ * exchange at a time and never the shape of a conversation, so whatever only
509
+ * becomes visible across the whole of one is structurally invisible to it: a
510
+ * preference mentioned in passing early and only acted on much later, a
511
+ * decision that emerged rather than being stated, and above all a
512
+ * correction.
513
+ *
514
+ * At night none of those constraints apply. There is no one waiting, so the
515
+ * transcript can be read whole, by a model worth paying for.
516
+ *
517
+ * Cost is kept sane by not spending that model on everything. A cheap pass
518
+ * sorts first - most conversations hold nothing durable at all, and finding
519
+ * that out should cost a fraction of a cent, not a full analysis. Only what
520
+ * survives triage gets read properly.
521
+ *
522
+ * The evidence rule is not relaxed here. The night must quote the user just
523
+ * as the day does; a better model is allowed to find more, not to invent
524
+ * more.
525
+ *
526
+ * And this is where the dream gets its best label (concept 4.2a). A
527
+ * correction is the one source that can say something about a memory the
528
+ * incumbent did NOT deliver, which is the single place the missing-label
529
+ * bias does not reach - so every correction admitted here is located in the
530
+ * transcript, written with its turn reference, and turned into labels
531
+ * against the frames of that session. An ambiguous quote is never guessed
532
+ * at: it lands session-wide, counts for the agreement check and the
533
+ * calibration, and never for a gain (S3).
534
+ */
535
+ async #replay(provider, triageModel, deepModel, owner, runId, sessions, signal) {
536
+ const idle = {
537
+ read: 0,
538
+ learned: 0,
539
+ corrections: 0,
540
+ labelled: 0,
541
+ labels: 0,
542
+ labelFailures: 0,
543
+ calls: 0,
544
+ };
545
+ // Corrections written from here on are this replay's, whatever else the
546
+ // owner's table already holds - the label pass reads them back by id
547
+ // afterwards, because `addCorrection` hands none out.
548
+ const since = Date.now();
549
+ // Only the assistant's own bank. An agent learns from its assignments,
550
+ // which its controller already extracts from, and there is no user in
551
+ // those transcripts to quote. The candidate list arrives pre-measured
552
+ // from `#replayCandidates`, which applied the same two-turn filter the
553
+ // budget was sized against.
554
+ if (signal.aborted || owner !== ASSISTANT_MEMORY_OWNER || !sessions.length)
555
+ return idle;
556
+ let read = 0;
557
+ let learned = 0;
558
+ let corrections = 0;
559
+ let calls = 0;
560
+ for (const session of sessions) {
561
+ if (signal.aborted)
562
+ break;
563
+ const messages = this.#store.getMessages(session.id).filter((message) => message.content.trim());
564
+ const spoken = messages.filter((message) => message.role === 'user');
565
+ // Nothing was said, or barely: no model needed to know there is nothing
566
+ // durable in "thanks" followed by "you're welcome".
567
+ if (spoken.length < 2)
568
+ continue;
569
+ const said = spoken.map((message) => message.content).join('\n');
570
+ // Triage, on the user's turns alone and heavily clipped. The question is
571
+ // only "is there anything here worth a proper look", and the assistant's
572
+ // side cannot answer that - nothing it said may back a memory anyway.
573
+ const verdict = await ask(provider, TRIAGE_PROMPT + '\n\nWHAT THE USER SAID:\n' +
574
+ spoken.map((message) => '- ' + clipText(message.content, 220)).join('\n'), triageModel, signal);
575
+ calls += 1;
576
+ if (parseObject(verdict)?.worth !== true)
577
+ continue;
578
+ const transcript = messages
579
+ .map((message) => (message.role === 'user' ? 'USER: ' : 'ASSISTANT: ') + clipText(message.content, 2500))
580
+ .join('\n\n');
581
+ const raw = await ask(provider, REPLAY_PROMPT +
582
+ '\n\nCURRENT DATE: ' + new Date().toISOString().slice(0, 10) +
583
+ '\n\nALREADY KNOWN:\n' + this.#knownFor(owner, said) +
584
+ '\n\nTHE CONVERSATION:\n' + clipText(transcript, 24000), deepModel, signal);
585
+ calls += 1;
586
+ read += 1;
587
+ const parsed = parseObject(raw);
588
+ const candidates = parseCandidates(JSON.stringify(parsed?.memories ?? []));
589
+ if (candidates.length) {
590
+ const admitted = admitCandidates(this.#store, {
591
+ candidates,
592
+ owner,
593
+ config: this.#config.memory,
594
+ // The user's words only, exactly as during the day.
595
+ sources: [said],
596
+ sourceSessionId: session.id,
597
+ sleepRunId: runId,
598
+ });
599
+ learned += admitted.stored.length;
600
+ if (admitted.rejected.length) {
601
+ this.#log.debug('Replay gate rejected candidates', {
602
+ session: session.id,
603
+ reasons: admitted.rejected.map((entry) => entry.reason).join(','),
604
+ });
605
+ }
606
+ }
607
+ for (const entry of Array.isArray(parsed?.corrections) ? parsed.corrections : []) {
608
+ if (!entry || typeof entry !== 'object')
609
+ continue;
610
+ const row = entry;
611
+ const text = typeof row.text === 'string' ? row.text.trim() : '';
612
+ const quote = typeof row.quote === 'string' ? row.quote.trim() : '';
613
+ // A correction has to be quotable too. "The user seemed unhappy" is
614
+ // not a correction, it is a mood.
615
+ if (text.length < 8 || !confirmedBy(quote, [said]))
616
+ continue;
617
+ // From the session reference to the turn reference (concept 4.2a,
618
+ // step 1): exactly one user message carries the quote, or there is
619
+ // no turn. `locateTurn` reads the same containment test that just
620
+ // admitted the quote, so the two can never disagree.
621
+ const located = locateTurn(messages, quote);
622
+ this.#store.addCorrection({
623
+ owner,
624
+ text,
625
+ quote,
626
+ sessionId: session.id,
627
+ ...(located.turnId ? { turnId: located.turnId } : {}),
628
+ });
629
+ corrections += 1;
630
+ }
631
+ this.#log.info('Replayed a conversation', {
632
+ session: session.id,
633
+ title: session.title,
634
+ learned,
635
+ corrections,
636
+ });
637
+ }
638
+ // One pass over what the night just wrote, once every session is read:
639
+ // the labels need the correction ids, and those only exist in the table.
640
+ const written = this.#writeCorrectionLabels(owner, sessions, since);
641
+ return {
642
+ read,
643
+ learned,
644
+ corrections,
645
+ labelled: written.labelled,
646
+ labels: written.labels,
647
+ labelFailures: written.failed,
648
+ calls,
649
+ };
650
+ }
651
+ /** What the extractor must not write again: whatever this talk touches. */
652
+ #knownFor(owner, text) {
653
+ const matched = recall(this.#store, { text, owner, limit: 25, threshold: 0.05, touch: false, expand: false });
654
+ if (!matched.length)
655
+ return '(nothing yet)';
656
+ return matched.map((memory) => '- ' + memory.content).join('\n');
657
+ }
197
658
  /* ------------------------------ phase 1 ------------------------------ */
198
659
  /**
199
660
  * Let the weak and unused fall asleep.
@@ -314,6 +775,14 @@ export class SleepRunner extends EventEmitter {
314
775
  let merged = 0;
315
776
  let retired = 0;
316
777
  let calls = 0;
778
+ /**
779
+ * Victim id to the condensed row that took its place - the one hop the
780
+ * `merge` label source is allowed to walk (concept 4.2c, S7). Collected
781
+ * as they are written, never re-read off the bank afterwards: a second
782
+ * query would pick up supersessions from earlier nights too, and a label
783
+ * that walks that far has stopped describing the prompt it observed.
784
+ */
785
+ const superseded = new Map();
317
786
  for (const cluster of clusters) {
318
787
  if (calls >= budget || signal.aborted)
319
788
  break;
@@ -390,11 +859,13 @@ export class SleepRunner extends EventEmitter {
390
859
  runId,
391
860
  });
392
861
  this.#store.sleepMemory(victim.id, { runId, supersededBy: record.id });
862
+ superseded.set(victim.id, record.id);
393
863
  retired += 1;
394
864
  }
395
865
  merged += 1;
396
866
  }
397
- return { merged, retired, calls };
867
+ const written = this.#writeMergeLabels(owner, superseded);
868
+ return { merged, retired, calls, labels: written.labels, labelFailures: written.failed };
398
869
  }
399
870
  /* --------------------- deep sleep: the decision --------------------- */
400
871
  /**
@@ -522,7 +993,7 @@ export class SleepRunner extends EventEmitter {
522
993
  async #link(provider, model, owner, runId, signal, budget) {
523
994
  const since = this.#store.lastSleepAt(owner);
524
995
  const fresh = this.#store
525
- .listMemories({ owner, since: since || undefined, limit: 60, includeDormant: false })
996
+ .listMemories({ owner, since: since || undefined, limit: 150, includeDormant: false })
526
997
  .filter((memory) => !memory.supersededBy);
527
998
  if (fresh.length < 2)
528
999
  return { edges: 0, conflicts: 0, calls: 0 };
@@ -532,6 +1003,9 @@ export class SleepRunner extends EventEmitter {
532
1003
  ...new Set(fresh.flatMap((memory) => this.#store.entitiesFor(memory.id).map((entity) => entity.id))),
533
1004
  ];
534
1005
  const neighbours = this.#store.memoriesForEntities(entityIds, {
1006
+ // The link table has no owner column, so a stray cross-owner link
1007
+ // would otherwise walk the night into another bank.
1008
+ owner,
535
1009
  exclude: fresh.map((memory) => memory.id),
536
1010
  limit: 40,
537
1011
  });
@@ -599,23 +1073,49 @@ export class SleepRunner extends EventEmitter {
599
1073
  continue;
600
1074
  this.#store.upsertEntity({ owner, name: existing.name, kind });
601
1075
  }
1076
+ // And so does the other half of a tidy graph: two names that mean one
1077
+ // thing ("Rookery", "Rookery-Agent") become one node, links and all.
1078
+ // A merge that would not hold - one side missing, both the same - is
1079
+ // refused by the store and costs the night nothing.
1080
+ const aliases = Array.isArray(parsed.aliases) ? parsed.aliases : [];
1081
+ for (const entry of aliases.slice(0, 8)) {
1082
+ if (!entry || typeof entry !== 'object')
1083
+ continue;
1084
+ const row = entry;
1085
+ const from = typeof row.from === 'string' ? row.from.trim() : '';
1086
+ const into = typeof row.into === 'string' ? row.into.trim() : '';
1087
+ if (!from || !into || from === into)
1088
+ continue;
1089
+ if (this.#store.mergeEntities(owner, from, into)) {
1090
+ this.#log.info('Merged duplicate entities', { owner, from, into });
1091
+ }
1092
+ }
602
1093
  }
603
1094
  return { edges, conflicts, calls };
604
1095
  }
605
1096
  /* ------------------------------ phase 5 ------------------------------ */
606
1097
  /**
607
1098
  * The part that makes it a memory rather than a filing cabinet: notice
608
- * something across the week that no single memory says. Strictly bounded -
609
- * one call, at most a couple of sentences, and each one has to point at
610
- * the evidence it came from or it is thrown away.
1099
+ * something across the window that no single memory says. Strictly
1100
+ * bounded - each call at most a couple of sentences, and each one has to
1101
+ * point at the evidence it came from or it is thrown away.
1102
+ *
1103
+ * Two passes over the same pool, from two angles. The first looks for
1104
+ * patterns in the user: habits, preferences, routines. The second looks
1105
+ * for patterns in the work: what keeps recurring, what keeps costing
1106
+ * time, what the projects share. One prompt that asks for both at once
1107
+ * returns the loudest kind only; separately, each gets its own lens. The
1108
+ * configured `insights` count caps the night's total, whichever angle
1109
+ * produced them.
611
1110
  */
612
- async #reflect(provider, model, owner, runId, signal) {
1111
+ async #reflect(provider, model, owner, runId, signal, budget) {
613
1112
  const wanted = this.#config.memory.sleep.insights;
614
- if (wanted <= 0 || signal.aborted)
1113
+ if (wanted <= 0 || budget <= 0 || signal.aborted)
615
1114
  return { written: 0, edges: 0, calls: 0 };
616
- const week = Date.now() - 7 * 24 * 60 * 60 * 1000;
1115
+ const window = this.#config.memory.sleep.insightWindowDays;
1116
+ const since = Date.now() - window * 24 * 60 * 60 * 1000;
617
1117
  const recent = this.#store
618
- .listMemories({ owner, since: week, limit: 40, includeDormant: false })
1118
+ .listMemories({ owner, since, limit: 80, includeDormant: false })
619
1119
  .filter((memory) => memory.kind !== 'insight');
620
1120
  if (recent.length < 4)
621
1121
  return { written: 0, edges: 0, calls: 0 };
@@ -626,56 +1126,1449 @@ export class SleepRunner extends EventEmitter {
626
1126
  const topics = entities.length
627
1127
  ? '\n\nCOMMON TOPICS:\n' + entities.map((entity) => '- ' + entity.name).join('\n')
628
1128
  : '';
629
- const raw = await ask(provider, INSIGHT_PROMPT.replace('{{MAX}}', String(wanted)) +
630
- '\n\nMEMORIES FROM RECENT DAYS:\n' + numbered + topics, model, signal);
631
- const parsed = parseObject(raw);
632
- const proposed = parsed && Array.isArray(parsed.insights) ? parsed.insights : [];
633
1129
  let written = 0;
634
1130
  let edges = 0;
1131
+ let calls = 0;
1132
+ // The two angles read the same pool, so the same sentence can come back
1133
+ // twice - and an insight that is already on record is not knowledge
1134
+ // gained. Both passes write against this set; whatever is in it, from
1135
+ // earlier nights or earlier in this one, is skipped.
1136
+ const onRecord = new Set(this.#store
1137
+ .listMemories({ owner, kinds: ['insight'], limit: 200, includeDormant: false })
1138
+ .map((memory) => memory.content));
1139
+ for (const angle of ['user', 'work']) {
1140
+ if (calls >= budget || written >= wanted || signal.aborted)
1141
+ break;
1142
+ const raw = await ask(provider, (angle === 'user' ? INSIGHT_USER_PROMPT : INSIGHT_WORK_PROMPT).replace('{{MAX}}', String(wanted - written)) +
1143
+ '\n\nMEMORIES FROM RECENT DAYS:\n' + numbered + topics, model, signal);
1144
+ calls += 1;
1145
+ const parsed = parseObject(raw);
1146
+ const proposed = parsed && Array.isArray(parsed.insights) ? parsed.insights : [];
1147
+ for (const entry of proposed.slice(0, wanted - written)) {
1148
+ if (!entry || typeof entry !== 'object')
1149
+ continue;
1150
+ const row = entry;
1151
+ const content = typeof row.content === 'string' ? row.content.trim() : '';
1152
+ if (content.length < 12 || content.length > 400)
1153
+ continue;
1154
+ if (onRecord.has(content))
1155
+ continue;
1156
+ const evidence = Array.isArray(row.evidence)
1157
+ ? [...new Set(row.evidence.map((value) => Number(value)))]
1158
+ .filter((value) => Number.isInteger(value) && value >= 1 && value <= recent.length)
1159
+ .map((value) => recent[value - 1])
1160
+ : [];
1161
+ // An insight standing on fewer than two memories is a guess.
1162
+ if (evidence.length < 2)
1163
+ continue;
1164
+ const record = this.#store.upsertMemory({
1165
+ kind: 'insight',
1166
+ content,
1167
+ tags: [...new Set(evidence.flatMap((memory) => memory.tags))].slice(0, 6),
1168
+ importance: clamp01(typeof row.importance === 'number' ? row.importance : 0.75),
1169
+ owner,
1170
+ origin: 'sleep',
1171
+ sleepRunId: runId,
1172
+ });
1173
+ onRecord.add(content);
1174
+ for (const memory of evidence) {
1175
+ for (const entity of this.#store.entitiesFor(memory.id)) {
1176
+ this.#store.linkEntity(record.id, entity.id);
1177
+ }
1178
+ // The insight refines its evidence, so recall can walk from either end.
1179
+ const edge = this.#store.addEdge({
1180
+ owner,
1181
+ srcId: record.id,
1182
+ dstId: memory.id,
1183
+ relation: 'refines',
1184
+ weight: 0.8,
1185
+ origin: 'sleep',
1186
+ runId,
1187
+ });
1188
+ if (edge)
1189
+ edges += 1;
1190
+ }
1191
+ written += 1;
1192
+ }
1193
+ }
1194
+ return { written, edges, calls };
1195
+ }
1196
+ /* ------------------------------ phase 6 ------------------------------ */
1197
+ /**
1198
+ * Repair before invention.
1199
+ *
1200
+ * A skill is written once and then followed for months, which makes a
1201
+ * stale one worse than none at all: it does not merely fail to help, it
1202
+ * confidently sends whoever opens it down a path that no longer exists. So
1203
+ * before the night considers writing anything new, it asks which of the
1204
+ * procedures it already owns have had the ground move under them.
1205
+ *
1206
+ * Two signals, both already in the database and neither of them guesswork:
1207
+ *
1208
+ * sources - the memories a skill was distilled from. One of them being
1209
+ * put to sleep, decided against in a contradiction, or edited
1210
+ * means the skill was written from something that no longer
1211
+ * reads that way.
1212
+ * failures - runs that had the skill open and then failed. The error text
1213
+ * comes along, because "the run failed" locates nothing while
1214
+ * "no such script: build:core" points at the exact line that
1215
+ * is lying.
1216
+ *
1217
+ * A trigger is consumed by being looked at, whatever the outcome: every
1218
+ * review leaves a snapshot, and the next night's window starts there.
1219
+ * Otherwise one dormant memory would drag the same skill in front of the
1220
+ * model every night for ever, at the cost of a call each time.
1221
+ */
1222
+ /**
1223
+ * Every skill of this bank that has a live reason to be looked at, worst
1224
+ * first. Pure database and lexical work - no model - so the demand
1225
+ * measurement can call it as often as it likes.
1226
+ */
1227
+ #skillSuspects(owner) {
1228
+ const store = new SkillStore(this.#config.skillsDir);
1229
+ const mine = store
1230
+ .for(owner === ASSISTANT_MEMORY_OWNER ? 'assistant' : 'agent')
1231
+ // Neither the user's own skills nor the ones Rookery ships are the
1232
+ // night's to rewrite, so there is no point spending a model call
1233
+ // deciding that they should be - the store would refuse the write.
1234
+ .filter((skill) => skill.origin === 'agent' || skill.origin === 'sleep');
1235
+ if (!mine.length)
1236
+ return [];
1237
+ // Corrections the night's replay pulled out of the day's conversations.
1238
+ // Unlike the other two signals these do not arrive attached to a skill, so
1239
+ // each is matched against the shelf by wording - the same lexical judgement
1240
+ // the rest of this file uses, and enough to tell "always run the tests
1241
+ // first" from a remark about the mail client.
1242
+ const open = this.#store.openCorrections(owner, 20);
1243
+ return mine
1244
+ .map((skill) => {
1245
+ // Looking counts as clearing, so the window opens at whichever came
1246
+ // last: the file being written, or the night last reading it.
1247
+ const since = Math.max(skill.updatedAt, this.#store.lastSkillReviewAt(skill.name));
1248
+ const changed = this.#store.changedSkillSources(skill.name, since);
1249
+ const failures = this.#store.failedRunsForSkill(skill.name, since, 3);
1250
+ // Name and description only, never the body. What a skill is ABOUT is
1251
+ // its subject line; the body is implementation detail, and every extra
1252
+ // step in it dilutes the overlap until nothing matches. A correction
1253
+ // shares few words with the procedure it bears on by nature - it is
1254
+ // usually introducing something the procedure fails to mention.
1255
+ const about = normalizeTokens(skill.name.replace(/-/g, ' ') + ' ' + skill.description);
1256
+ const corrections = open.filter((entry) => similarity(about, normalizeTokens(entry.text)) >= CORRECTION_MATCH);
1257
+ return { skill, changed, failures, corrections };
1258
+ })
1259
+ // A failure is the louder signal: it is evidence the procedure was
1260
+ // actually followed and actually did not work.
1261
+ .filter((entry) => entry.changed.length > 0 || entry.failures.length > 0 || entry.corrections.length > 0)
1262
+ .sort((a, b) => weigh(b) - weigh(a));
1263
+ }
1264
+ async #revise(provider, model, owner, runId, signal, budget) {
1265
+ if (budget <= 0 || signal.aborted)
1266
+ return { written: 0, calls: 0 };
1267
+ const store = new SkillStore(this.#config.skillsDir);
1268
+ const suspects = this.#skillSuspects(owner).slice(0, budget);
1269
+ if (!suspects.length)
1270
+ return { written: 0, calls: 0 };
1271
+ const consumed = new Set();
1272
+ let written = 0;
1273
+ let calls = 0;
1274
+ for (const suspect of suspects) {
1275
+ if (signal.aborted)
1276
+ break;
1277
+ const { skill, changed, failures, corrections } = suspect;
1278
+ for (const entry of corrections)
1279
+ consumed.add(entry.id);
1280
+ const why = [];
1281
+ for (const entry of changed) {
1282
+ const line = entry.replacement
1283
+ ? 'This memory was replaced:\n BEFORE: ' + entry.memory.content + '\n NOW: ' + entry.replacement.content
1284
+ : entry.memory.dormantAt
1285
+ ? 'This memory was put to sleep as no longer worth keeping: ' + entry.memory.content
1286
+ : 'This memory was edited since the skill was written: ' + entry.memory.content;
1287
+ why.push('- ' + line);
1288
+ }
1289
+ // The user's own words go first: nothing else in the list carries as
1290
+ // much weight as being told outright that this is wrong.
1291
+ for (const entry of corrections) {
1292
+ why.unshift('- The user corrected this: ' + entry.text +
1293
+ '\n IN THEIR WORDS: "' + clipText(entry.quote, 220) + '"');
1294
+ }
1295
+ for (const failure of failures) {
1296
+ why.push('- A run that had this skill open failed.\n TASK: ' + clipText(failure.task, 200) +
1297
+ '\n ERROR: ' + clipText(failure.error, 400));
1298
+ }
1299
+ const raw = await ask(provider, REVISE_PROMPT +
1300
+ '\n\nTHE SKILL AS IT READS NOW:\nname: ' + skill.name +
1301
+ '\ndescription: ' + skill.description +
1302
+ '\n\n' + skill.body +
1303
+ '\n\nWHAT HAS CHANGED SINCE IT WAS WRITTEN:\n' + why.join('\n'), model, signal);
1304
+ calls += 1;
1305
+ const parsed = parseObject(raw);
1306
+ const wantsRevision = parsed?.revise === true;
1307
+ const description = typeof parsed?.description === 'string' && parsed.description.trim()
1308
+ ? parsed.description.trim()
1309
+ : skill.description;
1310
+ const body = typeof parsed?.body === 'string' ? parsed.body.trim() : '';
1311
+ if (!wantsRevision || body.length < 120) {
1312
+ // Reviewed and left alone. The snapshot carries no run id: there is
1313
+ // nothing for undo to take back, but the timestamp still closes the
1314
+ // window so tomorrow does not ask the same question again.
1315
+ this.#store.snapshotSkill({ skill: skill.name, content: store.raw(skill.name) });
1316
+ this.#settleSources(skill.name, owner, changed);
1317
+ this.#log.info('Sleep reviewed a skill and left it', { owner, skill: skill.name });
1318
+ continue;
1319
+ }
1320
+ try {
1321
+ this.#store.snapshotSkill({ skill: skill.name, content: store.raw(skill.name), sleepRunId: runId });
1322
+ store.save({ name: skill.name, description, body, audience: skill.audience, origin: 'sleep' });
1323
+ this.#settleSources(skill.name, owner, changed);
1324
+ this.#log.info('Sleep revised a skill', {
1325
+ owner,
1326
+ skill: skill.name,
1327
+ changed: changed.length,
1328
+ failures: failures.length,
1329
+ });
1330
+ written += 1;
1331
+ }
1332
+ catch (cause) {
1333
+ this.#log.info('Sleep left a skill alone', { owner, skill: skill.name, reason: cause.message });
1334
+ }
1335
+ }
1336
+ // Looked at is looked at, whatever came of it: a correction that has been
1337
+ // weighed must not be weighed again tomorrow.
1338
+ this.#store.consumeCorrections([...consumed]);
1339
+ return { written, calls };
1340
+ }
1341
+ /**
1342
+ * Re-point a skill at the memories that hold now.
1343
+ *
1344
+ * A superseded source is followed to whatever replaced it, so the chain
1345
+ * survives a condensation instead of breaking at it; a sleeping source is
1346
+ * dropped, because a memory nobody kept is not something to keep standing
1347
+ * on. Without this the same trigger would fire for ever: the memory stays
1348
+ * dormant, and dormancy has no timestamp a window could exclude.
1349
+ */
1350
+ #settleSources(skill, owner, changed) {
1351
+ if (!changed.length)
1352
+ return;
1353
+ const current = new Set(this.#store.skillSourceIds(skill));
1354
+ for (const entry of changed) {
1355
+ current.delete(entry.memory.id);
1356
+ if (entry.replacement && !entry.replacement.dormantAt)
1357
+ current.add(entry.replacement.id);
1358
+ else if (!entry.memory.dormantAt && !entry.memory.supersededBy)
1359
+ current.add(entry.memory.id);
1360
+ }
1361
+ this.#store.setSkillSources(skill, owner, [...current]);
1362
+ }
1363
+ /**
1364
+ * The night's last act, and the only one that changes what the assistant
1365
+ * can do rather than only what it knows.
1366
+ *
1367
+ * A memory says that something is true. A skill says how something is
1368
+ * done - and that second kind of knowledge is exactly what gets worked out
1369
+ * from scratch every time while it lives as a scatter of separate
1370
+ * sentences. So once the bank is tidy, the same evidence rule that governs
1371
+ * insights is pointed at procedure: where several memories describe the
1372
+ * same recurring piece of work, that work is written down as a skill, and
1373
+ * from the next turn on it sits in the index the assistant and its agents
1374
+ * both read.
1375
+ *
1376
+ * Three things keep this from filling the shelf with rubbish. It is capped
1377
+ * (one a night by default). Nothing is written on fewer than three
1378
+ * memories. And a skill the user wrote is never overwritten - the store
1379
+ * refuses, and the refusal is logged rather than worked around.
1380
+ */
1381
+ async #practise(provider, model, owner, runId, signal, budget) {
1382
+ const wanted = this.#config.memory.sleep.skills;
1383
+ if (wanted <= 0 || budget <= 0 || signal.aborted)
1384
+ return { written: 0, calls: 0 };
1385
+ // What this bank holds, strongest first. Insights are deliberately in:
1386
+ // they are precisely the "this keeps happening" observations a procedure
1387
+ // grows out of.
1388
+ const live = this.#store
1389
+ .listMemories({ owner, limit: 60, includeDormant: false })
1390
+ .filter((memory) => memory.kind !== 'summary');
1391
+ if (live.length < 6)
1392
+ return { written: 0, calls: 0 };
1393
+ const numbered = live
1394
+ .map((memory, index) => index + 1 + '. [' + memory.kind + '] ' + memory.content)
1395
+ .join('\n');
1396
+ // Whose shelf this is. The assistant's bank writes skills the assistant
1397
+ // may open; an agent's bank writes skills for agents.
1398
+ const audience = owner === ASSISTANT_MEMORY_OWNER ? 'assistant' : 'agents';
1399
+ const store = new SkillStore(this.#config.skillsDir);
1400
+ const existing = store.for(owner === ASSISTANT_MEMORY_OWNER ? 'assistant' : 'agent');
1401
+ const shelf = existing.length
1402
+ ? existing.map((skill) => '- ' + skill.name + ' (' + skill.origin + '): ' + skill.description).join('\n')
1403
+ : '(nothing yet)';
1404
+ const raw = await ask(provider, SKILL_PROMPT.replace('{{MAX}}', String(wanted)) +
1405
+ '\n\nSKILLS THAT ALREADY EXIST:\n' + shelf +
1406
+ '\n\nWHAT THIS MEMORY HOLDS:\n' + numbered, model, signal);
1407
+ const parsed = parseObject(raw);
1408
+ const proposed = parsed && Array.isArray(parsed.skills) ? parsed.skills : [];
1409
+ let written = 0;
635
1410
  for (const entry of proposed.slice(0, wanted)) {
636
1411
  if (!entry || typeof entry !== 'object')
637
1412
  continue;
638
1413
  const row = entry;
639
- const content = typeof row.content === 'string' ? row.content.trim() : '';
640
- if (content.length < 12 || content.length > 400)
1414
+ const name = typeof row.name === 'string' ? skillSlug(row.name) : '';
1415
+ const description = typeof row.description === 'string' ? row.description.trim() : '';
1416
+ const body = typeof row.body === 'string' ? row.body.trim() : '';
1417
+ if (!name || !description)
1418
+ continue;
1419
+ // Shorter than this is a note, not a procedure worth opening.
1420
+ if (body.length < 120)
641
1421
  continue;
642
1422
  const evidence = Array.isArray(row.evidence)
643
- ? [...new Set(row.evidence.map((value) => Number(value)))]
644
- .filter((value) => Number.isInteger(value) && value >= 1 && value <= recent.length)
645
- .map((value) => recent[value - 1])
1423
+ ? [...new Set(row.evidence.map((value) => Number(value)))].filter((value) => Number.isInteger(value) && value >= 1 && value <= live.length)
646
1424
  : [];
647
- // An insight standing on fewer than two memories is a guess.
648
- if (evidence.length < 2)
1425
+ // A procedure standing on fewer than three memories is one anecdote
1426
+ // with ambitions.
1427
+ if (evidence.length < 3)
649
1428
  continue;
650
- const record = this.#store.upsertMemory({
651
- kind: 'insight',
652
- content,
653
- tags: [...new Set(evidence.flatMap((memory) => memory.tags))].slice(0, 6),
654
- importance: clamp01(typeof row.importance === 'number' ? row.importance : 0.75),
1429
+ try {
1430
+ // The snapshot goes in first and carries the run id: writing a skill
1431
+ // is part of the night, so undoing the night has to take it back.
1432
+ // Null content says the skill did not exist, which is how undo knows
1433
+ // to delete rather than restore.
1434
+ this.#store.snapshotSkill({ skill: name, content: store.raw(name), sleepRunId: runId });
1435
+ const skill = store.save({ name, description, body, audience, origin: 'sleep' });
1436
+ // What it stands on, kept: this is what lets a later night notice
1437
+ // that the ground under this procedure has moved.
1438
+ this.#store.setSkillSources(skill.name, owner, evidence.map((index) => live[index - 1].id));
1439
+ this.#log.info('Sleep wrote a skill', { owner, skill: skill.name, evidence: evidence.length });
1440
+ written += 1;
1441
+ }
1442
+ catch (cause) {
1443
+ // Almost always "that name belongs to the user". Not worth failing a
1444
+ // night over; the night simply does not get that name.
1445
+ this.#log.info('Sleep left a skill alone', { owner, skill: name, reason: cause.message });
1446
+ }
1447
+ }
1448
+ return { written, calls: 1 };
1449
+ }
1450
+ /* -------------------------------- the dream -------------------------------- */
1451
+ /**
1452
+ * The dream: measure the retrieval policy, and - when every condition
1453
+ * holds - put a better one in force (concept 5, 6, 10).
1454
+ *
1455
+ * It sits before the cycle loop and above the provider guard because all
1456
+ * of it is model-free. The grid is declared, the candidates it ranks were
1457
+ * proposed by a night that has already been and gone, and every number
1458
+ * comes out of frames frozen during the day. A night without a provider
1459
+ * still measures, still promotes and still freezes - and that is exactly
1460
+ * the night where this is the only thing that could run at all. It is also
1461
+ * why the candidate writer sits at the far end of the night (`#propose`)
1462
+ * and writes for tomorrow: a promotion path that needed tonight's model
1463
+ * call would stop working on the night it matters most.
1464
+ *
1465
+ * One wall clock for the whole of it (`dream.maxEvalMs`), not one per
1466
+ * part: a pool cut into pieces must not be able to buy itself a second
1467
+ * budget. One catch around the whole of it as well - a dream that throws
1468
+ * costs the night its measurement, never its consolidation (10.5: a
1469
+ * degraded path is never turned into an error).
1470
+ */
1471
+ async #dream(owner, runId, counters, signal) {
1472
+ const dream = this.#config.memory.dream;
1473
+ // Stage 2 dreams for one bank, the assistant's (R18): nothing scores an
1474
+ // agent's frames, so recording and measuring them would be pure cost.
1475
+ if (!dream.enabled || owner !== ASSISTANT_MEMORY_OWNER)
1476
+ return '';
1477
+ const deadline = Date.now() + clampMs(dream.maxEvalMs);
1478
+ this.#phase(runId, 'dream', counters, 1);
1479
+ let report = '';
1480
+ try {
1481
+ report += this.#probe(owner, runId, counters, deadline, signal);
1482
+ // `dream.slots` is what the night CARRIES (9.3, S18). `recall` is the
1483
+ // one slot this stage has a promotion path for; `budget` and `retry`
1484
+ // are measured after the cycles and carried by nobody yet.
1485
+ if (dream.slots.includes('recall')) {
1486
+ report += await this.#recallSlot(owner, runId, counters, deadline, signal);
1487
+ }
1488
+ }
1489
+ catch (cause) {
1490
+ const message = cause.message;
1491
+ this.#log.warn('The dream phase failed', { owner, error: message });
1492
+ report += ' The dream phase failed: ' + message + '.';
1493
+ }
1494
+ this.#phase(runId, 'dream', counters, 1);
1495
+ return report;
1496
+ }
1497
+ /**
1498
+ * The grid probe (stage 1): the declared placements, scored against each
1499
+ * frame's own incumbent. Unchanged by stage 2 on purpose - it takes ONE
1500
+ * gain function for a whole pool, and a gain is a statement about one
1501
+ * turn, so a label-derived gain handed in here would let a memory proven
1502
+ * relevant in one turn score in every other. The labelled measurement is
1503
+ * `#recallSlot` below, which carries a gain per turn.
1504
+ */
1505
+ #probe(owner, runId, counters, deadline, signal) {
1506
+ const dream = this.#config.memory.dream;
1507
+ // The night's deadline, not a second one computed from the same key.
1508
+ // Without this the probe could spend the whole of `dream.maxEvalMs` and
1509
+ // `#recallSlot` would start already past its own - every evaluation
1510
+ // invalid, no row written, and last night's proposals retired for a
1511
+ // measurement that never happened (concept 6.1).
1512
+ const probe = runGridProbe(this.#store, this.#config, owner, runId, signal, {
1513
+ deadline,
1514
+ });
1515
+ counters.dreamTracesSeen = probe.tracesSeen;
1516
+ counters.dreamFramesScored = probe.framesScored;
1517
+ let report = '';
1518
+ if (probe.invalidated > 0) {
1519
+ // Concept 3.3: frames older than a reindex or bulk import are declared
1520
+ // invalid outright, and the night report says so instead of letting
1521
+ // every following night guess at it as corpus drift.
1522
+ const since = probe.invalidatedAt
1523
+ ? new Date(probe.invalidatedAt).toISOString()
1524
+ : 'an unknown import';
1525
+ report +=
1526
+ ' ' + probe.invalidated + ' of ' + probe.frames +
1527
+ ' dream frames unusable since the import/reindex at ' + since + '.';
1528
+ }
1529
+ if (probe.poolTruncated) {
1530
+ // The pool walks the oldest frames first, so above the cap it is the
1531
+ // NEWEST frames that fall out of the measurement - a smaller pool must
1532
+ // be reported, not passed off as the whole one.
1533
+ report +=
1534
+ ' The dream probe read the ' + probe.frames + ' oldest of ' +
1535
+ probe.framesTotal + ' stored dream frames.';
1536
+ }
1537
+ // R18: the probe is model-free, and the run-global ceiling is what
1538
+ // certifies it. A probe that ever exceeds it has stopped being the
1539
+ // probe, and the night should say so rather than shrug.
1540
+ const ceiling = Math.max(0, Math.round(dream.maxCallsPerNight));
1541
+ if (probe.modelCalls > ceiling) {
1542
+ this.#log.warn('Dream probe exceeded dream.maxCallsPerNight', {
655
1543
  owner,
656
- origin: 'sleep',
657
- sleepRunId: runId,
1544
+ calls: probe.modelCalls,
1545
+ ceiling,
658
1546
  });
659
- for (const memory of evidence) {
660
- for (const entity of this.#store.entitiesFor(memory.id)) {
661
- this.#store.linkEntity(record.id, entity.id);
662
- }
663
- // The insight refines its evidence, so recall can walk from either end.
664
- const edge = this.#store.addEdge({
1547
+ }
1548
+ this.#log.info('Dream probe measured', {
1549
+ owner,
1550
+ tracesSeen: probe.tracesSeen,
1551
+ frames: probe.frames,
1552
+ framesTotal: probe.framesTotal,
1553
+ poolTruncated: probe.poolTruncated,
1554
+ framesScored: probe.framesScored,
1555
+ evalMs: probe.evalMs,
1556
+ modelCalls: probe.modelCalls,
1557
+ deadlineHit: probe.deadlineHit,
1558
+ error: probe.error ?? undefined,
1559
+ });
1560
+ return report;
1561
+ }
1562
+ /**
1563
+ * The `recall` slot, end to end: candidates, admission, selection, the
1564
+ * three sensors, the freeze and the gate.
1565
+ *
1566
+ * The order is the contract and it is not taste:
1567
+ *
1568
+ * 1. The candidates - last night's proposals and tonight's declared
1569
+ * grid, the incumbent first (E2/6.3).
1570
+ * 2. Admission BEFORE the measurement (S17/10.1). Every mechanism in the
1571
+ * gaming table is a legal point inside the box, so a comparison on
1572
+ * the score cannot catch one; what catches it is a predicate about
1573
+ * the candidate's shape, decided without touching a score.
1574
+ * 3. Selection on the training half, exactly one candidate on the
1575
+ * holdout, the frozen audit set opened only when a promotion is
1576
+ * actually on the table (E4/S12/S13).
1577
+ * 4. The label agreement sensor over the pool's labels, `user`
1578
+ * privileged (5.5b).
1579
+ * 5. The wake test on what is already in force (5.5c), then the freeze,
1580
+ * then the gate - so tonight's regression alarm blocks tonight's
1581
+ * promotion rather than the one after it.
1582
+ */
1583
+ async #recallSlot(owner, runId, counters, deadline, signal) {
1584
+ const dream = this.#config.memory.dream;
1585
+ const slot = 'recall';
1586
+ // The NEWEST frames, not the oldest. Everything below means the frames
1587
+ // nearest to now - the box of the last one, the wake test's "since the
1588
+ // last promotion" filter, the admission sample's trailing slice - and an
1589
+ // owner holding more frames than the cap would otherwise pin all three
1590
+ // to a weeks-old slice for good, silently (S3).
1591
+ const pool = this.#store.framesFor(owner, { limit: DREAM_POOL_LIMIT, newest: true });
1592
+ const entries = pool
1593
+ // A night never scores its own writes.
1594
+ .filter((entry) => entry.trace.sleepRunId !== runId);
1595
+ if (!entries.length)
1596
+ return '';
1597
+ let report = '';
1598
+ const framesTotal = this.#store.dreamFrameCount(owner);
1599
+ if (framesTotal > pool.length) {
1600
+ // Disclosed the way the probe discloses its own cut: a measurement
1601
+ // over part of the store must be visible as one, never pass for the
1602
+ // whole of it.
1603
+ report +=
1604
+ ' The recall slot measured the ' + pool.length + ' newest of ' + framesTotal +
1605
+ ' stored dream frames.';
1606
+ }
1607
+ const incumbent = resolvePolicy(this.#store, this.#config, owner, slot);
1608
+ // The box of the newest frame in the pool. The recorder derives it from
1609
+ // the policy in force, so every frame recorded under one policy carries
1610
+ // the same one; a candidate that leaves an older frame's box costs that
1611
+ // frame an abstention (`limit-out-of-box`), counted like every other.
1612
+ const box = entries[entries.length - 1].frame.box;
1613
+ // The frozen audit set is touched exactly once per promotion and serves
1614
+ // neither for selection nor as a holdout (5.5d). `selectOnTraining`
1615
+ // splits the pool itself, so every OTHER reader of the pool has to keep
1616
+ // the audit sessions out on its own: the admission predicate reads the
1617
+ // training half, exactly as the candidate writer does, and the wake test
1618
+ // reads everything but the audit.
1619
+ const split = splitPool(entries, DEFAULT_SPLIT_RATES);
1620
+ const audited = new Set(split.audit);
1621
+ const awake = entries.filter((entry) => !audited.has(entry));
1622
+ /* ------------------------------ candidates ------------------------------ */
1623
+ const proposals = this.#proposals(owner, slot, incumbent, dream.candidates);
1624
+ const versionOf = new Map(proposals.map((entry) => [entry.policy, entry.version]));
1625
+ const grid = buildGrid(incumbent, box, dream.gridSize).map((placement) => liftPolicy(placement, incumbent));
1626
+ // The incumbent goes first and a repeated point is dropped: every delta
1627
+ // is then paired against a number measured tonight, on tonight's frames,
1628
+ // never against a number from yesterday (E2).
1629
+ const offered = withIncumbent([...proposals.map((entry) => entry.policy), ...grid], incumbent);
1630
+ /* -------------------- admission, before the measurement -------------------- */
1631
+ const admissions = new Map();
1632
+ const admitted = [offered[0]];
1633
+ // Which admitted position carries which proposal, and which proposals
1634
+ // the night has reached a verdict on. Only a settled proposal is retired
1635
+ // at the end; one that was never measured is carried over (7).
1636
+ const proposalAt = new Map();
1637
+ const settled = new Set();
1638
+ const onOffer = new Set(offered);
1639
+ for (const entry of proposals) {
1640
+ // Dropped as a duplicate of a point already on offer - the incumbent's
1641
+ // own, usually (E2). There is nothing to measure about it tonight or
1642
+ // any other night, so it is spent rather than carried forever.
1643
+ if (!onOffer.has(entry.policy))
1644
+ settled.add(entry.version.id);
1645
+ }
1646
+ const incumbentCoverage = this.#coverageOf(split.train, incumbent, deadline, signal);
1647
+ let refused = 0;
1648
+ for (let index = 1; index < offered.length; index += 1) {
1649
+ const candidate = offered[index];
1650
+ const verdict = admit(candidate, incumbent, box, {
1651
+ coverage: {
1652
+ candidate: this.#coverageOf(split.train, candidate, deadline, signal),
1653
+ incumbent: incumbentCoverage,
1654
+ },
1655
+ // H3: only the write gate's reinforcement branch ever un-parks a
1656
+ // memory, and this stage ships no `gate` slot - so neither arm
1657
+ // revives anything. Two measured zeroes, not a waived predicate.
1658
+ revivalRate: { candidate: 0, incumbent: 0 },
1659
+ });
1660
+ const version = versionOf.get(candidate);
1661
+ if (!verdict.ok) {
1662
+ refused += 1;
1663
+ // A refusal is a decision about the candidate's SHAPE, taken without
1664
+ // a score, so it comes out the same tomorrow and every night after:
1665
+ // the proposal is spent. Carrying it over would block the quota for
1666
+ // good rather than give it another chance.
1667
+ if (version)
1668
+ settled.add(version.id);
1669
+ this.#log.debug('A dream candidate was refused admission', {
665
1670
  owner,
666
- srcId: record.id,
667
- dstId: memory.id,
668
- relation: 'refines',
669
- weight: 0.8,
670
- origin: 'sleep',
671
- runId,
1671
+ findings: verdict.findings.join(','),
672
1672
  });
673
- if (edge)
674
- edges += 1;
1673
+ continue;
1674
+ }
1675
+ // Keyed by the position the candidate takes in `admitted`, which is
1676
+ // the index `selectOnTraining` reports back on the chosen one.
1677
+ if (version)
1678
+ proposalAt.set(admitted.length, version);
1679
+ admissions.set(admitted.length, verdict);
1680
+ admitted.push(candidate);
1681
+ }
1682
+ /* ------------------------------ measurement ------------------------------ */
1683
+ const selection = selectOnTraining(this.#store, {
1684
+ owner,
1685
+ slot,
1686
+ config: this.#config,
1687
+ entries,
1688
+ incumbent,
1689
+ // The frozen audit set is scored against the set the product shipped
1690
+ // with, never against last night's winner (10.2, condition 2b).
1691
+ factory: factoryPolicy(),
1692
+ candidates: admitted,
1693
+ // Tonight's fingerprint, as the probe above just stamped it: a frame
1694
+ // whose corpus has moved abstains instead of being scored (5.4).
1695
+ corpus: this.#store.currentCorpusStamp(owner),
1696
+ freshness: true,
1697
+ sourceDeltas: true,
1698
+ deadline,
1699
+ signal,
1700
+ });
1701
+ const agreement = agreementReport(this.#labelsFor(entries, owner), {
1702
+ floor: dream.agreementFloor,
1703
+ margin: dream.margin,
1704
+ deltaBySource: selection.holdout?.detail?.deltaBySource,
1705
+ });
1706
+ this.#log.info('The dream measured the recall slot', {
1707
+ owner,
1708
+ split: selection.split,
1709
+ offered: offered.length,
1710
+ admitted: admitted.length - 1,
1711
+ refused,
1712
+ findings: selection.findings.join(','),
1713
+ delta: selection.holdout?.delta,
1714
+ ciLow: selection.holdout?.ciLow,
1715
+ valid: selection.holdout?.valid,
1716
+ violations: selection.holdout?.violations.join(','),
1717
+ agreement: agreement.findings.join(','),
1718
+ });
1719
+ /* --------------------------- the wake test, then the freeze --------------------------- */
1720
+ const wake = this.#wakeTest(owner, slot, awake, incumbent, deadline, signal);
1721
+ if (wake && wake.drift !== null) {
1722
+ report +=
1723
+ ' The wake test (a regression alarm, not a calibration: the replay value and the live' +
1724
+ ' value come out of the same estimator and the same labels, so wrong labels leave both' +
1725
+ ' agreeing) measured a drift of ' + signedNumber(wake.drift) + ' over the ' +
1726
+ plural(wake.closed, 'trace', 'traces') + ' that closed of ' + wake.offered +
1727
+ ' frames since the last promotion, ' + plural(wake.abstained, 'abstention', 'abstentions') +
1728
+ leadingReason(wake.reasons) + '.';
1729
+ }
1730
+ else if (wake) {
1731
+ // The verdict is read off what CLOSED, so a pool that closed too
1732
+ // little says so and freezes nothing: `calibration` is a freeze
1733
+ // somebody has to undo by hand (10.3), and one trace of noise out of
1734
+ // fifty offered must not be able to hand it out.
1735
+ report +=
1736
+ ' The wake test could not run: ' + wake.closed + ' of ' + wake.offered +
1737
+ ' frames since the last promotion closed, under dream.calibrationTraces (' +
1738
+ wake.required + '), with ' + plural(wake.abstained, 'abstention', 'abstentions') +
1739
+ leadingReason(wake.reasons) + '. Nothing is frozen on a pool that could not be read.';
1740
+ }
1741
+ report += this.#freeze(owner, slot, wake, selection.holdout, agreement);
1742
+ /* --------------------------------- the gate --------------------------------- */
1743
+ const chosen = selection.chosen;
1744
+ const params = chosen ? paramsOf(chosen.policy, incumbent) : {};
1745
+ const decision = promotionDecision({
1746
+ config: this.#config,
1747
+ holdout: selection.holdout,
1748
+ audit: selection.audit,
1749
+ // Exactly one candidate reaches the holdout, or none did (E4/S12).
1750
+ holdoutChecks: selection.holdout ? 1 : 0,
1751
+ agreement,
1752
+ admission: chosen ? admissions.get(chosen.index) ?? null : null,
1753
+ // Read after the freeze above, so a slot frozen tonight blocks
1754
+ // tonight's promotion (condition 7a).
1755
+ slotState: this.#store.slotState(owner, slot),
1756
+ lastTraceSetHash: this.#store.lastPromotedTraceSetHash(owner, slot),
1757
+ incumbentOrigin: incumbent.origin,
1758
+ params,
1759
+ // Stage 2 promotes for the assistant alone, so the night's own count
1760
+ // is the count across every slot (condition 8).
1761
+ promotionsTonight: counters.dreamPromoted,
1762
+ });
1763
+ if (selection.holdout && chosen && decision.promote) {
1764
+ const record = applyPromotion(this.#store, {
1765
+ owner,
1766
+ slot,
1767
+ sleepRunId: runId,
1768
+ config: this.#config,
1769
+ params,
1770
+ box: box,
1771
+ holdout: selection.holdout,
1772
+ audit: selection.audit,
1773
+ });
1774
+ counters.dreamPromoted += record.promoted;
1775
+ await this.#announcePromotion({
1776
+ owner,
1777
+ slot,
1778
+ runId,
1779
+ version: record.version,
1780
+ evaluation: record.evaluation,
1781
+ prevActiveId: record.prevActiveId,
1782
+ rationale: record.version.rationale ?? renderRationale(selection.holdout, selection.audit),
1783
+ cooldownUntil: record.cooldownUntil,
1784
+ });
1785
+ report +=
1786
+ ' A new ' + slot + ' policy is in force (version ' + record.version.version + '): ' +
1787
+ record.version.rationale + '. It can be taken back.';
1788
+ }
1789
+ else if (selection.holdout && chosen) {
1790
+ // A night that measures and does not promote is the common case, and
1791
+ // the record of it is what the next calibration stands on. The
1792
+ // evaluation row needs a version to hang off - `dream_evals.policy_id`
1793
+ // is a foreign key - so the candidate becomes an unpromoted version
1794
+ // carrying its own replay numbers, which is also what keeps it from
1795
+ // coming back tomorrow as an unmeasured proposal.
1796
+ const version = this.#store.createPolicyVersion({
1797
+ owner,
1798
+ slot,
1799
+ params,
1800
+ box: box,
1801
+ origin: 'dream',
1802
+ parentId: this.#store.activePolicy(owner, slot)?.id,
1803
+ sleepRunId: runId,
1804
+ rationale: renderRationale(selection.holdout, selection.audit),
1805
+ replayScore: selection.holdout.score,
1806
+ replayN: selection.holdout.closed,
1807
+ baselineScore: selection.holdout.baseline,
1808
+ auditDelta: selection.audit?.delta ?? selection.holdout.auditDelta,
1809
+ auditCiLow: selection.audit?.ciLow ?? selection.holdout.auditCiLow,
1810
+ });
1811
+ this.#recordEval(selection.holdout, version.id, runId, false);
1812
+ if (dream.promote) {
1813
+ // Only worth a sentence when promoting is switched on at all -
1814
+ // otherwise every night would end with the same blocker.
1815
+ report +=
1816
+ ' A ' + slot + ' candidate was measured and not promoted: ' +
1817
+ decision.blockers.join(', ') + '.';
1818
+ }
1819
+ }
1820
+ this.#log.info('The dream gate answered', {
1821
+ owner,
1822
+ slot,
1823
+ promote: decision.promote,
1824
+ blockers: decision.blockers.join(','),
1825
+ });
1826
+ // A proposal is offered exactly once - once it has been MEASURED.
1827
+ // Measured means a number exists for it: its training evaluation closed
1828
+ // at least one trace. A night that ran out of wall clock, or aborted, or
1829
+ // stood on a pool that closed nothing, measured none of them, and
1830
+ // retiring them for it would burn `dream.maxCallsPerNight` every night
1831
+ // forever on proposals that never got a number (7). What was measured,
1832
+ // or refused on its shape, is spent; the rest is carried over.
1833
+ for (const ranked of selection.ranked) {
1834
+ if (ranked.training.closed <= 0)
1835
+ continue;
1836
+ const version = proposalAt.get(ranked.index);
1837
+ if (version)
1838
+ settled.add(version.id);
1839
+ }
1840
+ let retired = 0;
1841
+ for (const entry of proposals) {
1842
+ if (!settled.has(entry.version.id))
1843
+ continue;
1844
+ this.#store.retirePolicyVersion(entry.version.id);
1845
+ retired += 1;
1846
+ }
1847
+ const carried = proposals.length - retired;
1848
+ if (carried > 0) {
1849
+ report +=
1850
+ ' ' + plural(carried, 'proposal was', 'proposals were') +
1851
+ ' carried over to the next night: nothing measured ' +
1852
+ (carried === 1 ? 'it' : 'them') + ' tonight.';
1853
+ }
1854
+ return report;
1855
+ }
1856
+ /**
1857
+ * The wake test (concept 5.5c): after `dream.calibrationTraces` traces,
1858
+ * how far the live score has moved from what the promotion promised.
1859
+ *
1860
+ * It is a **regression alarm, not a calibration**, and the report says so.
1861
+ * The replay value and the live value come out of the same estimator and
1862
+ * the same labels, so if the labels are wrong the two agree with each
1863
+ * other and both are wrong together. What this catches is the trace
1864
+ * distribution shifting after a promotion - that, and nothing more.
1865
+ *
1866
+ * The arm is the policy in force, which `resolvePolicy` has already laid
1867
+ * the promoted parameters into, and it is measured frame by frame with
1868
+ * `measure` - the same estimator and the same per-turn gains the holdout
1869
+ * used, which is the whole basis of the comparison. Deliberately NOT
1870
+ * through `evaluateCandidate`: that machinery is paired, and an arm
1871
+ * scored against itself moves nothing on any trace, so every one of them
1872
+ * would drop out as `no-labelled-move` and the pool would close empty.
1873
+ *
1874
+ * What it is allowed to conclude anything from is the frames that CLOSED.
1875
+ * `dream.calibrationTraces` decides when the test is due - that many
1876
+ * frames since the promotion have to exist at all - and then decides again
1877
+ * whether the pool it actually read is thick enough to read a verdict off.
1878
+ * The abstentions in between are counted by reason and reported, because
1879
+ * they are the finding when they dominate: the alternative, a verdict off
1880
+ * one trace out of fifty, freezes a slot until somebody thaws it by hand
1881
+ * (5.4, 10.3).
1882
+ */
1883
+ #wakeTest(owner, slot, entries, arm, deadline, signal) {
1884
+ const dream = this.#config.memory.dream;
1885
+ const active = this.#store.activePolicy(owner, slot);
1886
+ // Nothing has been promoted, or the promotion carries no promise to
1887
+ // compare against: there is no regression to alarm about.
1888
+ if (!active?.promotedAt || active.replayScore === undefined)
1889
+ return null;
1890
+ const promotedAt = active.promotedAt;
1891
+ const required = clampCount(dream.calibrationTraces);
1892
+ const fresh = entries.filter((entry) => entry.frame.createdAt >= promotedAt);
1893
+ // Not due yet. Fewer frames exist since the promotion than the floor
1894
+ // asks for, so no pool could clear it and there is nothing to say.
1895
+ if (fresh.length < required)
1896
+ return null;
1897
+ const costWeight = Math.min(1, Math.max(0, dream.costWeight));
1898
+ const gainFor = this.#gainsFor(fresh, owner);
1899
+ const reasons = {};
1900
+ let total = 0;
1901
+ let closed = 0;
1902
+ let abstained = 0;
1903
+ for (const entry of fresh) {
1904
+ if (signal.aborted || Date.now() > deadline)
1905
+ break;
1906
+ const result = measure(entry.frame.payload, arm, gainFor(entry.trace.turnId), costWeight);
1907
+ // An abstention is not a low score; it is the absence of one - and a
1908
+ // counted quantity with a name (5.4), never a frame that drops out of
1909
+ // the pool unnoticed.
1910
+ if (!result.ok) {
1911
+ abstained += 1;
1912
+ reasons[result.abstain] = (reasons[result.abstain] ?? 0) + 1;
1913
+ continue;
1914
+ }
1915
+ total += result.score;
1916
+ closed += 1;
1917
+ }
1918
+ const seen = {
1919
+ offered: fresh.length,
1920
+ closed,
1921
+ abstained,
1922
+ reasons,
1923
+ required,
1924
+ promised: active.replayScore,
1925
+ };
1926
+ // The floor is read against what CLOSED, not against what was offered.
1927
+ // Fifty offered frames of which forty-nine abstain carry one trace of
1928
+ // noise, and `calibration` is a freeze a person has to undo by hand
1929
+ // (10.3): a test that could not close enough frames reports that it
1930
+ // could not run, and freezes nothing.
1931
+ if (closed < required)
1932
+ return { ...seen, drift: null, observed: null };
1933
+ const observed = total / closed;
1934
+ // The reading itself goes on the version it judges. The drift decides
1935
+ // whether the slot freezes tonight; `online_score` is what a person
1936
+ // reads next to `replay_score` later - "this is what the promise was
1937
+ // worth once it was actually in force" (5.5c). A test that could not
1938
+ // close enough frames returned above and writes nothing: an absent
1939
+ // reading stays absent rather than being recorded as a bad one.
1940
+ this.#store.setPolicyOnlineScore(active.id, observed);
1941
+ return { ...seen, drift: observed - active.replayScore, observed };
1942
+ }
1943
+ /**
1944
+ * Freeze the slot if one of the four causes of 10.3 fired.
1945
+ *
1946
+ * A frozen slot keeps measuring and stops promoting, which is what makes
1947
+ * it readable later: the evaluations written while it was frozen are the
1948
+ * evidence a person thaws it on. An already frozen slot keeps the reason
1949
+ * it was frozen for - re-stamping tonight's cause over last night's would
1950
+ * lose the one thing somebody needs in order to decide.
1951
+ */
1952
+ #freeze(owner, slot, wake, holdout, agreement) {
1953
+ const state = this.#store.slotState(owner, slot);
1954
+ if (state.frozenAt)
1955
+ return '';
1956
+ const reason = freezeReasonFor({
1957
+ // Null where the wake test could not read a verdict: a drift nobody
1958
+ // measured freezes nothing (10.3).
1959
+ calibrationDrift: wake ? wake.drift : null,
1960
+ tolerance: this.#config.memory.dream.tolerance,
1961
+ signAgree: holdout?.signAgree ?? null,
1962
+ agreement,
1963
+ });
1964
+ if (!reason)
1965
+ return '';
1966
+ freezeFor(this.#store, owner, slot, reason);
1967
+ this.#log.warn('A dream slot was frozen', { owner, slot, reason });
1968
+ return (' The ' + slot + ' slot is frozen (' + reason +
1969
+ '): it goes on measuring and stops promoting until somebody thaws it.');
1970
+ }
1971
+ /** Tell whoever wants to know that a parameter set went in force (S26). */
1972
+ async #announcePromotion(notice) {
1973
+ this.#log.info('A retrieval policy went in force', {
1974
+ owner: notice.owner,
1975
+ slot: notice.slot,
1976
+ version: notice.version.version,
1977
+ policy: notice.version.id,
1978
+ previous: notice.prevActiveId,
1979
+ run: notice.runId,
1980
+ });
1981
+ if (!this.#onPromotion)
1982
+ return;
1983
+ try {
1984
+ await this.#onPromotion(notice);
1985
+ }
1986
+ catch (cause) {
1987
+ // Telling somebody is not part of the promotion. A hook that throws
1988
+ // costs the message, never the night.
1989
+ this.#log.warn('The promotion hook failed', {
1990
+ owner: notice.owner,
1991
+ error: cause.message,
1992
+ });
1993
+ }
1994
+ }
1995
+ /**
1996
+ * The candidate writer (concept 6.2): one model call per candidate, on
1997
+ * `dream.model`, at `dream.effort` - never at `ask`'s wired `'low'`,
1998
+ * because designing a parameter set out of failure cases is judgement and
1999
+ * not extraction (S16/E14). Its own caller lives in `dream/candidate.ts`
2000
+ * for exactly that reason.
2001
+ *
2002
+ * What it writes are PROPOSALS, not policies: unpromoted `policy_versions`
2003
+ * rows that the next night's dream measures, ranks and possibly promotes.
2004
+ * That is what keeps the promotion path model-free and above the provider
2005
+ * guard - a night without a provider proposes nothing and still promotes
2006
+ * what the last one proposed.
2007
+ *
2008
+ * The wallet is run-global (`dream.maxCallsPerNight` across ALL owners,
2009
+ * concept 9.4): with `sleep.scope: 'all'` the runtime runs one night per
2010
+ * bank, sequentially, so a per-run ceiling would multiply by the number of
2011
+ * banks. The budget arrives already measured; the first line spends
2012
+ * nothing if there is none, and there is no abort throw between here and
2013
+ * the caller's next one.
2014
+ */
2015
+ async #propose(provider, owner, runId, signal, budget) {
2016
+ if (budget <= 0 || signal.aborted)
2017
+ return { written: 0, calls: 0 };
2018
+ const idle = { written: 0, calls: 0 };
2019
+ const dream = this.#config.memory.dream;
2020
+ if (!dream.enabled || owner !== ASSISTANT_MEMORY_OWNER)
2021
+ return idle;
2022
+ if (!dream.slots.includes('recall'))
2023
+ return idle;
2024
+ // The newest frames, for the reason `#recallSlot` gives: a writer that
2025
+ // reads the oldest slice of a full store writes candidates for a day
2026
+ // weeks gone (S3).
2027
+ const entries = this.#store
2028
+ .framesFor(owner, { limit: DREAM_POOL_LIMIT, newest: true })
2029
+ .filter((entry) => entry.trace.sleepRunId !== runId);
2030
+ // The writer reads the TRAINING half and nothing else. A proposal
2031
+ // written out of holdout traces is a proposal measured on evidence the
2032
+ // search has already seen, and the one interval that will be read would
2033
+ // stop being the one interval nobody looked at (E4/6.2).
2034
+ const pool = splitPool(entries, DEFAULT_SPLIT_RATES).train;
2035
+ if (!pool.length)
2036
+ return idle;
2037
+ const incumbent = resolvePolicy(this.#store, this.#config, owner, 'recall');
2038
+ const box = pool[pool.length - 1].frame.box;
2039
+ const aggregates = this.#aggregateCases(pool, this.#gainsFor(pool, owner), incumbent);
2040
+ // Nothing went wrong that a parameter set could have fixed, so nothing
2041
+ // is asked of a model.
2042
+ if (!aggregates.cases)
2043
+ return idle;
2044
+ const proposal = await proposeCandidates(provider, {
2045
+ aggregates,
2046
+ box,
2047
+ incumbent,
2048
+ count: Math.min(Math.max(0, Math.round(dream.candidates)), budget),
2049
+ model: dream.model.trim() || undefined,
2050
+ effort: dream.effort,
2051
+ }, signal);
2052
+ const parentId = this.#store.activePolicy(owner, 'recall')?.id;
2053
+ for (const candidate of proposal.candidates) {
2054
+ this.#store.createPolicyVersion({
2055
+ owner,
2056
+ slot: 'recall',
2057
+ params: paramsOf(candidate, incumbent),
2058
+ box: box,
2059
+ origin: 'dream',
2060
+ parentId,
2061
+ sleepRunId: runId,
2062
+ // Numbers and this file's vocabulary, never a word out of the frames
2063
+ // it was written from: a version row outlives every one of them
2064
+ // (E19/S21).
2065
+ rationale: 'proposal cases=' + aggregates.cases +
2066
+ ' scored=' + aggregates.scored +
2067
+ ' missed=' + aggregates.missedRows.toFixed(2) +
2068
+ ' budget-cut=' + aggregates.budgetCutShare.toFixed(3) +
2069
+ ' hop2=' + aggregates.hop2Share.toFixed(3),
2070
+ });
2071
+ }
2072
+ this.#log.info('The dream wrote candidates', {
2073
+ owner,
2074
+ cases: aggregates.cases,
2075
+ calls: proposal.calls,
2076
+ written: proposal.candidates.length,
2077
+ failures: proposal.failures,
2078
+ rejected: proposal.rejected,
2079
+ });
2080
+ return { written: proposal.candidates.length, calls: proposal.calls };
2081
+ }
2082
+ /**
2083
+ * One night's bad cases, aggregated into the only thing the candidate
2084
+ * writer gets to see (concept 6.2).
2085
+ *
2086
+ * Frame by frame, each with its OWN turn's gain: a gain is a statement
2087
+ * about one turn, and folding every turn's labels into one function would
2088
+ * let a memory proven relevant in one turn score in every other - the same
2089
+ * reason the freshness sensor walks its pool entry by entry. What comes
2090
+ * out is therefore a macro-average over cases rather than over rows, and
2091
+ * that is what the writer needs: it reads directions out of these numbers,
2092
+ * not magnitudes.
2093
+ */
2094
+ #aggregateCases(entries, gainFor, policy) {
2095
+ const missed = zeroMeans();
2096
+ const delivered = zeroMeans();
2097
+ const firstHitRanks = [];
2098
+ let scored = 0;
2099
+ let abstained = 0;
2100
+ let cases = 0;
2101
+ let missedRows = 0;
2102
+ let renderedRows = 0;
2103
+ let budgetCut = 0;
2104
+ let hop2 = 0;
2105
+ let coverage = 0;
2106
+ let chars = 0;
2107
+ for (const entry of entries) {
2108
+ const one = buildAggregates([entry.frame.payload], gainFor(entry.trace.turnId), policy);
2109
+ scored += one.scored;
2110
+ abstained += one.abstained;
2111
+ if (one.scored) {
2112
+ renderedRows += one.renderedRows;
2113
+ coverage += one.coverage;
2114
+ chars += one.chars;
675
2115
  }
676
- written += 1;
2116
+ if (!one.cases)
2117
+ continue;
2118
+ cases += one.cases;
2119
+ addMeans(missed, one.missed);
2120
+ addMeans(delivered, one.delivered);
2121
+ missedRows += one.missedRows;
2122
+ budgetCut += one.budgetCutShare;
2123
+ hop2 += one.hop2Share;
2124
+ firstHitRanks.push(...one.firstHitRanks);
2125
+ }
2126
+ return {
2127
+ frames: entries.length,
2128
+ scored,
2129
+ abstained,
2130
+ cases,
2131
+ missed: divideMeans(missed, cases),
2132
+ delivered: divideMeans(delivered, cases),
2133
+ missedRows: cases ? missedRows / cases : 0,
2134
+ renderedRows: scored ? renderedRows / scored : 0,
2135
+ firstHitRanks,
2136
+ budgetCutShare: cases ? budgetCut / cases : 0,
2137
+ hop2Share: cases ? hop2 / cases : 0,
2138
+ coverage: scored ? coverage / scored : 0,
2139
+ chars: scored ? chars / scored : 0,
2140
+ };
2141
+ }
2142
+ /** `gain(m)` per turn over a pool, read once and folded per turn (4.1). */
2143
+ #gainsFor(entries, owner) {
2144
+ const byTurn = new Map();
2145
+ for (const label of this.#labelsFor(entries, owner)) {
2146
+ const bucket = byTurn.get(label.turnId);
2147
+ if (bucket)
2148
+ bucket.push(label);
2149
+ else
2150
+ byTurn.set(label.turnId, [label]);
2151
+ }
2152
+ const cache = new Map();
2153
+ return (turnId) => {
2154
+ const known = cache.get(turnId);
2155
+ if (known)
2156
+ return known;
2157
+ // `gainFrom` is what refuses a session-wide label and a `review` row a
2158
+ // gain, so no caller here has to remember to (S3/S8).
2159
+ const gain = gainFrom(byTurn.get(turnId) ?? []).gain;
2160
+ cache.set(turnId, gain);
2161
+ return gain;
2162
+ };
2163
+ }
2164
+ /**
2165
+ * Every label behind a pool: the turn-scoped ones that can carry a gain,
2166
+ * and the session-scoped ones that cannot but still count for the
2167
+ * agreement sensor and the coverage rate (4.4/5.5b). Read in batches, so a
2168
+ * pool of five hundred frames cannot walk into SQLite's bound-parameter
2169
+ * limit, and owner-filtered in SQL the way 10.5 asks.
2170
+ */
2171
+ #labelsFor(entries, owner) {
2172
+ const turnIds = [...new Set(entries.map((entry) => entry.trace.turnId))];
2173
+ const sessionIds = [
2174
+ ...new Set(entries.map((entry) => entry.trace.sessionId).filter((id) => !!id)),
2175
+ ];
2176
+ const labels = [];
2177
+ for (let index = 0; index < turnIds.length; index += LABEL_BATCH) {
2178
+ labels.push(...this.#store.labelsForTurns(turnIds.slice(index, index + LABEL_BATCH), owner));
2179
+ }
2180
+ for (let index = 0; index < sessionIds.length; index += LABEL_BATCH) {
2181
+ labels.push(...this.#store.labelsForSessions(sessionIds.slice(index, index + LABEL_BATCH), owner));
2182
+ }
2183
+ return labels;
2184
+ }
2185
+ /**
2186
+ * The proposals a previous night wrote and nothing has measured yet.
2187
+ *
2188
+ * The discriminator is `replayScore`: a version that carries one has had
2189
+ * its night, and one that was promoted or retired is not on offer. Nothing
2190
+ * else is needed, because a measured candidate gets its replay numbers
2191
+ * written onto its row in the same breath as its evaluation.
2192
+ */
2193
+ #proposals(owner, slot, incumbent, limit) {
2194
+ const wanted = Math.max(0, Math.round(limit));
2195
+ if (!wanted)
2196
+ return [];
2197
+ const out = [];
2198
+ for (const version of this.#store.policyHistory(owner, slot, PROPOSAL_WINDOW)) {
2199
+ if (version.origin !== 'dream' || version.promotedAt || version.retiredAt)
2200
+ continue;
2201
+ if (version.replayScore !== undefined)
2202
+ continue;
2203
+ // A row nobody can read back into a policy point is not a candidate.
2204
+ const policy = policyFromParams(version.params, incumbent);
2205
+ if (!policy)
2206
+ continue;
2207
+ out.push({ version, policy });
2208
+ if (out.length >= wanted)
2209
+ break;
2210
+ }
2211
+ return out;
2212
+ }
2213
+ /**
2214
+ * H1's coverage figure (10.1): how many distinct memories an arm ever
2215
+ * surfaced over the same sample of frames. The absolute number means
2216
+ * nothing; both arms are counted the same way over the same sample, which
2217
+ * is all `admit` asks for. The newest slice of the TRAINING half, because
2218
+ * the whole pool would double the evaluation's work for a predicate - and
2219
+ * because the frozen audit set is not something a predicate may read
2220
+ * (5.5d).
2221
+ *
2222
+ * It replays whole frames through the pipeline, which is real work, so it
2223
+ * runs under the night's one wall clock and its abort signal like every
2224
+ * other part of the dream - both checked BEFORE the first frame, so a
2225
+ * clock that is already spent costs the predicate rather than overrunning
2226
+ * it. A sample cut short leaves both arms at the count they reached, and
2227
+ * `coverageFloorHolds` compares them as it always does.
2228
+ */
2229
+ #coverageOf(entries, policy, deadline, signal) {
2230
+ const seen = new Set();
2231
+ for (const entry of entries.slice(-ADMISSION_SAMPLE)) {
2232
+ if (signal.aborted || Date.now() > deadline)
2233
+ break;
2234
+ for (const id of this.#replayFrame(entry, policy))
2235
+ seen.add(id);
2236
+ }
2237
+ return seen.size;
2238
+ }
2239
+ /** The ids that stood in one frame's block, in prompt order, at one point. */
2240
+ #replayFrame(entry, policy) {
2241
+ const frame = entry.frame.payload;
2242
+ const run = frame.pipeline === 'agent' ? pipelineAgent(frame, policy) : pipelineAssistant(frame, policy);
2243
+ return run.ok ? run.lines.map((line) => line.id) : [];
2244
+ }
2245
+ /** What the block actually held, replayed at the policy it was fetched with. */
2246
+ #promptedOf(entry) {
2247
+ return this.#replayFrame(entry, entry.trace.policySet.recall ?? {});
2248
+ }
2249
+ /**
2250
+ * One `dream_evals` row out of one finished evaluation (concept 8.6).
2251
+ *
2252
+ * Written out field by field rather than spread: `DreamEvalResult` also
2253
+ * carries the certificate (`valid`, `violations`, `error`) and the paired
2254
+ * counts, and those belong to the decision, not to the row.
2255
+ */
2256
+ #recordEval(result, policyId, sleepRunId, promoted) {
2257
+ return this.#store.recordDreamEval({
2258
+ sleepRunId,
2259
+ policyId,
2260
+ slot: result.slot,
2261
+ traces: result.traces,
2262
+ closed: result.closed,
2263
+ abstained: result.abstained,
2264
+ abstainReasons: result.abstainReasons,
2265
+ reachableRate: result.reachableRate,
2266
+ labelCoverage: result.labelCoverage,
2267
+ costOnlyShare: result.costOnlyShare,
2268
+ score: result.score,
2269
+ baseline: result.baseline,
2270
+ delta: result.delta,
2271
+ ciLow: result.ciLow,
2272
+ ciHigh: result.ciHigh,
2273
+ auditDelta: result.auditDelta,
2274
+ auditCiLow: result.auditCiLow,
2275
+ deltaLive: result.deltaLive,
2276
+ signAgree: result.signAgree,
2277
+ evalMs: result.evalMs,
2278
+ traceSetHash: result.traceSetHash,
2279
+ evidenceDigest: result.evidenceDigest ?? renderEvidenceDigest(result),
2280
+ promoted,
2281
+ detail: result.detail,
2282
+ });
2283
+ }
2284
+ /**
2285
+ * From the corrections this replay wrote to the labels they prove
2286
+ * (concept 4.2a, step 2).
2287
+ *
2288
+ * The pass runs once, after every session has been read, because
2289
+ * `addCorrection` hands no id back and a label's evidence is the
2290
+ * correction's id - so the rows are read back out of the table, which is
2291
+ * also where the turn reference the write already put on them lives.
2292
+ *
2293
+ * Two refusals are built in. A located turn whose frame was never recorded
2294
+ * (`dream.frameRate` frames a quarter of the sessions) has no reachable
2295
+ * set of its own, so its label goes out session-wide rather than claiming
2296
+ * a turn over a union of other turns' rows. And an unlocatable quote is
2297
+ * anchored at the session's start, which is no later than any of its turns
2298
+ * and therefore the conservative side of the anachronism lock (S4).
2299
+ */
2300
+ #writeCorrectionLabels(owner, sessions, since) {
2301
+ const idle = { labelled: 0, labels: 0, failed: 0 };
2302
+ if (!this.#config.memory.dream.enabled || !sessions.length)
2303
+ return idle;
2304
+ try {
2305
+ return this.#correctionLabelPass(owner, sessions, since);
2306
+ }
2307
+ catch (cause) {
2308
+ // The dream never turns a degraded path into an error (10.5). One
2309
+ // unreadable frame payload, or a store that refuses the write, used to
2310
+ // throw all the way into the night's outer catch - which ends the run
2311
+ // failed and skips `recountEntities` AND every retention sweep behind
2312
+ // it, so the verbatim frame store outlives its window for exactly the
2313
+ // reason the dream must never cause (10.4, 8.7). It costs its labels
2314
+ // and nothing else.
2315
+ this.#log.warn('Writing correction labels failed', {
2316
+ owner,
2317
+ error: cause.message,
2318
+ });
2319
+ return { labelled: 0, labels: 0, failed: 1 };
2320
+ }
2321
+ }
2322
+ /** The body of `#writeCorrectionLabels`, inside its caller's catch. */
2323
+ #correctionLabelPass(owner, sessions, since) {
2324
+ const idle = { labelled: 0, labels: 0, failed: 0 };
2325
+ const rows = this.#store.correctionsSince(owner, since);
2326
+ if (!rows.length)
2327
+ return idle;
2328
+ const bySession = new Map(sessions.map((session) => [session.id, session]));
2329
+ const frames = this.#framesBySession(owner, sessions);
2330
+ const threshold = this.#config.memory.gate.duplicateThreshold;
2331
+ const now = Date.now();
2332
+ const labels = [];
2333
+ let labelled = 0;
2334
+ for (const row of rows) {
2335
+ const session = row.sessionId ? bySession.get(row.sessionId) : undefined;
2336
+ if (!session)
2337
+ continue;
2338
+ const pool = frames.get(session.id) ?? [];
2339
+ if (!pool.length)
2340
+ continue;
2341
+ const anchored = row.turnId
2342
+ ? pool.find((entry) => entry.trace.turnId === row.turnId)
2343
+ : undefined;
2344
+ const scope = anchored ? [anchored] : pool;
2345
+ const reachable = new Map();
2346
+ const prompted = new Set();
2347
+ for (const entry of scope) {
2348
+ for (const record of Object.values(entry.frame.payload.records)) {
2349
+ reachable.set(record.id, record);
2350
+ }
2351
+ for (const id of this.#promptedOf(entry))
2352
+ prompted.add(id);
2353
+ }
2354
+ const made = correctionLabels({
2355
+ text: row.text,
2356
+ owner,
2357
+ sessionId: session.id,
2358
+ turn: anchored && row.turnId ? { id: row.turnId, startedAt: anchored.trace.startedAt } : null,
2359
+ sessionStartedAt: session.createdAt,
2360
+ reachable: [...reachable.values()],
2361
+ prompted: [...prompted],
2362
+ // The same arithmetic the write gate already owns; passed in,
2363
+ // because `label.ts` reads no config.
2364
+ duplicateThreshold: threshold,
2365
+ evidence: row.id,
2366
+ now,
2367
+ });
2368
+ if (made.length)
2369
+ labelled += 1;
2370
+ labels.push(...made);
2371
+ }
2372
+ return { labelled, labels: this.#store.putLabels(labels), failed: 0 };
2373
+ }
2374
+ /**
2375
+ * The `merge` labels of one condensation pass (concept 4.2c, S7).
2376
+ *
2377
+ * The claim is narrow and it only points one way: if two rows stood in ONE
2378
+ * prompt and later fell into the same condensation cluster, the
2379
+ * worse-placed of the two is proven redundant. Redundant is not
2380
+ * "irrelevant to this question", so no positive label can come out of this
2381
+ * source and none is written.
2382
+ *
2383
+ * At most one `supersedes` hop, and it is the map this night filled that
2384
+ * enforces it: re-reading `superseded_by` off the bank would pick up
2385
+ * chains from earlier nights, and a label that walks that far has stopped
2386
+ * describing the prompt it observed. The pre-filter is what keeps this
2387
+ * cheap - a frame that never held two of tonight's victims cannot carry a
2388
+ * cluster, and replaying it would cost a pipeline run for nothing.
2389
+ */
2390
+ #writeMergeLabels(owner, superseded) {
2391
+ if (!this.#config.memory.dream.enabled || superseded.size < 2) {
2392
+ return { labels: 0, failed: 0 };
2393
+ }
2394
+ try {
2395
+ return { labels: this.#mergeLabelPass(owner, superseded), failed: 0 };
2396
+ }
2397
+ catch (cause) {
2398
+ // Its own failure, caught here for the reason `#writeCorrectionLabels`
2399
+ // gives above: a label is worth a condensation, never a night (10.5).
2400
+ this.#log.warn('Writing merge labels failed', {
2401
+ owner,
2402
+ error: cause.message,
2403
+ });
2404
+ return { labels: 0, failed: 1 };
2405
+ }
2406
+ }
2407
+ /** The body of `#writeMergeLabels`, inside its caller's catch. */
2408
+ #mergeLabelPass(owner, superseded) {
2409
+ const now = Date.now();
2410
+ const labels = [];
2411
+ // The newest frames, like every other reader that means "lately": an
2412
+ // owner past the cap would otherwise have its merge labels written only
2413
+ // against a slice of frames weeks older than the condensation they
2414
+ // describe (S3).
2415
+ for (const entry of this.#store.framesFor(owner, { limit: DREAM_POOL_LIMIT, newest: true })) {
2416
+ let held = 0;
2417
+ for (const id of Object.keys(entry.frame.payload.records)) {
2418
+ if (superseded.has(id))
2419
+ held += 1;
2420
+ }
2421
+ if (held < 2)
2422
+ continue;
2423
+ const prompted = this.#promptedOf(entry);
2424
+ if (prompted.length < 2)
2425
+ continue;
2426
+ labels.push(...mergeLabels({
2427
+ owner,
2428
+ sessionId: entry.trace.sessionId,
2429
+ turnId: entry.trace.turnId,
2430
+ prompted,
2431
+ targets: prompted.map((id) => {
2432
+ const into = superseded.get(id);
2433
+ return into ? { id, supersededBy: into } : { id };
2434
+ }),
2435
+ now,
2436
+ }));
2437
+ }
2438
+ return this.#store.putLabels(labels);
2439
+ }
2440
+ /** The frames of the replayed sessions, grouped by session. */
2441
+ #framesBySession(owner, sessions) {
2442
+ const map = new Map();
2443
+ if (!sessions.length)
2444
+ return map;
2445
+ const wanted = new Set(sessions.map((session) => session.id));
2446
+ // From the oldest replayed session onwards, not from the last night: a
2447
+ // conversation that began days ago has its early frames back there too.
2448
+ const since = Math.min(...sessions.map((session) => session.createdAt));
2449
+ for (const entry of this.#store.framesFor(owner, { since, limit: DREAM_POOL_LIMIT })) {
2450
+ const id = entry.trace.sessionId;
2451
+ if (!id || !wanted.has(id))
2452
+ continue;
2453
+ const bucket = map.get(id);
2454
+ if (bucket)
2455
+ bucket.push(entry);
2456
+ else
2457
+ map.set(id, [entry]);
2458
+ }
2459
+ return map;
2460
+ }
2461
+ /**
2462
+ * What `correction` actually yielded tonight, and what the night says when
2463
+ * it is not enough (`dream.correctionPrecisionFloor`, concept 4.2a).
2464
+ *
2465
+ * Be exact about what this number is. The concept asks for the hand-judged
2466
+ * hit rate over at least fifty corrections, and no night can compute that.
2467
+ * What a night CAN observe without a model is the yield: the share of
2468
+ * admitted corrections that found any target at all. The two are not the
2469
+ * same quantity, and the asymmetry is what makes the yield worth reading -
2470
+ * a source that finds nothing cannot be precise about anything, so a yield
2471
+ * under the floor is reason enough to distrust `correction`, while a yield
2472
+ * over it proves nothing about precision.
2473
+ *
2474
+ * And when it falls short, the night SAYS so rather than carrying on
2475
+ * quietly. The named alternative is a model call per correction, which is
2476
+ * `dream.labelModelCalls` and is 0: the post exists in the report so that
2477
+ * turning it on is a decision somebody takes, not a default that arrives.
2478
+ */
2479
+ #correctionPrecision(replayed) {
2480
+ const dream = this.#config.memory.dream;
2481
+ if (!dream.enabled || replayed.corrections <= 0)
2482
+ return '';
2483
+ const precision = replayed.labelled / replayed.corrections;
2484
+ this.#log.info('Correction labelling measured', {
2485
+ corrections: replayed.corrections,
2486
+ labelled: replayed.labelled,
2487
+ labels: replayed.labels,
2488
+ precision,
2489
+ floor: dream.correctionPrecisionFloor,
2490
+ modelCalls: dream.labelModelCalls,
2491
+ });
2492
+ if (precision >= dream.correctionPrecisionFloor)
2493
+ return '';
2494
+ return (' Correction labelling reached ' + Math.round(precision * 100) + ' percent of ' +
2495
+ plural(replayed.corrections, 'correction', 'corrections') +
2496
+ ', below dream.correctionPrecisionFloor (' + dream.correctionPrecisionFloor +
2497
+ '): while it stays there, corrections are not a label source. The named alternative is a' +
2498
+ ' model call per correction (dream.labelModelCalls is ' + dream.labelModelCalls +
2499
+ '), and it is not built.');
2500
+ }
2501
+ /**
2502
+ * The `budget` and `retry` slots, measured (concept 7.1, S24).
2503
+ *
2504
+ * `budget` is measured out of what this night actually spent per phase and
2505
+ * got back for it - `yieldRates` reports the observed rate WITH its
2506
+ * spread, labelled approximate, and a projection that would have to
2507
+ * extrapolate past the call counts anybody was ever seen spending abstains
2508
+ * instead of guessing. One night is one sample; the record accumulates in
2509
+ * the log, night by night, which is what a later stage would promote on.
2510
+ *
2511
+ * `retry` is not measured here and the reason is worth writing down: it
2512
+ * judges a realized sequence of attempts, and no attempt sequence reaches
2513
+ * this file. Those live on the assignment path, which is the organisation's
2514
+ * side of the house. `judgeRetry` is built and tested; its caller is not
2515
+ * the night.
2516
+ *
2517
+ * Neither slot is carried. `dream.slots` is what decides that, and this
2518
+ * stage has a promotion path for `recall` alone - so a `budget` in the
2519
+ * list changes exactly one thing today: this line says the night would
2520
+ * have carried it.
2521
+ */
2522
+ #measureSlots(owner, spend) {
2523
+ const dream = this.#config.memory.dream;
2524
+ if (!dream.enabled)
2525
+ return;
2526
+ const rates = yieldRates(NIGHT_PHASES.map((phase) => ({
2527
+ owner,
2528
+ phase,
2529
+ calls: spend[phase].calls,
2530
+ value: spend[phase].value,
2531
+ })));
2532
+ if (!rates.length)
2533
+ return;
2534
+ this.#log.info('The night measured its own yield', {
2535
+ owner,
2536
+ wouldCarry: dream.slots.filter((slot) => slot !== 'recall').join(',') || 'nothing',
2537
+ rates: rates.map((rate) => ({
2538
+ phase: rate.phase,
2539
+ perCall: rate.meanPerCall,
2540
+ low: rate.low,
2541
+ high: rate.high,
2542
+ calls: rate.callsRange,
2543
+ samples: rate.samples,
2544
+ approximated: rate.approximated,
2545
+ })),
2546
+ });
2547
+ }
2548
+ /**
2549
+ * What is left of the run-global dream wallet (concept 9.4).
2550
+ *
2551
+ * A window opens with the first dream call and closes after
2552
+ * `DREAM_NIGHT_WINDOW_MS` of quiet. That is what "one night" has to mean
2553
+ * for a process with no calendar: the runtime runs the due banks in one
2554
+ * sequential loop, so every one of them draws on the same wallet, and a
2555
+ * night a day later starts with a full one.
2556
+ */
2557
+ #dreamBudget() {
2558
+ const ceiling = Math.max(0, Math.round(this.#config.memory.dream.maxCallsPerNight));
2559
+ const now = Date.now();
2560
+ if (now - this.#dreamCalls.since > DREAM_NIGHT_WINDOW_MS) {
2561
+ this.#dreamCalls = { since: now, spent: 0 };
677
2562
  }
678
- return { written, edges, calls: 1 };
2563
+ return Math.max(0, ceiling - this.#dreamCalls.spent);
2564
+ }
2565
+ /** Book model calls against that wallet, spent or wasted. */
2566
+ #spendDreamCalls(calls) {
2567
+ if (calls <= 0)
2568
+ return;
2569
+ if (!this.#dreamCalls.since)
2570
+ this.#dreamCalls.since = Date.now();
2571
+ this.#dreamCalls.spent += calls;
679
2572
  }
680
2573
  /* ------------------------------ internals ------------------------------ */
681
2574
  async #resolveProvider(wanted) {
@@ -739,11 +2632,16 @@ Rules:
739
2632
  - "weight" is your confidence between 0 and 1.
740
2633
  - Also classify recognisable proper names as:
741
2634
  person, project, tool, place, org or topic.
2635
+ - If two DIFFERENT names in the list clearly mean the same real thing
2636
+ ("Rookery" and "Rookery-Agent", "TS" and "TypeScript"), list them under
2637
+ "aliases": "from" is the variant, "into" the canonical name. Only when you
2638
+ are sure they are the same thing; a wrong merge loses structure.
742
2639
 
743
2640
  Reply ONLY with JSON, no prose or code fence:
744
2641
  {"edges":[{"from":1,"to":4,"relation":"refines","weight":0.8}],
745
- "entities":[{"name":"Rookery","kind":"project"}]}
746
- An empty result is {"edges":[],"entities":[]}`;
2642
+ "entities":[{"name":"Rookery","kind":"project"}],
2643
+ "aliases":[{"from":"Rookery-Agent","into":"Rookery"}]}
2644
+ An empty result is {"edges":[],"entities":[],"aliases":[]}`;
747
2645
  const RESOLVE_PROMPT = `You are resolving a contradiction in a personal assistant's memory overnight.
748
2646
 
749
2647
  The two sentences below contradict each other. Decide which takes precedence. You must decide,
@@ -762,10 +2660,11 @@ Reply ONLY with JSON, no prose or code fence:
762
2660
  {"decision":"second"}
763
2661
  {"decision":"both"}
764
2662
  {"decision":"merge","content":"..."}`;
765
- const INSIGHT_PROMPT = `You are reflecting on a personal assistant's memory overnight.
2663
+ const INSIGHT_USER_PROMPT = `You are reflecting on a personal assistant's memory overnight.
766
2664
 
767
- The memories below come from recent days. What stands out BEYOND the individual sentences?
768
- Look for a pattern, habit, common thread or connection that no single sentence states.
2665
+ The memories below come from recent days. What stands out BEYOND the individual sentences
2666
+ ABOUT THE USER - the person this memory belongs to? Look for a pattern, habit, routine,
2667
+ preference or common thread that no single sentence states.
769
2668
 
770
2669
  Rules:
771
2670
  - At most {{MAX}} insights. None is the right answer when nothing stands out.
@@ -777,6 +2676,128 @@ Rules:
777
2676
  Reply ONLY with JSON, no prose or code fence:
778
2677
  {"insights":[{"content":"...","importance":0.8,"evidence":[1,4,7],"tags":["..."]}]}
779
2678
  An empty result is {"insights":[]}`;
2679
+ const INSIGHT_WORK_PROMPT = `You are reflecting on a personal assistant's memory overnight.
2680
+
2681
+ The memories below come from recent days. What stands out BEYOND the individual sentences
2682
+ ABOUT THE WORK - the projects, the tools, the way things get done? Look for what keeps
2683
+ recurring, what keeps costing time, what several efforts share, or what keeps going wrong
2684
+ the same way. The user has to be able to act on it.
2685
+
2686
+ Rules:
2687
+ - At most {{MAX}} insights. None is the right answer when nothing stands out.
2688
+ - Every insight needs at least TWO sources: the numbers supporting it.
2689
+ - Never repeat an individual memory as an insight. An insight says something new.
2690
+ - One sentence, third person, in the same language as the source memories.
2691
+ - Do not invent or speculate. Only state what the evidence actually supports.
2692
+
2693
+ Reply ONLY with JSON, no prose or code fence:
2694
+ {"insights":[{"content":"...","importance":0.8,"evidence":[1,4,7],"tags":["..."]}]}
2695
+ An empty result is {"insights":[]}`;
2696
+ const TRIAGE_PROMPT = `You decide whether one conversation is worth reading closely tonight.
2697
+
2698
+ Below are only the things the USER said in it, shortened. Answer one question: could a careful
2699
+ reading of this conversation yield something durable - a stable fact about the user, a preference
2700
+ about how they want things done, a project constraint, or a correction of something that was
2701
+ done wrong?
2702
+
2703
+ Say false for small talk, one-off requests, pure question-and-answer where the user reveals
2704
+ nothing about themselves, and anything that is only about the here and now. Most conversations
2705
+ are false. That is fine and expected - being wrong the cheap way costs one more reading, being
2706
+ wrong the expensive way costs nothing at all.
2707
+
2708
+ Reply ONLY with JSON, no prose or code fence:
2709
+ {"worth":true} or {"worth":false}`;
2710
+ const REPLAY_PROMPT = `You are re-reading one conversation at night, after it has ended.
2711
+
2712
+ It was already skimmed once, right after each turn, by a small fast model that saw one exchange
2713
+ at a time and never the whole. Your advantage is exactly that: you can see the arc. Look for what
2714
+ only shows up across the conversation - a preference mentioned early in passing, a constraint the
2715
+ user repeated in different words, a decision that emerged rather than being stated in one line.
2716
+
2717
+ TWO THINGS TO RETURN.
2718
+
2719
+ 1. memories - durable facts the USER STATED THEMSELVES, worth remembering weeks from now.
2720
+ Every one needs "evidence": a span copied VERBATIM, character for character, from a USER turn.
2721
+ Not from the assistant's. Not reworded, not translated, not tidied. A memory whose evidence is
2722
+ not found word for word in what the user wrote is thrown away before it is stored, so there is
2723
+ nothing to gain by inventing one.
2724
+ - one self-contained sentence each, third person about the user, in the user's own language
2725
+ - kinds: fact, preference, project, event
2726
+ - nothing already under ALREADY KNOWN, nothing the assistant worked out, nothing you inferred
2727
+ - a question is not a fact. "How do I deploy this?" says nothing durable.
2728
+ - importance: 0.9 identity and hard constraints, 0.7 preferences and active projects,
2729
+ 0.5 useful context, 0.3 minor detail
2730
+
2731
+ 2. corrections - places where the user put the assistant right: rejected an approach, restated
2732
+ something that had been misunderstood, or said a thing should be done differently in future.
2733
+ This is the signal nothing else in the system captures. Each needs the user's own words as
2734
+ "quote", under the same verbatim rule, and one sentence in "text" saying what should be done
2735
+ differently from now on. Irritation alone is not a correction; there has to be a should.
2736
+
2737
+ Returning empty lists is the ordinary answer for most conversations.
2738
+
2739
+ Reply ONLY with JSON, no prose or code fence:
2740
+ {"memories":[{"kind":"preference","content":"The user wants releases cut from main.","tags":["release"],"importance":0.7,"evidence":"cut releases from main"}],
2741
+ "corrections":[{"text":"Do not open a PR without running the tests first.","quote":"du hast wieder keine Tests laufen lassen"}]}`;
2742
+ const REVISE_PROMPT = `You maintain one written procedure that an assistant follows unattended.
2743
+
2744
+ Below is a skill as it currently reads, and everything that has changed since it was written:
2745
+ memories it was built on that have been replaced, retired or edited, and runs that had it open
2746
+ and then failed, with the real error text.
2747
+
2748
+ Decide ONE thing: does the skill still hold, or does it now mislead whoever opens it next?
2749
+
2750
+ Revise it when:
2751
+ - a step names something that has been replaced (a command, a path, a tool, a threshold)
2752
+ - an error shows a step simply does not work the way the skill claims
2753
+ - the skill is silent about a trap that has now caught a run
2754
+
2755
+ Do NOT revise when:
2756
+ - the change is unrelated to what the skill actually says
2757
+ - the run failed for a reason the skill never claimed to cover
2758
+ - you would only be rewording it. Churn is worse than an old sentence that is still true.
2759
+
2760
+ When you revise:
2761
+ - return the COMPLETE new body, not a diff and not only the changed part
2762
+ - change what is wrong and leave the rest alone, word for word
2763
+ - keep the same structure and the same language
2764
+ - fix the cause, not the symptom: if a command was renamed, rename it, do not add a note
2765
+ saying it might have been renamed
2766
+ - never invent a step you have no evidence for. If the error shows a step is wrong but not
2767
+ what the right one is, say so plainly in the skill rather than guessing a replacement.
2768
+
2769
+ Reply ONLY with JSON, no prose or code fence:
2770
+ {"revise":true,"description":"when to open this skill","body":"## Steps\\n1. ..."}
2771
+ Leaving it alone is {"revise":false}`;
2772
+ const SKILL_PROMPT = `You turn what an assistant has learned into something it can actually follow.
2773
+
2774
+ Below are the memories this assistant holds and the skills it already has. A memory says THAT
2775
+ something is true. A skill says HOW a kind of work is done, so it does not have to be figured out
2776
+ again. Your job is to notice where the memories have quietly documented a procedure, and to write
2777
+ that procedure down.
2778
+
2779
+ Write a skill ONLY when all of these hold:
2780
+ - the memories point at a RECURRING kind of task, not one thing that happened once
2781
+ - there is an actual procedure in them: an order to do things in, a tool to reach for, a mistake
2782
+ worth avoiding, a rule that keeps coming back
2783
+ - no existing skill already covers it
2784
+ - at least THREE of the numbered memories support it
2785
+
2786
+ Write at most {{MAX}}. Writing none is the ordinary answer - reply with an empty list and stop.
2787
+
2788
+ Revising a skill you wrote before (one marked "sleep" or "agent") counts towards the limit and is
2789
+ usually better than adding another one: reuse its exact name and write the improved version in
2790
+ full. NEVER reuse the name of a skill marked "user" - those belong to the person and are refused.
2791
+
2792
+ For the body: Markdown, written for somebody who has never seen these memories. Concrete names,
2793
+ paths, commands, thresholds. Steps in the order they are done. State the traps explicitly. No
2794
+ preamble, no restating of the memories, no "as an AI".
2795
+
2796
+ Write in the same language the memories are written in.
2797
+
2798
+ Reply ONLY with JSON, no prose or code fence:
2799
+ {"skills":[{"name":"release-checklist","description":"When cutting a release of the web package","body":"## Steps\\n1. ...","evidence":[2,5,9]}]}
2800
+ An empty result is {"skills":[]}`;
780
2801
  /* ------------------------------- helpers ------------------------------- */
781
2802
  /** What the night may never touch. */
782
2803
  function isProtected(memory) {
@@ -831,6 +2852,12 @@ export function parseObject(raw) {
831
2852
  /** The night in one line, in the language the user reads. */
832
2853
  export function describeSleep(counters) {
833
2854
  const parts = [counters.readCount + ' memories read'];
2855
+ if (counters.replayedCount) {
2856
+ parts.push(plural(counters.replayedCount, 'conversation', 'conversations') + ' re-read');
2857
+ }
2858
+ if (counters.learnedCount) {
2859
+ parts.push(plural(counters.learnedCount, 'memory', 'memories') + ' learned from them');
2860
+ }
834
2861
  if (counters.mergedCount)
835
2862
  parts.push(counters.mergedCount + ' condensed');
836
2863
  if (counters.dormantCount)
@@ -847,6 +2874,29 @@ export function describeSleep(counters) {
847
2874
  if (counters.insightCount) {
848
2875
  parts.push(plural(counters.insightCount, 'insight', 'insights') + ' recorded');
849
2876
  }
2877
+ if (counters.skillRevisedCount) {
2878
+ parts.push(plural(counters.skillRevisedCount, 'skill', 'skills') + ' revised');
2879
+ }
2880
+ if (counters.skillCount) {
2881
+ parts.push(plural(counters.skillCount, 'skill', 'skills') + ' written');
2882
+ }
2883
+ // The dream's own line: grid placements scored, the counter the probe
2884
+ // owns in stage 1 (its writer is the paired measure call, and the frame
2885
+ // rows it could not score appear in the log and the report suffix, not
2886
+ // here - a night that abstained everything still did the work).
2887
+ if (counters.dreamFramesScored) {
2888
+ parts.push(plural(counters.dreamFramesScored, 'dream placement', 'dream placements') + ' scored');
2889
+ }
2890
+ // Stage 2's own two. The labels are the supply side of the whole
2891
+ // apparatus - without them every delta is a delta over nothing - and a
2892
+ // promotion is the only line in this sentence that changed how the
2893
+ // assistant will behave tomorrow, so it goes last, where it is read.
2894
+ if (counters.dreamLabelsWritten) {
2895
+ parts.push(plural(counters.dreamLabelsWritten, 'dream label', 'dream labels') + ' written');
2896
+ }
2897
+ if (counters.dreamPromoted) {
2898
+ parts.push(plural(counters.dreamPromoted, 'retrieval policy', 'retrieval policies') + ' promoted');
2899
+ }
850
2900
  return parts.length === 1 ? parts[0] + ', nothing to do.' : parts.join(', ') + '.';
851
2901
  }
852
2902
  /**
@@ -872,6 +2922,91 @@ export function share(total, cycles, cycle, bias) {
872
2922
  };
873
2923
  return upTo(cycle) - upTo(cycle - 1);
874
2924
  }
2925
+ /**
2926
+ * Fund one night's work out of a fixed wallet.
2927
+ *
2928
+ * Every phase first asks for what it can actually use - demand, capped by
2929
+ * its own ceiling. If all of that fits under `cap`, everyone is funded in
2930
+ * full: a quiet week sleeps cheap because there is simply less to do. Only
2931
+ * when the demand overflows the wallet does the night have to choose, and
2932
+ * the rule is that the volume phases give way first. Condensing, deciding
2933
+ * and linking scale with the day's load, so one call shaved off each loses
2934
+ * the least; whatever they leave unfunded waits for tomorrow, which is
2935
+ * exactly what tomorrow is for. The judgement phases - insight, skill
2936
+ * repair, distillation - are a handful of calls and keep theirs until only
2937
+ * they are left, because an insight or a repair that never happens is not
2938
+ * deferred work, it is work that quietly never happens at all.
2939
+ *
2940
+ * The replay pass sits outside this wallet on purpose: its deep reads are
2941
+ * bounded by their own ceiling (`replaySessions`) and its triage is the
2942
+ * cheap model, and the replay has to run before the wallet can even be
2943
+ * measured - what it harvests is part of the workload being measured.
2944
+ */
2945
+ export function allocateNightBudget(demand, cap, ceilings) {
2946
+ const volume = ['condense', 'resolve', 'link'];
2947
+ const judgement = ['reflect', 'revise', 'practise'];
2948
+ // Derived, never re-listed (R20): a key present in a hand-written tuple
2949
+ // but in neither sub-list kept its uncapped allocation while the volume
2950
+ // phases were squeezed, and a demand key missing from the tuple never
2951
+ // reached `funded` at all - `budgets.x` read undefined, the phase guard
2952
+ // let it through and the phase ran unbudgeted. With the tuple derived
2953
+ // from the two lists, neither failure mode can be written.
2954
+ const keys = [...volume, ...judgement];
2955
+ const funded = new Map();
2956
+ for (const key of keys) {
2957
+ funded.set(key, Math.max(0, Math.min(demand[key] ?? 0, ceilings[key] ?? Number.POSITIVE_INFINITY)));
2958
+ }
2959
+ const sumOf = (which) => which.reduce((total, key) => total + (funded.get(key) ?? 0), 0);
2960
+ if (sumOf(keys) <= cap)
2961
+ return Object.fromEntries(funded);
2962
+ const judgementSum = sumOf(judgement);
2963
+ if (judgementSum >= cap) {
2964
+ // A starved night: only the judgement phases fit at all, and even they
2965
+ // have to share what is left.
2966
+ for (const key of volume)
2967
+ funded.set(key, 0);
2968
+ distribute(funded, judgement, cap);
2969
+ }
2970
+ else {
2971
+ distribute(funded, volume, cap - judgementSum);
2972
+ }
2973
+ return Object.fromEntries(funded);
2974
+ }
2975
+ /**
2976
+ * Share `cap` calls among `keys`, in proportion to what each asked for.
2977
+ * Floors first, then the rounding remainder one call at a time to whoever
2978
+ * asked for the most - so the parts always sum to exactly `cap` and no
2979
+ * phase is handed a fraction of a call. Never exceeds what was asked.
2980
+ */
2981
+ function distribute(funded, keys, cap) {
2982
+ const asked = keys.map((key) => funded.get(key) ?? 0);
2983
+ const askedSum = asked.reduce((total, want) => total + want, 0);
2984
+ if (askedSum <= 0 || cap <= 0) {
2985
+ for (const key of keys)
2986
+ funded.set(key, 0);
2987
+ return;
2988
+ }
2989
+ const given = asked.map((want) => Math.floor((cap * want) / askedSum));
2990
+ let left = cap - given.reduce((total, part) => total + part, 0);
2991
+ const order = keys
2992
+ .map((key, index) => ({ index, want: asked[index] }))
2993
+ .sort((a, b) => b.want - a.want);
2994
+ while (left > 0) {
2995
+ let moved = false;
2996
+ for (const entry of order) {
2997
+ if (left <= 0)
2998
+ break;
2999
+ if (given[entry.index] < asked[entry.index]) {
3000
+ given[entry.index] += 1;
3001
+ left -= 1;
3002
+ moved = true;
3003
+ }
3004
+ }
3005
+ if (!moved)
3006
+ break;
3007
+ }
3008
+ keys.forEach((key, index) => funded.set(key, given[index]));
3009
+ }
875
3010
  /** Use explicit singular and plural forms. */
876
3011
  function plural(count, one, many) {
877
3012
  return count + ' ' + (count === 1 ? one : many);
@@ -885,4 +3020,188 @@ function chunk(items, size) {
885
3020
  function clamp01(value) {
886
3021
  return Math.min(1, Math.max(0, Number.isFinite(value) ? value : 0));
887
3022
  }
3023
+ /**
3024
+ * A retention span in days, clamped for a config that bypassed the patch
3025
+ * schema (E21): `rookery config set` writes anything, so the night clamps
3026
+ * what it reads rather than trusting what was written. A hundred years is
3027
+ * the ceiling - beyond that the caller means "never sweep", and a negative
3028
+ * span would instead sweep everything, every night.
3029
+ */
3030
+ function clampDays(value) {
3031
+ const days = Number.isFinite(value) ? Math.round(value) : 0;
3032
+ return Math.min(36_500, Math.max(0, days));
3033
+ }
3034
+ /**
3035
+ * The abstention that dominated a pool, as half a sentence. Which one it was
3036
+ * is the whole point of counting them: `no-reachable-label` says the pool is
3037
+ * unlabelled, `corpus-drifted` says the index moved, and the two call for
3038
+ * entirely different answers.
3039
+ */
3040
+ function leadingReason(reasons) {
3041
+ let name = '';
3042
+ let most = 0;
3043
+ for (const [reason, count] of Object.entries(reasons)) {
3044
+ if ((count ?? 0) <= most)
3045
+ continue;
3046
+ most = count ?? 0;
3047
+ name = reason;
3048
+ }
3049
+ return name ? ', mostly ' + name : '';
3050
+ }
3051
+ /** Frames one night reads: the pool `framesFor` walks, oldest first. */
3052
+ const DREAM_POOL_LIMIT = 500;
3053
+ /**
3054
+ * Frames the admission check compares coverage over - the newest slice of
3055
+ * the pool. Both arms are counted the same way over the same sample, which
3056
+ * is the whole of what `admit` asks for; the full pool would double the
3057
+ * evaluation's work for a predicate.
3058
+ */
3059
+ const ADMISSION_SAMPLE = 50;
3060
+ /** Ids per label read: SQLite takes at most 999 bound parameters. */
3061
+ const LABEL_BATCH = 200;
3062
+ /** How deep into the version history a proposal may still be offered from. */
3063
+ const PROPOSAL_WINDOW = 50;
3064
+ /**
3065
+ * How long one night lasts for the run-global model-call ceiling. With
3066
+ * `sleep.scope: 'all'` the runtime runs the due banks sequentially in one
3067
+ * loop, so they all draw on one wallet; half a day of quiet opens a new one.
3068
+ */
3069
+ const DREAM_NIGHT_WINDOW_MS = 12 * 60 * 60 * 1000;
3070
+ /** Every field of a proposed point comes from the dream, by construction. */
3071
+ const DREAM_ORIGIN = {
3072
+ limit: 'dream',
3073
+ threshold: 'dream',
3074
+ hopEntity: 'dream',
3075
+ hopEdge: 'dream',
3076
+ relevance: 'dream',
3077
+ importance: 'dream',
3078
+ recency: 'dream',
3079
+ usage: 'dream',
3080
+ };
3081
+ /**
3082
+ * A grid placement is a point, not a policy: it carries the four weights and
3083
+ * the four knobs and nothing else. `kinds` and `minImportance` come from the
3084
+ * incumbent, because they are SQL filters rather than scoring terms and
3085
+ * widening either would admit rows the frame never fetched (concept 3.4).
3086
+ */
3087
+ function liftPolicy(placement, incumbent) {
3088
+ return {
3089
+ limit: Math.round(placement.limit ?? incumbent.limit),
3090
+ threshold: placement.threshold ?? incumbent.threshold,
3091
+ w: placement.w ?? incumbent.w,
3092
+ hopEntity: placement.hopEntity ?? incumbent.hopEntity,
3093
+ hopEdge: placement.hopEdge ?? incumbent.hopEdge,
3094
+ kinds: incumbent.kinds,
3095
+ minImportance: incumbent.minImportance,
3096
+ origin: DREAM_ORIGIN,
3097
+ };
3098
+ }
3099
+ /**
3100
+ * The `params` blob a promoted version stores, in exactly the shape
3101
+ * `resolvePolicy` reads back (`POLICY_FIELDS`, dream/promote.ts). A key the
3102
+ * resolver never looks at could not change behaviour and does not belong in
3103
+ * a version row.
3104
+ */
3105
+ function paramsOf(policy, incumbent) {
3106
+ const point = liftPolicy(policy, incumbent);
3107
+ return {
3108
+ limit: point.limit,
3109
+ threshold: point.threshold,
3110
+ hopEntity: point.hopEntity,
3111
+ hopEdge: point.hopEdge,
3112
+ w: { ...point.w },
3113
+ };
3114
+ }
3115
+ /** A stored `params` blob back to a policy point, or null if it cannot be read. */
3116
+ function policyFromParams(params, incumbent) {
3117
+ const read = (source, key) => {
3118
+ const value = source?.[key];
3119
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
3120
+ };
3121
+ const weights = params.w;
3122
+ if (!weights || typeof weights !== 'object' || Array.isArray(weights))
3123
+ return null;
3124
+ const w = weights;
3125
+ const limit = read(params, 'limit');
3126
+ const threshold = read(params, 'threshold');
3127
+ const hopEntity = read(params, 'hopEntity');
3128
+ const hopEdge = read(params, 'hopEdge');
3129
+ const relevance = read(w, 'relevance');
3130
+ const importance = read(w, 'importance');
3131
+ const recency = read(w, 'recency');
3132
+ const usage = read(w, 'usage');
3133
+ if (limit === null || threshold === null || hopEntity === null || hopEdge === null ||
3134
+ relevance === null || importance === null || recency === null || usage === null) {
3135
+ return null;
3136
+ }
3137
+ return {
3138
+ limit: Math.round(limit),
3139
+ threshold,
3140
+ w: { relevance, importance, recency, usage },
3141
+ hopEntity,
3142
+ hopEdge,
3143
+ kinds: incumbent.kinds,
3144
+ minImportance: incumbent.minImportance,
3145
+ origin: DREAM_ORIGIN,
3146
+ };
3147
+ }
3148
+ /**
3149
+ * A wall-clock span in milliseconds, clamped for a config that bypassed the
3150
+ * patch schema (E21), like `clampDays` above. An hour is the ceiling: past
3151
+ * that the night is no longer a night.
3152
+ */
3153
+ function clampMs(value) {
3154
+ const ms = Number.isFinite(value) ? Math.round(value) : 0;
3155
+ return Math.min(3_600_000, Math.max(0, ms));
3156
+ }
3157
+ /** A count of things, clamped, and never below one: zero would mean "always". */
3158
+ function clampCount(value) {
3159
+ const count = Number.isFinite(value) ? Math.round(value) : 0;
3160
+ return Math.max(1, Math.min(1_000_000, count));
3161
+ }
3162
+ /** A delta with its sign, the way the evidence digest prints one. */
3163
+ function signedNumber(value) {
3164
+ if (!Number.isFinite(value))
3165
+ return 'an unreadable amount';
3166
+ return (value >= 0 ? '+' : '') + value.toFixed(4);
3167
+ }
3168
+ function zeroMeans() {
3169
+ return { relevance: 0, importance: 0, recency: 0, usage: 0, tagHit: 0 };
3170
+ }
3171
+ function addMeans(target, source) {
3172
+ target.relevance += source.relevance;
3173
+ target.importance += source.importance;
3174
+ target.recency += source.recency;
3175
+ target.usage += source.usage;
3176
+ target.tagHit += source.tagHit;
3177
+ }
3178
+ function divideMeans(target, count) {
3179
+ if (count <= 0)
3180
+ return target;
3181
+ return {
3182
+ relevance: target.relevance / count,
3183
+ importance: target.importance / count,
3184
+ recency: target.recency / count,
3185
+ usage: target.usage / count,
3186
+ tagHit: target.tagHit / count,
3187
+ };
3188
+ }
3189
+ /**
3190
+ * How close a correction's wording has to be to a skill before it counts as
3191
+ * being about that skill. Low on purpose: a correction and the procedure it
3192
+ * bears on rarely share many words, and the cost of a false match is one
3193
+ * reading that concludes "leave it alone", while the cost of a miss is a skill
3194
+ * that goes on being wrong.
3195
+ */
3196
+ const CORRECTION_MATCH = 0.12;
3197
+ /** Which suspect gets the night's attention first. */
3198
+ function weigh(entry) {
3199
+ // Being told outright beats a failed run, which beats shifted ground.
3200
+ return entry.corrections.length * 4 + entry.failures.length * 2 + entry.changed.length;
3201
+ }
3202
+ /** A task or an error trimmed to the part that still says something. */
3203
+ function clipText(text, max) {
3204
+ const trimmed = text.trim().replace(/\s+/g, ' ');
3205
+ return trimmed.length <= max ? trimmed : trimmed.slice(0, max) + ' [...]';
3206
+ }
888
3207
  //# sourceMappingURL=sleep.js.map