rookery-agent 0.3.1 → 0.4.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 (740) hide show
  1. package/README.md +3 -3
  2. package/docs/updates.md +12 -0
  3. package/package.json +1 -1
  4. package/packages/cli/dist/commands/chat.d.ts.map +1 -1
  5. package/packages/cli/dist/commands/chat.js +37 -74
  6. package/packages/cli/dist/commands/chat.js.map +1 -1
  7. package/packages/cli/dist/commands/config.js +4 -4
  8. package/packages/cli/dist/commands/config.js.map +1 -1
  9. package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
  10. package/packages/cli/dist/commands/doctor.js +113 -91
  11. package/packages/cli/dist/commands/doctor.js.map +1 -1
  12. package/packages/cli/dist/commands/memory.d.ts.map +1 -1
  13. package/packages/cli/dist/commands/memory.js +28 -31
  14. package/packages/cli/dist/commands/memory.js.map +1 -1
  15. package/packages/cli/dist/commands/org.d.ts.map +1 -1
  16. package/packages/cli/dist/commands/org.js +36 -103
  17. package/packages/cli/dist/commands/org.js.map +1 -1
  18. package/packages/cli/dist/commands/serve.d.ts.map +1 -1
  19. package/packages/cli/dist/commands/serve.js +8 -6
  20. package/packages/cli/dist/commands/serve.js.map +1 -1
  21. package/packages/cli/dist/commands/sessions.d.ts.map +1 -1
  22. package/packages/cli/dist/commands/sessions.js +18 -17
  23. package/packages/cli/dist/commands/sessions.js.map +1 -1
  24. package/packages/cli/dist/commands/shared.d.ts +26 -5
  25. package/packages/cli/dist/commands/shared.d.ts.map +1 -1
  26. package/packages/cli/dist/commands/shared.js +85 -63
  27. package/packages/cli/dist/commands/shared.js.map +1 -1
  28. package/packages/cli/dist/commands/slash.d.ts +51 -0
  29. package/packages/cli/dist/commands/slash.d.ts.map +1 -0
  30. package/packages/cli/dist/commands/slash.js +110 -0
  31. package/packages/cli/dist/commands/slash.js.map +1 -0
  32. package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
  33. package/packages/cli/dist/commands/tasks.js +74 -115
  34. package/packages/cli/dist/commands/tasks.js.map +1 -1
  35. package/packages/cli/dist/commands/tools.d.ts.map +1 -1
  36. package/packages/cli/dist/commands/tools.js +51 -34
  37. package/packages/cli/dist/commands/tools.js.map +1 -1
  38. package/packages/cli/dist/index.js +42 -52
  39. package/packages/cli/dist/index.js.map +1 -1
  40. package/packages/cli/dist/repl.d.ts +1 -25
  41. package/packages/cli/dist/repl.d.ts.map +1 -1
  42. package/packages/cli/dist/repl.js +165 -726
  43. package/packages/cli/dist/repl.js.map +1 -1
  44. package/packages/cli/dist/replInput.d.ts +33 -0
  45. package/packages/cli/dist/replInput.d.ts.map +1 -0
  46. package/packages/cli/dist/replInput.js +97 -0
  47. package/packages/cli/dist/replInput.js.map +1 -0
  48. package/packages/cli/dist/replOutput.d.ts +11 -0
  49. package/packages/cli/dist/replOutput.d.ts.map +1 -0
  50. package/packages/cli/dist/replOutput.js +22 -0
  51. package/packages/cli/dist/replOutput.js.map +1 -0
  52. package/packages/cli/dist/replQuestions.d.ts +32 -0
  53. package/packages/cli/dist/replQuestions.d.ts.map +1 -0
  54. package/packages/cli/dist/replQuestions.js +122 -0
  55. package/packages/cli/dist/replQuestions.js.map +1 -0
  56. package/packages/cli/dist/replSlash.d.ts +24 -0
  57. package/packages/cli/dist/replSlash.d.ts.map +1 -0
  58. package/packages/cli/dist/replSlash.js +311 -0
  59. package/packages/cli/dist/replSlash.js.map +1 -0
  60. package/packages/cli/dist/replState.d.ts +56 -0
  61. package/packages/cli/dist/replState.d.ts.map +1 -0
  62. package/packages/cli/dist/replState.js +89 -0
  63. package/packages/cli/dist/replState.js.map +1 -0
  64. package/packages/cli/dist/tui/App.d.ts +7 -24
  65. package/packages/cli/dist/tui/App.d.ts.map +1 -1
  66. package/packages/cli/dist/tui/App.js +139 -513
  67. package/packages/cli/dist/tui/App.js.map +1 -1
  68. package/packages/cli/dist/tui/LiveRegion.d.ts +16 -0
  69. package/packages/cli/dist/tui/LiveRegion.d.ts.map +1 -0
  70. package/packages/cli/dist/tui/LiveRegion.js +37 -0
  71. package/packages/cli/dist/tui/LiveRegion.js.map +1 -0
  72. package/packages/cli/dist/tui/boot.d.ts +34 -0
  73. package/packages/cli/dist/tui/boot.d.ts.map +1 -0
  74. package/packages/cli/dist/tui/boot.js +133 -0
  75. package/packages/cli/dist/tui/boot.js.map +1 -0
  76. package/packages/cli/dist/tui/commands.d.ts +3 -4
  77. package/packages/cli/dist/tui/commands.d.ts.map +1 -1
  78. package/packages/cli/dist/tui/commands.js +339 -405
  79. package/packages/cli/dist/tui/commands.js.map +1 -1
  80. package/packages/cli/dist/tui/components/ActivityLine.d.ts +1 -1
  81. package/packages/cli/dist/tui/components/ActivityLine.d.ts.map +1 -1
  82. package/packages/cli/dist/tui/components/ActivityLine.js +2 -2
  83. package/packages/cli/dist/tui/components/ActivityLine.js.map +1 -1
  84. package/packages/cli/dist/tui/components/AssignmentsView.d.ts.map +1 -1
  85. package/packages/cli/dist/tui/components/AssignmentsView.js +34 -20
  86. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
  87. package/packages/cli/dist/tui/components/Logo.d.ts +3 -19
  88. package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -1
  89. package/packages/cli/dist/tui/components/Logo.js +13 -13
  90. package/packages/cli/dist/tui/components/Logo.js.map +1 -1
  91. package/packages/cli/dist/tui/components/Markdown.d.ts.map +1 -1
  92. package/packages/cli/dist/tui/components/Markdown.js +201 -146
  93. package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
  94. package/packages/cli/dist/tui/components/QuestionView.d.ts +0 -2
  95. package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -1
  96. package/packages/cli/dist/tui/components/QuestionView.js +21 -12
  97. package/packages/cli/dist/tui/components/QuestionView.js.map +1 -1
  98. package/packages/cli/dist/tui/components/Scrollback.d.ts.map +1 -1
  99. package/packages/cli/dist/tui/components/Scrollback.js +6 -3
  100. package/packages/cli/dist/tui/components/Scrollback.js.map +1 -1
  101. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
  102. package/packages/cli/dist/tui/components/SlashPalette.js +14 -9
  103. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
  104. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
  105. package/packages/cli/dist/tui/components/StatusLine.js +45 -22
  106. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
  107. package/packages/cli/dist/tui/components/ToolGroup.d.ts.map +1 -1
  108. package/packages/cli/dist/tui/components/ToolGroup.js +12 -7
  109. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
  110. package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -1
  111. package/packages/cli/dist/tui/components/WatchView.js +28 -17
  112. package/packages/cli/dist/tui/components/WatchView.js.map +1 -1
  113. package/packages/cli/dist/tui/highlight.d.ts +0 -2
  114. package/packages/cli/dist/tui/highlight.d.ts.map +1 -1
  115. package/packages/cli/dist/tui/highlight.js +8 -6
  116. package/packages/cli/dist/tui/highlight.js.map +1 -1
  117. package/packages/cli/dist/tui/history.d.ts +30 -4
  118. package/packages/cli/dist/tui/history.d.ts.map +1 -1
  119. package/packages/cli/dist/tui/history.js +100 -75
  120. package/packages/cli/dist/tui/history.js.map +1 -1
  121. package/packages/cli/dist/tui/hooks/coalescer.d.ts +18 -0
  122. package/packages/cli/dist/tui/hooks/coalescer.d.ts.map +1 -0
  123. package/packages/cli/dist/tui/hooks/coalescer.js +36 -0
  124. package/packages/cli/dist/tui/hooks/coalescer.js.map +1 -0
  125. package/packages/cli/dist/tui/hooks/useColumns.d.ts +2 -7
  126. package/packages/cli/dist/tui/hooks/useColumns.d.ts.map +1 -1
  127. package/packages/cli/dist/tui/hooks/useColumns.js +6 -11
  128. package/packages/cli/dist/tui/hooks/useColumns.js.map +1 -1
  129. package/packages/cli/dist/tui/hooks/useHistory.d.ts +7 -4
  130. package/packages/cli/dist/tui/hooks/useHistory.d.ts.map +1 -1
  131. package/packages/cli/dist/tui/hooks/useHistory.js +21 -18
  132. package/packages/cli/dist/tui/hooks/useHistory.js.map +1 -1
  133. package/packages/cli/dist/tui/hooks/usePrompt.d.ts +27 -0
  134. package/packages/cli/dist/tui/hooks/usePrompt.d.ts.map +1 -0
  135. package/packages/cli/dist/tui/hooks/usePrompt.js +169 -0
  136. package/packages/cli/dist/tui/hooks/usePrompt.js.map +1 -0
  137. package/packages/cli/dist/tui/hooks/useQuestion.d.ts +23 -0
  138. package/packages/cli/dist/tui/hooks/useQuestion.d.ts.map +1 -0
  139. package/packages/cli/dist/tui/hooks/useQuestion.js +43 -0
  140. package/packages/cli/dist/tui/hooks/useQuestion.js.map +1 -0
  141. package/packages/cli/dist/tui/hooks/useScrollback.d.ts +18 -0
  142. package/packages/cli/dist/tui/hooks/useScrollback.d.ts.map +1 -0
  143. package/packages/cli/dist/tui/hooks/useScrollback.js +29 -0
  144. package/packages/cli/dist/tui/hooks/useScrollback.js.map +1 -0
  145. package/packages/cli/dist/tui/hooks/useSession.d.ts +25 -0
  146. package/packages/cli/dist/tui/hooks/useSession.d.ts.map +1 -0
  147. package/packages/cli/dist/tui/hooks/useSession.js +36 -0
  148. package/packages/cli/dist/tui/hooks/useSession.js.map +1 -0
  149. package/packages/cli/dist/tui/hooks/useSlash.d.ts +0 -2
  150. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
  151. package/packages/cli/dist/tui/hooks/useSlash.js +0 -1
  152. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
  153. package/packages/cli/dist/tui/hooks/useSpeech.d.ts +19 -0
  154. package/packages/cli/dist/tui/hooks/useSpeech.d.ts.map +1 -0
  155. package/packages/cli/dist/tui/hooks/useSpeech.js +33 -0
  156. package/packages/cli/dist/tui/hooks/useSpeech.js.map +1 -0
  157. package/packages/cli/dist/tui/hooks/useTicker.d.ts +13 -0
  158. package/packages/cli/dist/tui/hooks/useTicker.d.ts.map +1 -0
  159. package/packages/cli/dist/tui/hooks/useTicker.js +24 -0
  160. package/packages/cli/dist/tui/hooks/useTicker.js.map +1 -0
  161. package/packages/cli/dist/tui/hooks/useTurn.d.ts +4 -4
  162. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
  163. package/packages/cli/dist/tui/hooks/useTurn.js +167 -289
  164. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
  165. package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -1
  166. package/packages/cli/dist/tui/hooks/useWatch.js +15 -48
  167. package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -1
  168. package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -1
  169. package/packages/cli/dist/tui/inkTheme.js +9 -11
  170. package/packages/cli/dist/tui/inkTheme.js.map +1 -1
  171. package/packages/cli/dist/tui/theme.d.ts +7 -13
  172. package/packages/cli/dist/tui/theme.d.ts.map +1 -1
  173. package/packages/cli/dist/tui/theme.js +18 -15
  174. package/packages/cli/dist/tui/theme.js.map +1 -1
  175. package/packages/cli/dist/tui/types.d.ts +10 -23
  176. package/packages/cli/dist/tui/types.d.ts.map +1 -1
  177. package/packages/cli/dist/tui/types.js +13 -31
  178. package/packages/cli/dist/tui/types.js.map +1 -1
  179. package/packages/cli/dist/ui/modelNames.d.ts.map +1 -1
  180. package/packages/cli/dist/ui/modelNames.js +45 -37
  181. package/packages/cli/dist/ui/modelNames.js.map +1 -1
  182. package/packages/cli/dist/ui/render.d.ts +32 -14
  183. package/packages/cli/dist/ui/render.d.ts.map +1 -1
  184. package/packages/cli/dist/ui/render.js +155 -98
  185. package/packages/cli/dist/ui/render.js.map +1 -1
  186. package/packages/cli/dist/ui/speech.d.ts +4 -7
  187. package/packages/cli/dist/ui/speech.d.ts.map +1 -1
  188. package/packages/cli/dist/ui/speech.js +37 -51
  189. package/packages/cli/dist/ui/speech.js.map +1 -1
  190. package/packages/cli/dist/ui/spinner.d.ts +1 -4
  191. package/packages/cli/dist/ui/spinner.d.ts.map +1 -1
  192. package/packages/cli/dist/ui/spinner.js +1 -12
  193. package/packages/cli/dist/ui/spinner.js.map +1 -1
  194. package/packages/cli/package.json +1 -1
  195. package/packages/core/dist/agents/persona.d.ts.map +1 -1
  196. package/packages/core/dist/agents/persona.js +27 -11
  197. package/packages/core/dist/agents/persona.js.map +1 -1
  198. package/packages/core/dist/assistant/board-watch.d.ts +72 -0
  199. package/packages/core/dist/assistant/board-watch.d.ts.map +1 -0
  200. package/packages/core/dist/assistant/board-watch.js +224 -0
  201. package/packages/core/dist/assistant/board-watch.js.map +1 -0
  202. package/packages/core/dist/assistant/chat-turn.d.ts +14 -0
  203. package/packages/core/dist/assistant/chat-turn.d.ts.map +1 -0
  204. package/packages/core/dist/assistant/chat-turn.js +159 -0
  205. package/packages/core/dist/assistant/chat-turn.js.map +1 -0
  206. package/packages/core/dist/assistant/dream-recorder.d.ts +74 -0
  207. package/packages/core/dist/assistant/dream-recorder.d.ts.map +1 -0
  208. package/packages/core/dist/assistant/dream-recorder.js +282 -0
  209. package/packages/core/dist/assistant/dream-recorder.js.map +1 -0
  210. package/packages/core/dist/assistant/headless-turn.d.ts +17 -0
  211. package/packages/core/dist/assistant/headless-turn.d.ts.map +1 -0
  212. package/packages/core/dist/assistant/headless-turn.js +330 -0
  213. package/packages/core/dist/assistant/headless-turn.js.map +1 -0
  214. package/packages/core/dist/assistant/journalled-turn.d.ts +39 -0
  215. package/packages/core/dist/assistant/journalled-turn.d.ts.map +1 -0
  216. package/packages/core/dist/assistant/journalled-turn.js +75 -0
  217. package/packages/core/dist/assistant/journalled-turn.js.map +1 -0
  218. package/packages/core/dist/assistant/memory-learning.d.ts +27 -0
  219. package/packages/core/dist/assistant/memory-learning.d.ts.map +1 -0
  220. package/packages/core/dist/assistant/memory-learning.js +82 -0
  221. package/packages/core/dist/assistant/memory-learning.js.map +1 -0
  222. package/packages/core/dist/assistant/promotion-notice.d.ts +14 -0
  223. package/packages/core/dist/assistant/promotion-notice.d.ts.map +1 -0
  224. package/packages/core/dist/assistant/promotion-notice.js +33 -0
  225. package/packages/core/dist/assistant/promotion-notice.js.map +1 -0
  226. package/packages/core/dist/assistant/scheduled-runs.d.ts +30 -0
  227. package/packages/core/dist/assistant/scheduled-runs.d.ts.map +1 -0
  228. package/packages/core/dist/assistant/scheduled-runs.js +184 -0
  229. package/packages/core/dist/assistant/scheduled-runs.js.map +1 -0
  230. package/packages/core/dist/assistant/sessions.d.ts +44 -0
  231. package/packages/core/dist/assistant/sessions.d.ts.map +1 -0
  232. package/packages/core/dist/assistant/sessions.js +75 -0
  233. package/packages/core/dist/assistant/sessions.js.map +1 -0
  234. package/packages/core/dist/assistant/terminal-turn.d.ts +18 -0
  235. package/packages/core/dist/assistant/terminal-turn.d.ts.map +1 -0
  236. package/packages/core/dist/assistant/terminal-turn.js +228 -0
  237. package/packages/core/dist/assistant/terminal-turn.js.map +1 -0
  238. package/packages/core/dist/assistant/terminals.d.ts +91 -0
  239. package/packages/core/dist/assistant/terminals.d.ts.map +1 -0
  240. package/packages/core/dist/assistant/terminals.js +266 -0
  241. package/packages/core/dist/assistant/terminals.js.map +1 -0
  242. package/packages/core/dist/assistant/turn-support.d.ts +109 -0
  243. package/packages/core/dist/assistant/turn-support.d.ts.map +1 -0
  244. package/packages/core/dist/assistant/turn-support.js +80 -0
  245. package/packages/core/dist/assistant/turn-support.js.map +1 -0
  246. package/packages/core/dist/assistant/turn-transcript.d.ts +44 -0
  247. package/packages/core/dist/assistant/turn-transcript.d.ts.map +1 -0
  248. package/packages/core/dist/assistant/turn-transcript.js +82 -0
  249. package/packages/core/dist/assistant/turn-transcript.js.map +1 -0
  250. package/packages/core/dist/assistant/types.d.ts +120 -0
  251. package/packages/core/dist/assistant/types.d.ts.map +1 -0
  252. package/packages/core/dist/assistant/types.js +2 -0
  253. package/packages/core/dist/assistant/types.js.map +1 -0
  254. package/packages/core/dist/computer/accessibility.d.ts.map +1 -1
  255. package/packages/core/dist/computer/accessibility.js +40 -35
  256. package/packages/core/dist/computer/accessibility.js.map +1 -1
  257. package/packages/core/dist/computer/mcp-server.js +426 -364
  258. package/packages/core/dist/computer/mcp-server.js.map +1 -1
  259. package/packages/core/dist/computer/powershell.d.ts.map +1 -1
  260. package/packages/core/dist/computer/powershell.js +25 -16
  261. package/packages/core/dist/computer/powershell.js.map +1 -1
  262. package/packages/core/dist/computer/screen-text.d.ts.map +1 -1
  263. package/packages/core/dist/computer/screen-text.js +54 -34
  264. package/packages/core/dist/computer/screen-text.js.map +1 -1
  265. package/packages/core/dist/computer/sketch.d.ts.map +1 -1
  266. package/packages/core/dist/computer/sketch.js +185 -128
  267. package/packages/core/dist/computer/sketch.js.map +1 -1
  268. package/packages/core/dist/computer/tools.d.ts +2 -0
  269. package/packages/core/dist/computer/tools.d.ts.map +1 -1
  270. package/packages/core/dist/computer/tools.js +31 -27
  271. package/packages/core/dist/computer/tools.js.map +1 -1
  272. package/packages/core/dist/computer/validation.d.ts +16 -16
  273. package/packages/core/dist/computer/validation.d.ts.map +1 -1
  274. package/packages/core/dist/computer/validation.js +28 -20
  275. package/packages/core/dist/computer/validation.js.map +1 -1
  276. package/packages/core/dist/config.d.ts +10 -1
  277. package/packages/core/dist/config.d.ts.map +1 -1
  278. package/packages/core/dist/config.js +64 -23
  279. package/packages/core/dist/config.js.map +1 -1
  280. package/packages/core/dist/cron/parse.d.ts.map +1 -1
  281. package/packages/core/dist/cron/parse.js +90 -77
  282. package/packages/core/dist/cron/parse.js.map +1 -1
  283. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  284. package/packages/core/dist/cron/scheduler.js +99 -65
  285. package/packages/core/dist/cron/scheduler.js.map +1 -1
  286. package/packages/core/dist/cron/script.d.ts.map +1 -1
  287. package/packages/core/dist/cron/script.js +72 -42
  288. package/packages/core/dist/cron/script.js.map +1 -1
  289. package/packages/core/dist/external/claude-code.d.ts.map +1 -1
  290. package/packages/core/dist/external/claude-code.js +41 -28
  291. package/packages/core/dist/external/claude-code.js.map +1 -1
  292. package/packages/core/dist/external/discovery.d.ts.map +1 -1
  293. package/packages/core/dist/external/discovery.js +14 -11
  294. package/packages/core/dist/external/discovery.js.map +1 -1
  295. package/packages/core/dist/external/shared.d.ts.map +1 -1
  296. package/packages/core/dist/external/shared.js +55 -74
  297. package/packages/core/dist/external/shared.js.map +1 -1
  298. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  299. package/packages/core/dist/gateway/policy.js +5 -2
  300. package/packages/core/dist/gateway/policy.js.map +1 -1
  301. package/packages/core/dist/logger.d.ts.map +1 -1
  302. package/packages/core/dist/logger.js +11 -11
  303. package/packages/core/dist/logger.js.map +1 -1
  304. package/packages/core/dist/memory/db.d.ts.map +1 -1
  305. package/packages/core/dist/memory/db.js +175 -226
  306. package/packages/core/dist/memory/db.js.map +1 -1
  307. package/packages/core/dist/memory/dream/admission.d.ts +5 -0
  308. package/packages/core/dist/memory/dream/admission.d.ts.map +1 -1
  309. package/packages/core/dist/memory/dream/admission.js +8 -14
  310. package/packages/core/dist/memory/dream/admission.js.map +1 -1
  311. package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -1
  312. package/packages/core/dist/memory/dream/candidate.js +119 -92
  313. package/packages/core/dist/memory/dream/candidate.js.map +1 -1
  314. package/packages/core/dist/memory/dream/evaluate.d.ts +13 -4
  315. package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -1
  316. package/packages/core/dist/memory/dream/evaluate.js +264 -288
  317. package/packages/core/dist/memory/dream/evaluate.js.map +1 -1
  318. package/packages/core/dist/memory/dream/frame.d.ts +6 -0
  319. package/packages/core/dist/memory/dream/frame.d.ts.map +1 -1
  320. package/packages/core/dist/memory/dream/frame.js +137 -91
  321. package/packages/core/dist/memory/dream/frame.js.map +1 -1
  322. package/packages/core/dist/memory/dream/label.d.ts.map +1 -1
  323. package/packages/core/dist/memory/dream/label.js +6 -9
  324. package/packages/core/dist/memory/dream/label.js.map +1 -1
  325. package/packages/core/dist/memory/dream/measure.d.ts +4 -0
  326. package/packages/core/dist/memory/dream/measure.d.ts.map +1 -1
  327. package/packages/core/dist/memory/dream/measure.js +13 -58
  328. package/packages/core/dist/memory/dream/measure.js.map +1 -1
  329. package/packages/core/dist/memory/dream/policy.d.ts.map +1 -1
  330. package/packages/core/dist/memory/dream/policy.js +4 -2
  331. package/packages/core/dist/memory/dream/policy.js.map +1 -1
  332. package/packages/core/dist/memory/dream/probe.d.ts +31 -4
  333. package/packages/core/dist/memory/dream/probe.d.ts.map +1 -1
  334. package/packages/core/dist/memory/dream/probe.js +290 -289
  335. package/packages/core/dist/memory/dream/probe.js.map +1 -1
  336. package/packages/core/dist/memory/dream/promote.d.ts.map +1 -1
  337. package/packages/core/dist/memory/dream/promote.js +10 -11
  338. package/packages/core/dist/memory/dream/promote.js.map +1 -1
  339. package/packages/core/dist/memory/dream/score.d.ts +9 -0
  340. package/packages/core/dist/memory/dream/score.d.ts.map +1 -1
  341. package/packages/core/dist/memory/dream/score.js +6 -7
  342. package/packages/core/dist/memory/dream/score.js.map +1 -1
  343. package/packages/core/dist/memory/dream/slots.d.ts.map +1 -1
  344. package/packages/core/dist/memory/dream/slots.js +0 -0
  345. package/packages/core/dist/memory/dream/slots.js.map +1 -1
  346. package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -1
  347. package/packages/core/dist/memory/dream/trajectory.js +76 -53
  348. package/packages/core/dist/memory/dream/trajectory.js.map +1 -1
  349. package/packages/core/dist/memory/dream/util.d.ts +44 -0
  350. package/packages/core/dist/memory/dream/util.d.ts.map +1 -0
  351. package/packages/core/dist/memory/dream/util.js +83 -0
  352. package/packages/core/dist/memory/dream/util.js.map +1 -0
  353. package/packages/core/dist/memory/extractor.d.ts.map +1 -1
  354. package/packages/core/dist/memory/extractor.js +67 -46
  355. package/packages/core/dist/memory/extractor.js.map +1 -1
  356. package/packages/core/dist/memory/gate.d.ts.map +1 -1
  357. package/packages/core/dist/memory/gate.js +55 -44
  358. package/packages/core/dist/memory/gate.js.map +1 -1
  359. package/packages/core/dist/memory/recall.d.ts +1 -1
  360. package/packages/core/dist/memory/recall.d.ts.map +1 -1
  361. package/packages/core/dist/memory/recall.js +42 -39
  362. package/packages/core/dist/memory/recall.js.map +1 -1
  363. package/packages/core/dist/memory/sleep-dream.d.ts +210 -0
  364. package/packages/core/dist/memory/sleep-dream.d.ts.map +1 -0
  365. package/packages/core/dist/memory/sleep-dream.js +1109 -0
  366. package/packages/core/dist/memory/sleep-dream.js.map +1 -0
  367. package/packages/core/dist/memory/sleep-frames.d.ts +40 -0
  368. package/packages/core/dist/memory/sleep-frames.d.ts.map +1 -0
  369. package/packages/core/dist/memory/sleep-frames.js +127 -0
  370. package/packages/core/dist/memory/sleep-frames.js.map +1 -0
  371. package/packages/core/dist/memory/sleep-limits.d.ts +18 -0
  372. package/packages/core/dist/memory/sleep-limits.d.ts.map +1 -0
  373. package/packages/core/dist/memory/sleep-limits.js +34 -0
  374. package/packages/core/dist/memory/sleep-limits.js.map +1 -0
  375. package/packages/core/dist/memory/sleep-model.d.ts +36 -0
  376. package/packages/core/dist/memory/sleep-model.d.ts.map +1 -0
  377. package/packages/core/dist/memory/sleep-model.js +80 -0
  378. package/packages/core/dist/memory/sleep-model.js.map +1 -0
  379. package/packages/core/dist/memory/sleep-policy.d.ts +19 -0
  380. package/packages/core/dist/memory/sleep-policy.d.ts.map +1 -0
  381. package/packages/core/dist/memory/sleep-policy.js +79 -0
  382. package/packages/core/dist/memory/sleep-policy.js.map +1 -0
  383. package/packages/core/dist/memory/sleep-prompts.d.ts +15 -0
  384. package/packages/core/dist/memory/sleep-prompts.d.ts.map +1 -0
  385. package/packages/core/dist/memory/sleep-prompts.js +212 -0
  386. package/packages/core/dist/memory/sleep-prompts.js.map +1 -0
  387. package/packages/core/dist/memory/sleep-report.d.ts +63 -0
  388. package/packages/core/dist/memory/sleep-report.d.ts.map +1 -0
  389. package/packages/core/dist/memory/sleep-report.js +97 -0
  390. package/packages/core/dist/memory/sleep-report.js.map +1 -0
  391. package/packages/core/dist/memory/sleep-verdicts.d.ts +77 -0
  392. package/packages/core/dist/memory/sleep-verdicts.d.ts.map +1 -0
  393. package/packages/core/dist/memory/sleep-verdicts.js +198 -0
  394. package/packages/core/dist/memory/sleep-verdicts.js.map +1 -0
  395. package/packages/core/dist/memory/sleep.d.ts +6 -61
  396. package/packages/core/dist/memory/sleep.d.ts.map +1 -1
  397. package/packages/core/dist/memory/sleep.js +1099 -2458
  398. package/packages/core/dist/memory/sleep.js.map +1 -1
  399. package/packages/core/dist/memory/store-rows.d.ts +43 -0
  400. package/packages/core/dist/memory/store-rows.d.ts.map +1 -0
  401. package/packages/core/dist/memory/store-rows.js +330 -0
  402. package/packages/core/dist/memory/store-rows.js.map +1 -0
  403. package/packages/core/dist/memory/store.d.ts +34 -20
  404. package/packages/core/dist/memory/store.d.ts.map +1 -1
  405. package/packages/core/dist/memory/store.js +634 -861
  406. package/packages/core/dist/memory/store.js.map +1 -1
  407. package/packages/core/dist/migration-cron.d.ts +2 -1
  408. package/packages/core/dist/migration-cron.d.ts.map +1 -1
  409. package/packages/core/dist/migration-cron.js +197 -154
  410. package/packages/core/dist/migration-cron.js.map +1 -1
  411. package/packages/core/dist/migration-scripts.d.ts +11 -3
  412. package/packages/core/dist/migration-scripts.d.ts.map +1 -1
  413. package/packages/core/dist/migration-scripts.js +81 -61
  414. package/packages/core/dist/migration-scripts.js.map +1 -1
  415. package/packages/core/dist/migration-shared.d.ts +9 -0
  416. package/packages/core/dist/migration-shared.d.ts.map +1 -0
  417. package/packages/core/dist/migration-shared.js +16 -0
  418. package/packages/core/dist/migration-shared.js.map +1 -0
  419. package/packages/core/dist/migration.d.ts.map +1 -1
  420. package/packages/core/dist/migration.js +150 -111
  421. package/packages/core/dist/migration.js.map +1 -1
  422. package/packages/core/dist/org/assignment-log.d.ts +28 -0
  423. package/packages/core/dist/org/assignment-log.d.ts.map +1 -0
  424. package/packages/core/dist/org/assignment-log.js +86 -0
  425. package/packages/core/dist/org/assignment-log.js.map +1 -0
  426. package/packages/core/dist/org/bridge.d.ts.map +1 -1
  427. package/packages/core/dist/org/bridge.js +32 -30
  428. package/packages/core/dist/org/bridge.js.map +1 -1
  429. package/packages/core/dist/org/controller.d.ts +18 -21
  430. package/packages/core/dist/org/controller.d.ts.map +1 -1
  431. package/packages/core/dist/org/controller.js +2042 -1848
  432. package/packages/core/dist/org/controller.js.map +1 -1
  433. package/packages/core/dist/org/json-reply.d.ts +6 -0
  434. package/packages/core/dist/org/json-reply.d.ts.map +1 -0
  435. package/packages/core/dist/org/json-reply.js +23 -0
  436. package/packages/core/dist/org/json-reply.js.map +1 -0
  437. package/packages/core/dist/org/mcp-bridge.js +34 -26
  438. package/packages/core/dist/org/mcp-bridge.js.map +1 -1
  439. package/packages/core/dist/org/planner.d.ts.map +1 -1
  440. package/packages/core/dist/org/planner.js +38 -42
  441. package/packages/core/dist/org/planner.js.map +1 -1
  442. package/packages/core/dist/org/project-mcp.d.ts.map +1 -1
  443. package/packages/core/dist/org/project-mcp.js +2 -5
  444. package/packages/core/dist/org/project-mcp.js.map +1 -1
  445. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  446. package/packages/core/dist/org/prompts.js +176 -156
  447. package/packages/core/dist/org/prompts.js.map +1 -1
  448. package/packages/core/dist/org/questions.d.ts.map +1 -1
  449. package/packages/core/dist/org/questions.js +19 -14
  450. package/packages/core/dist/org/questions.js.map +1 -1
  451. package/packages/core/dist/org/review.d.ts.map +1 -1
  452. package/packages/core/dist/org/review.js +27 -43
  453. package/packages/core/dist/org/review.js.map +1 -1
  454. package/packages/core/dist/org/store.d.ts +19 -32
  455. package/packages/core/dist/org/store.d.ts.map +1 -1
  456. package/packages/core/dist/org/store.js +250 -206
  457. package/packages/core/dist/org/store.js.map +1 -1
  458. package/packages/core/dist/org/tool-args.d.ts +54 -0
  459. package/packages/core/dist/org/tool-args.d.ts.map +1 -0
  460. package/packages/core/dist/org/tool-args.js +104 -0
  461. package/packages/core/dist/org/tool-args.js.map +1 -0
  462. package/packages/core/dist/org/tools.d.ts.map +1 -1
  463. package/packages/core/dist/org/tools.js +238 -443
  464. package/packages/core/dist/org/tools.js.map +1 -1
  465. package/packages/core/dist/profile.d.ts.map +1 -1
  466. package/packages/core/dist/profile.js +114 -57
  467. package/packages/core/dist/profile.js.map +1 -1
  468. package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
  469. package/packages/core/dist/providers/catalogue.js +89 -60
  470. package/packages/core/dist/providers/catalogue.js.map +1 -1
  471. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  472. package/packages/core/dist/providers/claude-code.js +418 -357
  473. package/packages/core/dist/providers/claude-code.js.map +1 -1
  474. package/packages/core/dist/providers/claude-tui.d.ts +13 -9
  475. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
  476. package/packages/core/dist/providers/claude-tui.js +568 -396
  477. package/packages/core/dist/providers/claude-tui.js.map +1 -1
  478. package/packages/core/dist/providers/codex-auth.d.ts +3 -0
  479. package/packages/core/dist/providers/codex-auth.d.ts.map +1 -1
  480. package/packages/core/dist/providers/codex-auth.js +9 -7
  481. package/packages/core/dist/providers/codex-auth.js.map +1 -1
  482. package/packages/core/dist/providers/codex-bridge.d.ts +24 -7
  483. package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -1
  484. package/packages/core/dist/providers/codex-bridge.js +128 -168
  485. package/packages/core/dist/providers/codex-bridge.js.map +1 -1
  486. package/packages/core/dist/providers/codex-translate.d.ts.map +1 -1
  487. package/packages/core/dist/providers/codex-translate.js +195 -197
  488. package/packages/core/dist/providers/codex-translate.js.map +1 -1
  489. package/packages/core/dist/providers/loopback-server.d.ts +33 -0
  490. package/packages/core/dist/providers/loopback-server.d.ts.map +1 -0
  491. package/packages/core/dist/providers/loopback-server.js +104 -0
  492. package/packages/core/dist/providers/loopback-server.js.map +1 -0
  493. package/packages/core/dist/providers/model-gateway.d.ts +2 -4
  494. package/packages/core/dist/providers/model-gateway.d.ts.map +1 -1
  495. package/packages/core/dist/providers/model-gateway.js +39 -75
  496. package/packages/core/dist/providers/model-gateway.js.map +1 -1
  497. package/packages/core/dist/providers/process.d.ts.map +1 -1
  498. package/packages/core/dist/providers/process.js +32 -23
  499. package/packages/core/dist/providers/process.js.map +1 -1
  500. package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -1
  501. package/packages/core/dist/providers/provider-catalog.js +21 -23
  502. package/packages/core/dist/providers/provider-catalog.js.map +1 -1
  503. package/packages/core/dist/providers/quota.d.ts.map +1 -1
  504. package/packages/core/dist/providers/quota.js +37 -37
  505. package/packages/core/dist/providers/quota.js.map +1 -1
  506. package/packages/core/dist/providers/registry.d.ts.map +1 -1
  507. package/packages/core/dist/providers/registry.js +3 -1
  508. package/packages/core/dist/providers/registry.js.map +1 -1
  509. package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -1
  510. package/packages/core/dist/providers/user-settings-guard.js +7 -2
  511. package/packages/core/dist/providers/user-settings-guard.js.map +1 -1
  512. package/packages/core/dist/runtime.d.ts +45 -158
  513. package/packages/core/dist/runtime.d.ts.map +1 -1
  514. package/packages/core/dist/runtime.js +184 -1701
  515. package/packages/core/dist/runtime.js.map +1 -1
  516. package/packages/core/dist/skills/import.d.ts.map +1 -1
  517. package/packages/core/dist/skills/import.js +52 -36
  518. package/packages/core/dist/skills/import.js.map +1 -1
  519. package/packages/core/dist/skills/shelf.d.ts +14 -0
  520. package/packages/core/dist/skills/shelf.d.ts.map +1 -1
  521. package/packages/core/dist/skills/shelf.js +2 -3
  522. package/packages/core/dist/skills/shelf.js.map +1 -1
  523. package/packages/core/dist/skills/store.d.ts +2 -0
  524. package/packages/core/dist/skills/store.d.ts.map +1 -1
  525. package/packages/core/dist/skills/store.js +17 -12
  526. package/packages/core/dist/skills/store.js.map +1 -1
  527. package/packages/core/dist/tools/catalog.d.ts.map +1 -1
  528. package/packages/core/dist/tools/catalog.js +6 -2
  529. package/packages/core/dist/tools/catalog.js.map +1 -1
  530. package/packages/core/dist/tools/hub.d.ts.map +1 -1
  531. package/packages/core/dist/tools/hub.js +97 -79
  532. package/packages/core/dist/tools/hub.js.map +1 -1
  533. package/packages/core/dist/turns/journal.d.ts.map +1 -1
  534. package/packages/core/dist/turns/journal.js +12 -18
  535. package/packages/core/dist/turns/journal.js.map +1 -1
  536. package/packages/core/dist/types.d.ts +12 -3
  537. package/packages/core/dist/types.d.ts.map +1 -1
  538. package/packages/core/dist/types.js.map +1 -1
  539. package/packages/core/dist/util/blocks.d.ts.map +1 -1
  540. package/packages/core/dist/util/blocks.js +14 -22
  541. package/packages/core/dist/util/blocks.js.map +1 -1
  542. package/packages/core/dist/util/queue.d.ts +0 -2
  543. package/packages/core/dist/util/queue.d.ts.map +1 -1
  544. package/packages/core/dist/util/queue.js +0 -6
  545. package/packages/core/dist/util/queue.js.map +1 -1
  546. package/packages/core/package.json +1 -1
  547. package/packages/server/dist/auth.d.ts +8 -0
  548. package/packages/server/dist/auth.d.ts.map +1 -1
  549. package/packages/server/dist/auth.js +8 -8
  550. package/packages/server/dist/auth.js.map +1 -1
  551. package/packages/server/dist/env.d.ts.map +1 -1
  552. package/packages/server/dist/env.js +18 -15
  553. package/packages/server/dist/env.js.map +1 -1
  554. package/packages/server/dist/errors.d.ts +3 -0
  555. package/packages/server/dist/errors.d.ts.map +1 -0
  556. package/packages/server/dist/errors.js +5 -0
  557. package/packages/server/dist/errors.js.map +1 -0
  558. package/packages/server/dist/gateways/attachments.d.ts.map +1 -1
  559. package/packages/server/dist/gateways/attachments.js +38 -21
  560. package/packages/server/dist/gateways/attachments.js.map +1 -1
  561. package/packages/server/dist/gateways/markdown.d.ts.map +1 -1
  562. package/packages/server/dist/gateways/markdown.js +30 -12
  563. package/packages/server/dist/gateways/markdown.js.map +1 -1
  564. package/packages/server/dist/gateways/push.d.ts +6 -6
  565. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  566. package/packages/server/dist/gateways/push.js +101 -74
  567. package/packages/server/dist/gateways/push.js.map +1 -1
  568. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
  569. package/packages/server/dist/gateways/telegram-api.js +61 -44
  570. package/packages/server/dist/gateways/telegram-api.js.map +1 -1
  571. package/packages/server/dist/gateways/telegram.d.ts +5 -0
  572. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  573. package/packages/server/dist/gateways/telegram.js +985 -753
  574. package/packages/server/dist/gateways/telegram.js.map +1 -1
  575. package/packages/server/dist/gateways/threads.d.ts.map +1 -1
  576. package/packages/server/dist/gateways/threads.js +144 -130
  577. package/packages/server/dist/gateways/threads.js.map +1 -1
  578. package/packages/server/dist/listeners/imap.d.ts.map +1 -1
  579. package/packages/server/dist/listeners/imap.js +0 -0
  580. package/packages/server/dist/listeners/imap.js.map +1 -1
  581. package/packages/server/dist/listeners/registry.d.ts.map +1 -1
  582. package/packages/server/dist/listeners/registry.js +15 -15
  583. package/packages/server/dist/listeners/registry.js.map +1 -1
  584. package/packages/server/dist/main.js +3 -2
  585. package/packages/server/dist/main.js.map +1 -1
  586. package/packages/server/dist/routes/chat.d.ts.map +1 -1
  587. package/packages/server/dist/routes/chat.js +5 -8
  588. package/packages/server/dist/routes/chat.js.map +1 -1
  589. package/packages/server/dist/routes/config.d.ts +6 -0
  590. package/packages/server/dist/routes/config.d.ts.map +1 -1
  591. package/packages/server/dist/routes/config.js +34 -31
  592. package/packages/server/dist/routes/config.js.map +1 -1
  593. package/packages/server/dist/routes/cron.d.ts.map +1 -1
  594. package/packages/server/dist/routes/cron.js +33 -23
  595. package/packages/server/dist/routes/cron.js.map +1 -1
  596. package/packages/server/dist/routes/dream.d.ts +1 -1
  597. package/packages/server/dist/routes/dream.d.ts.map +1 -1
  598. package/packages/server/dist/routes/dream.js +16 -34
  599. package/packages/server/dist/routes/dream.js.map +1 -1
  600. package/packages/server/dist/routes/gateways.d.ts.map +1 -1
  601. package/packages/server/dist/routes/gateways.js +8 -13
  602. package/packages/server/dist/routes/gateways.js.map +1 -1
  603. package/packages/server/dist/routes/memories.d.ts.map +1 -1
  604. package/packages/server/dist/routes/memories.js +16 -29
  605. package/packages/server/dist/routes/memories.js.map +1 -1
  606. package/packages/server/dist/routes/night.d.ts +31 -0
  607. package/packages/server/dist/routes/night.d.ts.map +1 -0
  608. package/packages/server/dist/routes/night.js +28 -0
  609. package/packages/server/dist/routes/night.js.map +1 -0
  610. package/packages/server/dist/routes/org.d.ts.map +1 -1
  611. package/packages/server/dist/routes/org.js +125 -119
  612. package/packages/server/dist/routes/org.js.map +1 -1
  613. package/packages/server/dist/routes/profile.d.ts.map +1 -1
  614. package/packages/server/dist/routes/profile.js +5 -6
  615. package/packages/server/dist/routes/profile.js.map +1 -1
  616. package/packages/server/dist/routes/providers.d.ts.map +1 -1
  617. package/packages/server/dist/routes/providers.js +1 -3
  618. package/packages/server/dist/routes/providers.js.map +1 -1
  619. package/packages/server/dist/routes/query.d.ts +10 -0
  620. package/packages/server/dist/routes/query.d.ts.map +1 -0
  621. package/packages/server/dist/routes/query.js +17 -0
  622. package/packages/server/dist/routes/query.js.map +1 -0
  623. package/packages/server/dist/routes/questions.d.ts.map +1 -1
  624. package/packages/server/dist/routes/questions.js +5 -11
  625. package/packages/server/dist/routes/questions.js.map +1 -1
  626. package/packages/server/dist/routes/sessions.d.ts.map +1 -1
  627. package/packages/server/dist/routes/sessions.js +20 -28
  628. package/packages/server/dist/routes/sessions.js.map +1 -1
  629. package/packages/server/dist/routes/sleep.d.ts.map +1 -1
  630. package/packages/server/dist/routes/sleep.js +21 -36
  631. package/packages/server/dist/routes/sleep.js.map +1 -1
  632. package/packages/server/dist/routes/stats.d.ts.map +1 -1
  633. package/packages/server/dist/routes/stats.js +2 -7
  634. package/packages/server/dist/routes/stats.js.map +1 -1
  635. package/packages/server/dist/routes/terminals.d.ts.map +1 -1
  636. package/packages/server/dist/routes/terminals.js +19 -14
  637. package/packages/server/dist/routes/terminals.js.map +1 -1
  638. package/packages/server/dist/routes/tools.d.ts.map +1 -1
  639. package/packages/server/dist/routes/tools.js +7 -5
  640. package/packages/server/dist/routes/tools.js.map +1 -1
  641. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  642. package/packages/server/dist/routes/ws.js +235 -207
  643. package/packages/server/dist/routes/ws.js.map +1 -1
  644. package/packages/server/dist/schemas.d.ts +30 -21
  645. package/packages/server/dist/schemas.d.ts.map +1 -1
  646. package/packages/server/dist/schemas.js +3 -2
  647. package/packages/server/dist/schemas.js.map +1 -1
  648. package/packages/server/dist/server.d.ts.map +1 -1
  649. package/packages/server/dist/server.js +250 -230
  650. package/packages/server/dist/server.js.map +1 -1
  651. package/packages/server/dist/services/stream.d.ts.map +1 -1
  652. package/packages/server/dist/services/stream.js +6 -4
  653. package/packages/server/dist/services/stream.js.map +1 -1
  654. package/packages/server/dist/services/stt.d.ts +1 -1
  655. package/packages/server/dist/services/stt.d.ts.map +1 -1
  656. package/packages/server/dist/services/stt.js +175 -124
  657. package/packages/server/dist/services/stt.js.map +1 -1
  658. package/packages/server/dist/services/tts.d.ts.map +1 -1
  659. package/packages/server/dist/services/tts.js +82 -54
  660. package/packages/server/dist/services/tts.js.map +1 -1
  661. package/packages/server/dist/services/turns.d.ts +8 -6
  662. package/packages/server/dist/services/turns.d.ts.map +1 -1
  663. package/packages/server/dist/services/turns.js +36 -32
  664. package/packages/server/dist/services/turns.js.map +1 -1
  665. package/packages/server/dist/services/updates.d.ts +1 -0
  666. package/packages/server/dist/services/updates.d.ts.map +1 -1
  667. package/packages/server/dist/services/updates.js +150 -91
  668. package/packages/server/dist/services/updates.js.map +1 -1
  669. package/packages/server/dist/services/voice-keys.d.ts.map +1 -1
  670. package/packages/server/dist/services/voice-keys.js +4 -2
  671. package/packages/server/dist/services/voice-keys.js.map +1 -1
  672. package/packages/server/dist/static.d.ts +1 -1
  673. package/packages/server/dist/static.d.ts.map +1 -1
  674. package/packages/server/dist/static.js +7 -7
  675. package/packages/server/dist/static.js.map +1 -1
  676. package/packages/server/package.json +1 -1
  677. package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-D7YyFndQ.js → abnfDiagram-O67JEVCF-c90Gs7pG.js} +1 -1
  678. package/packages/web/dist/assets/{arc-C_Zgk2dJ.js → arc-C28-SQX8.js} +1 -1
  679. package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-eI0adu1B.js → architectureDiagram-NJMV4G6O-CBPhVAKx.js} +1 -1
  680. package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-WAoOFUA9.js → blockDiagram-BEXU5L5S-CwKMvCbh.js} +1 -1
  681. package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-DE8Zyhng.js → c4Diagram-YGBWAQC7-CsL4YtmG.js} +1 -1
  682. package/packages/web/dist/assets/channel-gYp6Rt3b.js +1 -0
  683. package/packages/web/dist/assets/{chunk-2Q5K7J3B-bnqLP2XD.js → chunk-2Q5K7J3B-C9Bji_Nr.js} +1 -1
  684. package/packages/web/dist/assets/{chunk-3FUC2YCW-Ck1_SVe0.js → chunk-3FUC2YCW-BUnPWClf.js} +2 -2
  685. package/packages/web/dist/assets/{chunk-5VM5RSS4-hDmC41gD.js → chunk-5VM5RSS4-CdfpfDTC.js} +1 -1
  686. package/packages/web/dist/assets/{chunk-GTNCS2PH-PoWvfCrT.js → chunk-GTNCS2PH-BZrKT8Ne.js} +1 -1
  687. package/packages/web/dist/assets/{chunk-GWA4HPMP-D3V0IG43.js → chunk-GWA4HPMP-C0jEzDJu.js} +1 -1
  688. package/packages/web/dist/assets/{chunk-JWPE2WC7-BryfpHM5.js → chunk-JWPE2WC7-CkLRmEro.js} +1 -1
  689. package/packages/web/dist/assets/{chunk-NETBCI7D-8ic1iEdT.js → chunk-NETBCI7D-BBeWMDmk.js} +1 -1
  690. package/packages/web/dist/assets/{chunk-WEXAMYUT-nM8tmQT2.js → chunk-WEXAMYUT-B6IqsBxs.js} +1 -1
  691. package/packages/web/dist/assets/{chunk-XXDRQBXY-Do28F482.js → chunk-XXDRQBXY-BPXeDnB2.js} +1 -1
  692. package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-Bop9oNNO.js → classDiagram-v2-NBCMYWYE-2kqq2mJ8.js} +1 -1
  693. package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-a7f_bpnt.js → cose-bilkent-JH36ORCC-G49FKtk6.js} +1 -1
  694. package/packages/web/dist/assets/{cynefin-OW5HDTMX-DnArcis_.js → cynefin-OW5HDTMX-98M_mPg9.js} +1 -1
  695. package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-vEuTb1GD.js → cynefinDiagram-VND7K2PF-BYJTAxOT.js} +1 -1
  696. package/packages/web/dist/assets/{dagre-6A5THRUB-BgG4MynJ.js → dagre-6A5THRUB-Bxcb5kkl.js} +1 -1
  697. package/packages/web/dist/assets/{diagram-22UHCM2B-DRCQpafv.js → diagram-22UHCM2B-DK7wAztC.js} +1 -1
  698. package/packages/web/dist/assets/{diagram-3UASUU5V-BKgmAXde.js → diagram-3UASUU5V-BMRz0ele.js} +1 -1
  699. package/packages/web/dist/assets/{diagram-ATOU4E4O-B6Hsy36X.js → diagram-ATOU4E4O-O23sdVpm.js} +1 -1
  700. package/packages/web/dist/assets/{diagram-CDSNMT55-JflyfyoB.js → diagram-CDSNMT55-CGxai-zV.js} +1 -1
  701. package/packages/web/dist/assets/{diagram-MLGK6HIB-Dd2QPJjT.js → diagram-MLGK6HIB-B_29W-sW.js} +1 -1
  702. package/packages/web/dist/assets/{diagram-MPIPVDR6-DE5QU60x.js → diagram-MPIPVDR6-OSt1qPU_.js} +1 -1
  703. package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-D7AQ741b.js → ebnfDiagram-ZINNZB2B-DnZcwiew.js} +1 -1
  704. package/packages/web/dist/assets/{elk-276RUBZZ-CeewBVLF.js → elk-276RUBZZ-BP6-xQAF.js} +1 -1
  705. package/packages/web/dist/assets/{erDiagram-OPXOYQCR-mLLYkZ5c.js → erDiagram-OPXOYQCR-DhG7UZtA.js} +1 -1
  706. package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-DtpSpsQN.js → flowDiagram-KWPJA3E3-CNTS1YPA.js} +1 -1
  707. package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-1_lh-3ky.js → ganttDiagram-FUAMR5RP-_eKkbUxc.js} +1 -1
  708. package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DoPXZuT5.js → gitGraphDiagram-X574FWY7-N_PXNE-o.js} +1 -1
  709. package/packages/web/dist/assets/index-DGq8BOVF.js +646 -0
  710. package/packages/web/dist/assets/index-DgMuFFt3.css +32 -0
  711. package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-DQpRGGiD.js → infoDiagram-VRGFBTTK-vj_EDhft.js} +1 -1
  712. package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js → ishikawaDiagram-OU5B5YK6-Dr0BodVq.js} +1 -1
  713. package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bg-oeFjb.js → journeyDiagram-ZHPQQLJL-DykOPAu9.js} +1 -1
  714. package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BnpI4VH8.js → kanban-definition-PNTS6WVX-zslQcJnX.js} +1 -1
  715. package/packages/web/dist/assets/{mermaid.core-BwBKxlRA.js → mermaid.core-C888eQE1.js} +4 -4
  716. package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-NBnnxEoO.js → mindmap-definition-NLK3R4M7-CpdltDoL.js} +1 -1
  717. package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-RrXXbIvO.js → pegDiagram-GJSIUBJH-Dsx3NmVN.js} +1 -1
  718. package/packages/web/dist/assets/{pieDiagram-5QR66LMP-B27q6Gso.js → pieDiagram-5QR66LMP-D_4DJLkr.js} +1 -1
  719. package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-DGDsdur2.js → quadrantDiagram-O4NWA36T-BXgGWrJ1.js} +1 -1
  720. package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-GdjkE3mI.js → railroadDiagram-XR7U4H2S-WMsrl4TR.js} +1 -1
  721. package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-DjK0GfgO.js → requirementDiagram-PLB6GJNP-m2PpXDpq.js} +1 -1
  722. package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-BG_AIkwF.js → sankeyDiagram-IPEJSGJF-DfcxNy3C.js} +1 -1
  723. package/packages/web/dist/assets/scene-BA1PRRU7.js +4620 -0
  724. package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-CIQwUb4y.js → sequenceDiagram-PO4LG4MO-B8yIKbJ8.js} +1 -1
  725. package/packages/web/dist/assets/{sizeCapture-INFHLROL-bpIoPxdJ.js → sizeCapture-INFHLROL-Cic9nV7h.js} +1 -1
  726. package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-8hYXvPPv.js → stateDiagram-v2-GCMORJYK-oOFJPdg1.js} +1 -1
  727. package/packages/web/dist/assets/{swimlanes-2SLR337P-gfflUMF9.js → swimlanes-2SLR337P-UCvVVk9j.js} +1 -1
  728. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-B8q2Z_Nb.js +8 -0
  729. package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-PHMNoGTZ.js → timeline-definition-EJHVYXUP-BLgviPCi.js} +1 -1
  730. package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-B2j5iteO.js → usecaseDiagram-POWQR4AR-CV7U5Y4h.js} +1 -1
  731. package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-BzxtZ-_2.js → vennDiagram-UO4OBE2U-C8OA0JqM.js} +1 -1
  732. package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-DL7YbMpY.js → wardleyDiagram-VNRHLVJA-F55WtNqt.js} +1 -1
  733. package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-CisgP1cT.js → xychartDiagram-PMCCYNJV-C93Bzul9.js} +1 -1
  734. package/packages/web/dist/index.html +2 -2
  735. package/packages/web/package.json +1 -1
  736. package/packages/web/dist/assets/channel-egZxcyUK.js +0 -1
  737. package/packages/web/dist/assets/index-Cw2Opmx7.js +0 -648
  738. package/packages/web/dist/assets/index-j0zBRCgT.css +0 -32
  739. package/packages/web/dist/assets/scene-D4LPicHk.js +0 -4620
  740. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +0 -8
@@ -1,45 +1,43 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import { ASSISTANT_MEMORY_OWNER, } from '../types.js';
3
3
  import { silentLogger } from '../logger.js';
4
- import { entitySlug } from './store.js';
5
4
  import { parseCandidates, smallModelFor } from './extractor.js';
6
5
  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';
6
+ import { recall } from './recall.js';
7
+ import { locateTurn } from './dream/label.js';
8
+ import { NIGHT_PHASES } from './dream/slots.js';
9
+ import { SkillStore } from '../skills/store.js';
10
+ import { DreamPhase } from './sleep-dream.js';
11
+ import { CONDENSE_PROMPT, INSIGHT_USER_PROMPT, INSIGHT_WORK_PROMPT, LINK_PROMPT, REPLAY_PROMPT, RESOLVE_PROMPT, REVISE_PROMPT, SKILL_PROMPT, TRIAGE_PROMPT, } from './sleep-prompts.js';
12
+ import { DAY_MS, clamp01, clampDays, clampMs } from './sleep-limits.js';
13
+ import { ask, clipText, parseObject } from './sleep-model.js';
14
+ import { describeSleep, plural } from './sleep-report.js';
15
+ import { MAX_MERGED_TAGS, isProtected, readAliases, readCondensed, readCorrectionClaims, readEntityKinds, readInsightDrafts, readMergeVerdict, readProposedEdges, readRevision, readSkillDrafts, unionTags, } from './sleep-verdicts.js';
16
+ export { describeSleep } from './sleep-report.js';
17
+ export { parseObject } from './sleep-model.js';
18
+ /** Nothing decided: the model gave no usable answer, or the pair had to wait. */
19
+ const UNSETTLED = { resolved: 0, retired: 0, merged: 0 };
19
20
  export class SleepRunner extends EventEmitter {
20
21
  #store;
21
22
  #registry;
22
23
  #config;
23
24
  #log;
24
- #onPromotion;
25
25
  /** One night at a time per bank. */
26
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 };
27
+ /** The dream's half of the night: measuring, labelling and proposing. */
28
+ #dreaming;
36
29
  constructor(options) {
37
30
  super();
38
31
  this.#store = options.store;
39
32
  this.#registry = options.registry;
40
33
  this.#config = options.config;
41
34
  this.#log = options.logger ?? silentLogger;
42
- this.#onPromotion = options.onPromotion;
35
+ this.#dreaming = new DreamPhase({
36
+ store: this.#store,
37
+ config: this.#config,
38
+ logger: this.#log,
39
+ onPromotion: options.onPromotion,
40
+ });
43
41
  }
44
42
  isRunning(owner = ASSISTANT_MEMORY_OWNER) {
45
43
  return this.#running.has(owner);
@@ -140,282 +138,318 @@ export class SleepRunner extends EventEmitter {
140
138
  if (latest)
141
139
  return latest;
142
140
  }
141
+ const run = this.#store.createSleepRun({ owner, trigger: input.trigger ?? 'manual' });
143
142
  const controller = new AbortController();
144
- if (input.signal) {
145
- if (input.signal.aborted)
146
- controller.abort();
147
- else
148
- input.signal.addEventListener('abort', () => controller.abort(), { once: true });
149
- }
143
+ const stopFollowing = followSignal(input.signal, controller);
150
144
  this.#running.set(owner, controller);
151
- const run = this.#store.createSleepRun({ owner, trigger: input.trigger ?? 'manual' });
152
145
  this.#announce(run, 'started');
153
146
  this.#log.info('Sleep started', { owner, run: run.id });
154
- const counters = {
155
- readCount: 0,
156
- replayedCount: 0,
157
- learnedCount: 0,
158
- mergedCount: 0,
159
- dormantCount: 0,
160
- edgeCount: 0,
161
- insightCount: 0,
162
- skillCount: 0,
163
- skillRevisedCount: 0,
164
- conflictCount: 0,
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,
179
- modelCalls: 0,
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
- };
147
+ const night = this.#openNight(owner, run.id, controller.signal);
194
148
  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;
203
149
  try {
204
- const providerId = await this.#resolveProvider(input.provider);
205
- const settings = this.#config.memory.sleep;
206
- const cycles = Math.max(1, Math.min(Math.round(settings.cycles), 5));
207
- const provider = providerId ? this.#registry.get(providerId) : null;
208
- const model = providerId ? settings.model.trim() || smallModelFor(providerId) : undefined;
209
- const insightModel = settings.insightModel.trim() || model;
210
- const live = this.#store.liveMemories(owner);
211
- counters.readCount = live.length;
212
- if (!provider) {
213
- this.#log.warn('Sleep ran without a provider; only light sleep happened', { owner });
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);
275
- for (let cycle = 1; cycle <= cycles; cycle += 1) {
276
- /* -------- light sleep: bookkeeping, no model, costs nothing -------- */
277
- this.#phase(run.id, 'light', counters, cycle);
278
- if (cycle === 1) {
279
- // Catch up anything written before the graph existed: its tags are
280
- // there, its entities are not. Pure bookkeeping, no model call.
281
- const orphans = this.#store.memoriesWithoutEntities(owner);
282
- for (const memory of orphans)
283
- linkEntities(this.#store, owner, memory.id, memory.tags);
284
- if (orphans.length) {
285
- this.#log.info('Attached entities to memories that had none', { owner, count: orphans.length });
286
- }
287
- counters.dormantCount += this.#decay(run.id, this.#store.liveMemories(owner));
288
- }
289
- this.#store.recountEntities(owner);
290
- this.#throwIfAborted(controller.signal);
291
- if (!provider || !budgets)
292
- continue;
293
- /* ---- deep sleep: filing. What repeats becomes one, what cannot ----
294
- ---- both be true gets decided. ---- */
295
- this.#phase(run.id, 'deep', counters, cycle);
296
- const clusters = this.#cluster(owner, this.#store.liveMemories(owner));
297
- const condensed = await this.#condense(provider, model, owner, run.id, clusters, controller.signal, share(budgets.condense, cycles, cycle, 'early'));
298
- counters.mergedCount += condensed.merged;
299
- counters.dormantCount += condensed.retired;
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;
305
- // Contradictions the previous cycle (or an earlier night) turned up.
306
- const settled = await this.#resolve(provider, model, owner, run.id, controller.signal, share(budgets.resolve, cycles, cycle, 'late'));
307
- counters.resolvedCount += settled.resolved;
308
- counters.dormantCount += settled.retired;
309
- counters.mergedCount += settled.merged;
310
- counters.modelCalls += settled.calls;
311
- spend.resolve.calls += settled.calls;
312
- spend.resolve.value += settled.resolved;
313
- this.#phase(run.id, 'deep', counters, cycle);
314
- this.#throwIfAborted(controller.signal);
315
- /* ---- dream sleep: the loose, associative part. Connections ----
316
- ---- across distance, and what the week adds up to. ---- */
317
- this.#phase(run.id, 'rem', counters, cycle);
318
- const linked = await this.#link(provider, model, owner, run.id, controller.signal, share(budgets.link, cycles, cycle, 'late'));
319
- counters.edgeCount += linked.edges;
320
- counters.conflictCount += linked.conflicts;
321
- counters.modelCalls += linked.calls;
322
- spend.link.calls += linked.calls;
323
- spend.link.value += linked.edges;
324
- // Insights come last, once the bank is as tidy as it will get tonight.
325
- if (cycle === cycles) {
326
- const insight = await this.#reflect(provider, insightModel, owner, run.id, controller.signal, budgets.reflect);
327
- counters.insightCount += insight.written;
328
- counters.edgeCount += insight.edges;
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;
361
- }
362
- this.#phase(run.id, 'rem', counters, cycle);
363
- this.#throwIfAborted(controller.signal);
364
- }
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);
150
+ await this.#sleepThrough(night, input.provider);
394
151
  }
395
152
  catch (cause) {
396
153
  error = cause.message;
397
154
  this.#log.warn('Sleep phase failed', { owner, error });
398
155
  }
399
156
  finally {
157
+ // Hygiene is not work the night can fail at: it runs after a finished,
158
+ // a failed and a cancelled night alike, or a night that keeps failing
159
+ // would keep the verbatim frame store past its window (R17).
160
+ error ??= this.#tidyAfterNight(owner);
400
161
  this.#running.delete(owner);
162
+ stopFollowing();
163
+ }
164
+ return this.#closeRun(run, night, error);
165
+ }
166
+ #openNight(owner, runId, signal) {
167
+ const cycles = Math.max(1, Math.min(Math.round(this.#config.memory.sleep.cycles), MAX_CYCLES));
168
+ return {
169
+ owner,
170
+ runId,
171
+ signal,
172
+ cycles,
173
+ tally: emptyTally(),
174
+ spend: emptySpend(),
175
+ reportSuffix: '',
176
+ labelFailures: 0,
177
+ };
178
+ }
179
+ /**
180
+ * The night's work, in order. A phase that throws ends it here; whatever
181
+ * finished before stays done.
182
+ */
183
+ async #sleepThrough(night, requested) {
184
+ const { owner, runId, tally } = night;
185
+ const voices = await this.#gatherVoices(night.signal, requested);
186
+ tally.readCount = this.#store.liveMemories(owner).length;
187
+ if (!voices) {
188
+ this.#log.warn('Sleep ran without a provider; only light sleep happened', { owner });
189
+ }
190
+ // The replay comes first, because the read has to happen before anything
191
+ // else: what the night harvests there should be condensed tonight, not
192
+ // tomorrow.
193
+ if (voices)
194
+ await this.#replayDay(night, voices);
195
+ const plan = voices ? { voices, budgets: this.#fundNight(owner) } : null;
196
+ /* ---- the dream: the measurement of the retrieval policy, and the ----
197
+ ---- one place a parameter set can go in force. Wedged here on ----
198
+ ---- purpose: BEFORE the cycle loop (R7), so that the freshness ----
199
+ ---- side sees the bank the day left rather than the supersessions ----
200
+ ---- #condense is about to write, and ABOVE the provider guard ----
201
+ ---- inside the loop (R8), so the whole of it also runs in a night ----
202
+ ---- without a provider - the one night where it is the only thing ----
203
+ ---- that could run at all. Stage 2 dreams for the assistant's ----
204
+ ---- bank only (R18); agent frames would be cost without a night ----
205
+ ---- that ever scores them. ---- */
206
+ night.reportSuffix += await this.#dream(owner, runId, tally, night.signal);
207
+ for (let cycle = 1; cycle <= night.cycles; cycle += 1) {
208
+ this.#lightSleep(night, cycle);
209
+ if (!plan)
210
+ continue;
211
+ await this.#deepSleep(night, plan, cycle);
212
+ await this.#remSleep(night, plan, cycle);
213
+ }
214
+ this.#dreaming.measureSlots(owner, night.spend);
215
+ }
216
+ /** The three models the night talks to; null when no provider is usable. */
217
+ async #gatherVoices(signal, requested) {
218
+ const providerId = await this.#resolveProvider(requested);
219
+ const provider = providerId ? this.#registry.get(providerId) : null;
220
+ if (!providerId || !provider)
221
+ return null;
222
+ const settings = this.#config.memory.sleep;
223
+ const deepModel = settings.model.trim() || smallModelFor(providerId);
224
+ const insightModel = settings.insightModel.trim() || deepModel;
225
+ const voice = (model) => ({ provider, model, signal, log: this.#log });
226
+ return {
227
+ triage: voice(smallModelFor(providerId)),
228
+ deep: voice(deepModel),
229
+ insight: voice(insightModel),
230
+ };
231
+ }
232
+ /**
233
+ * Replay: the day, read again and properly, before the cycles - so
234
+ * tonight's harvest is condensed tonight, not tomorrow.
235
+ */
236
+ async #replayDay(night, voices) {
237
+ const { owner, runId, tally } = night;
238
+ const sessions = this.#replayCandidates(owner);
239
+ this.#phase(runId, 'replay', tally, 1);
240
+ const replayed = await this.#replay({ owner, runId, voice: voices.deep }, voices.triage, sessions);
241
+ tally.replayedCount += replayed.read;
242
+ tally.learnedCount += replayed.learned;
243
+ tally.modelCalls += replayed.calls;
244
+ tally.dreamLabelsWritten += replayed.labels;
245
+ night.labelFailures += replayed.labelFailures;
246
+ night.reportSuffix += this.#dreaming.correctionPrecision(replayed);
247
+ // The bank changed, so the figure the run reports as "looked at" has
248
+ // to be taken after the harvest, not before it.
249
+ tally.readCount = this.#store.liveMemories(owner).length;
250
+ this.#phase(runId, 'replay', tally, 1);
251
+ this.#throwIfAborted(night.signal);
252
+ }
253
+ /**
254
+ * The night's wallet is filled by need, not by the clock, and it is
255
+ * filled after the replay, not before it. The re-read grows the bank,
256
+ * surfaces contradictions and pulls corrections out of the day's words,
257
+ * and that is precisely the work the later phases exist to do; a budget
258
+ * measured before the read funds the night for a quieter day than the one
259
+ * it just had. The arithmetic is database-only, but it is not free:
260
+ * #demand clusters the living bank pair by pair, and the dream probe that
261
+ * follows reads and scores every stored frame. Both carry their own
262
+ * ceilings (#demand's phase budgets, the probe's dream.maxEvalMs), so
263
+ * "measures itself" means "costs up to a declared bound", never "costs
264
+ * nothing".
265
+ */
266
+ #fundNight(owner) {
267
+ const settings = this.#config.memory.sleep;
268
+ const demand = this.#demand(owner, this.#store.liveMemories(owner));
269
+ const budgets = allocateNightBudget(demand, settings.nightBudget, {
270
+ condense: settings.maxMergeCalls,
271
+ resolve: settings.maxResolveCalls,
272
+ link: settings.maxLinkCalls,
273
+ reflect: settings.insights > 0 ? INSIGHT_ANGLES.length : 0,
274
+ revise: settings.skillRevisions,
275
+ practise: settings.skills,
276
+ });
277
+ this.#log.info('Night measured', { owner, demand, budgets });
278
+ return budgets;
279
+ }
280
+ /** Light sleep: bookkeeping, no model, costs nothing. */
281
+ #lightSleep(night, cycle) {
282
+ const { owner, runId, tally } = night;
283
+ this.#phase(runId, 'light', tally, cycle);
284
+ if (cycle === 1) {
285
+ this.#attachOrphanEntities(owner);
286
+ tally.dormantCount += this.#decay(runId, this.#store.liveMemories(owner));
287
+ }
288
+ this.#store.recountEntities(owner);
289
+ this.#throwIfAborted(night.signal);
290
+ }
291
+ /**
292
+ * Catch up anything written before the graph existed: its tags are there,
293
+ * its entities are not. Pure bookkeeping, no model call.
294
+ */
295
+ #attachOrphanEntities(owner) {
296
+ const orphans = this.#store.memoriesWithoutEntities(owner);
297
+ for (const memory of orphans)
298
+ linkEntities(this.#store, owner, memory.id, memory.tags);
299
+ if (orphans.length) {
300
+ this.#log.info('Attached entities to memories that had none', { owner, count: orphans.length });
301
+ }
302
+ }
303
+ /**
304
+ * Deep sleep: filing. What repeats becomes one, what cannot both be true
305
+ * gets decided.
306
+ */
307
+ async #deepSleep(night, plan, cycle) {
308
+ const { owner, runId, tally } = night;
309
+ const scope = { owner, runId, voice: plan.voices.deep };
310
+ this.#phase(runId, 'deep', tally, cycle);
311
+ const clusters = this.#cluster(owner, this.#store.liveMemories(owner));
312
+ const condensed = await this.#condense(scope, clusters, share(plan.budgets.condense, night.cycles, cycle, 'early'));
313
+ tally.mergedCount += condensed.merged;
314
+ tally.dormantCount += condensed.retired;
315
+ tally.modelCalls += condensed.calls;
316
+ tally.dreamLabelsWritten += condensed.labels;
317
+ night.labelFailures += condensed.labelFailures;
318
+ bookSpend(night, 'condense', condensed.calls, condensed.merged);
319
+ // Contradictions the previous cycle (or an earlier night) turned up.
320
+ const settled = await this.#resolve(scope, share(plan.budgets.resolve, night.cycles, cycle, 'late'));
321
+ tally.resolvedCount += settled.resolved;
322
+ tally.dormantCount += settled.retired;
323
+ tally.mergedCount += settled.merged;
324
+ tally.modelCalls += settled.calls;
325
+ bookSpend(night, 'resolve', settled.calls, settled.resolved);
326
+ this.#phase(runId, 'deep', tally, cycle);
327
+ this.#throwIfAborted(night.signal);
328
+ }
329
+ /**
330
+ * Dream sleep: the loose, associative part. Connections across distance,
331
+ * and what the week adds up to.
332
+ */
333
+ async #remSleep(night, plan, cycle) {
334
+ const { owner, runId, tally } = night;
335
+ this.#phase(runId, 'rem', tally, cycle);
336
+ const scope = { owner, runId, voice: plan.voices.deep };
337
+ const linked = await this.#link(scope, share(plan.budgets.link, night.cycles, cycle, 'late'));
338
+ tally.edgeCount += linked.edges;
339
+ tally.conflictCount += linked.conflicts;
340
+ tally.modelCalls += linked.calls;
341
+ bookSpend(night, 'link', linked.calls, linked.edges);
342
+ // Insights come last, once the bank is as tidy as it will get tonight.
343
+ if (cycle === night.cycles) {
344
+ await this.#recordInsights(night, plan);
345
+ await this.#writeCandidates(night, plan);
346
+ await this.#tendSkills(night, plan);
347
+ }
348
+ this.#phase(runId, 'rem', tally, cycle);
349
+ this.#throwIfAborted(night.signal);
350
+ }
351
+ async #recordInsights(night, plan) {
352
+ const { owner, runId, tally } = night;
353
+ const insight = await this.#reflect({ owner, runId, voice: plan.voices.insight }, plan.budgets.reflect);
354
+ tally.insightCount += insight.written;
355
+ tally.edgeCount += insight.edges;
356
+ tally.modelCalls += insight.calls;
357
+ bookSpend(night, 'reflect', insight.calls, insight.written);
358
+ }
359
+ /**
360
+ * The candidate writer (concept 6.2, 9.4). Here, and not earlier: the
361
+ * order is deliberate - first it has to be settled how well the search
362
+ * control works, then procedures get rewritten. Its wallet is run-global
363
+ * (`dream.maxCallsPerNight` across ALL owners), because with
364
+ * `sleep.scope: 'all'` the runtime runs one night per bank and a per-run
365
+ * ceiling would multiply by the owner count. What it writes are
366
+ * proposals, not policies: the night that measures them is the next one,
367
+ * above the provider guard, which is what keeps the promotion path
368
+ * model-free.
369
+ */
370
+ async #writeCandidates(night, plan) {
371
+ const { owner, runId, tally } = night;
372
+ const proposed = await this.#dreaming.propose({ owner, runId, voice: plan.voices.deep }, this.#dreaming.remainingCalls());
373
+ tally.dreamCandidates += proposed.written;
374
+ tally.modelCalls += proposed.calls;
375
+ this.#dreaming.bookCalls(proposed.calls);
376
+ }
377
+ /**
378
+ * After the insights, the two steps that leave something behind outside
379
+ * the bank. Repair comes first on purpose: a procedure that has gone stale
380
+ * is actively misleading whoever opens it next, which is worth more than a
381
+ * ninth procedure nobody asked for.
382
+ */
383
+ async #tendSkills(night, plan) {
384
+ const { owner, runId, tally } = night;
385
+ const scope = { owner, runId, voice: plan.voices.insight };
386
+ const revised = await this.#revise(scope, plan.budgets.revise);
387
+ tally.skillRevisedCount += revised.written;
388
+ tally.modelCalls += revised.calls;
389
+ bookSpend(night, 'revise', revised.calls, revised.written);
390
+ const practised = await this.#practise(scope, plan.budgets.practise);
391
+ tally.skillCount += practised.written;
392
+ tally.modelCalls += practised.calls;
393
+ bookSpend(night, 'practise', practised.calls, practised.written);
394
+ }
395
+ /**
396
+ * What closes every night, whatever became of its work: entity counts are
397
+ * brought up to date and the dream's retention clocks run. Never throws;
398
+ * the failure, if any, comes back for the run to carry.
399
+ */
400
+ #tidyAfterNight(owner) {
401
+ try {
402
+ this.#store.recountEntities(owner);
403
+ this.#sweepRetention();
404
+ return undefined;
405
+ }
406
+ catch (cause) {
407
+ const error = cause.message;
408
+ this.#log.warn('Sleep tidy-up failed', { owner, error });
409
+ return error;
401
410
  }
411
+ }
412
+ /**
413
+ * The dream's two retention clocks (concept 8.7, S21). Frames and the
414
+ * episode index go after `frameRetainDays`, because both point at verbatim
415
+ * text - a frame quotes the rows it froze, an episode points straight at
416
+ * journal steps. Traces, touches, labels and evaluations go after
417
+ * `retainDays`: they are small, they carry the calibration, and none of
418
+ * them holds a word anybody wrote. Every sweep runs in batches of 500 with
419
+ * its own transaction, so the one connection is never locked for long.
420
+ * Hygiene, not measurement: this runs with the dream switched off too,
421
+ * because a verbatim store must not outlive its retention window just
422
+ * because measuring was turned off (R17).
423
+ */
424
+ #sweepRetention() {
425
+ const dream = this.#config.memory.dream;
426
+ const now = Date.now();
427
+ const frameBefore = now - clampDays(dream.frameRetainDays) * DAY_MS;
428
+ const traceBefore = now - clampDays(dream.retainDays) * DAY_MS;
429
+ this.#store.sweepDreamFrames(frameBefore);
430
+ this.#store.sweepDreamEpisodes(frameBefore);
431
+ this.#store.sweepDreamTraces(traceBefore);
432
+ this.#store.sweepDreamLabels(traceBefore);
433
+ this.#store.sweepDreamEvals(traceBefore);
434
+ }
435
+ #closeRun(run, night, error) {
402
436
  const finished = Date.now();
403
437
  const updated = this.#store.updateSleepRun(run.id, {
404
- ...counters,
438
+ ...night.tally,
405
439
  status: error ? 'failed' : 'done',
406
440
  finishedAt: finished,
407
441
  durationMs: finished - run.startedAt,
408
- report: describeSleep(counters) + dreamReportSuffix,
442
+ report: describeSleep(night.tally) + night.reportSuffix + labelFailureNote(night.labelFailures),
409
443
  error,
410
444
  }) ?? run;
411
445
  this.#announce(updated, 'finished');
412
446
  this.#log.info('Sleep finished', {
413
- owner,
447
+ owner: night.owner,
414
448
  run: run.id,
415
449
  status: updated.status,
416
- merged: counters.mergedCount,
417
- dormant: counters.dormantCount,
418
- calls: counters.modelCalls,
450
+ merged: night.tally.mergedCount,
451
+ dormant: night.tally.dormantCount,
452
+ calls: night.tally.modelCalls,
419
453
  });
420
454
  return updated;
421
455
  }
@@ -434,27 +468,52 @@ export class SleepRunner extends EventEmitter {
434
468
  */
435
469
  #demand(owner, live) {
436
470
  const settings = this.#config.memory.sleep;
437
- const since = this.#store.lastSleepAt(owner);
438
471
  const condense = this.#cluster(owner, live).length;
439
472
  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;
473
+ const link = Math.ceil(this.#freshMemories(owner).length / LINK_PORTION);
474
+ // One pass per angle, on purpose: one looks for patterns in the user, one
475
+ // in the work - neither prompt sees the other's angle.
476
+ const reflect = settings.insights > 0 && this.#reflectionDue(owner) ? INSIGHT_ANGLES.length : 0;
454
477
  const revise = this.#skillSuspects(owner).length;
455
- const practise = settings.skills > 0 && live.length >= 6 ? 1 : 0;
478
+ const practise = settings.skills > 0 && live.length >= MIN_PRACTISE_MEMORIES ? 1 : 0;
456
479
  return { condense, resolve, link, reflect, revise, practise };
457
480
  }
481
+ /** What this bank learned since its last finished night, and still stands. */
482
+ #freshMemories(owner) {
483
+ const since = this.#store.lastSleepAt(owner);
484
+ return this.#store
485
+ .listMemories({ owner, since: since || undefined, limit: FRESH_LIMIT, includeDormant: false })
486
+ .filter((memory) => !memory.supersededBy);
487
+ }
488
+ /** What the insight window holds that is not itself an insight. */
489
+ #reflectPool(owner) {
490
+ const since = Date.now() - this.#config.memory.sleep.insightWindowDays * DAY_MS;
491
+ return this.#store
492
+ .listMemories({ owner, since, limit: REFLECT_POOL_LIMIT, includeDormant: false })
493
+ .filter((memory) => memory.kind !== 'insight');
494
+ }
495
+ /**
496
+ * Whether the insight window holds enough to look for a pattern in, and
497
+ * something the last insight pass had not read. Asked again over the same
498
+ * memories plus a day's three, the model words yesterday's insight a
499
+ * little differently, and the bank fills with paraphrases of itself.
500
+ */
501
+ #reflectionDue(owner) {
502
+ const pool = this.#reflectPool(owner);
503
+ if (pool.length < MIN_REFLECT_POOL)
504
+ return false;
505
+ const reflectedUntil = newestCreation(this.#insightsOnRecord(owner));
506
+ return pool.some((memory) => memory.createdAt > reflectedUntil);
507
+ }
508
+ /** The insights already standing in the bank. */
509
+ #insightsOnRecord(owner) {
510
+ return this.#store.listMemories({
511
+ owner,
512
+ kinds: ['insight'],
513
+ limit: ON_RECORD_LIMIT,
514
+ includeDormant: false,
515
+ });
516
+ }
458
517
  /**
459
518
  * The conversations worth reading again tonight, oldest pending first.
460
519
  *
@@ -470,13 +529,10 @@ export class SleepRunner extends EventEmitter {
470
529
  return [];
471
530
  const since = this.#store.lastSleepAt(owner);
472
531
  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());
532
+ for (const session of this.#store.sessionsActiveSince(since, REPLAY_SCAN)) {
477
533
  // Nothing was said, or barely: "thanks" followed by "you're welcome"
478
534
  // holds nothing durable no matter how expensively it is read.
479
- if (spoken.length < 2)
535
+ if (userTurns(this.#store.getMessages(session.id)).length < MIN_SPOKEN_TURNS)
480
536
  continue;
481
537
  candidates.push(session);
482
538
  if (candidates.length >= budget)
@@ -486,18 +542,30 @@ export class SleepRunner extends EventEmitter {
486
542
  }
487
543
  /** Contradiction pairs neither side of which has been settled yet. */
488
544
  #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 }));
545
+ const open = [];
546
+ for (const edge of this.#store.listEdges(owner, CONTRADICTION_SCAN)) {
547
+ if (edge.relation !== 'contradicts')
548
+ continue;
549
+ const sides = this.#openSides(edge);
550
+ if (sides)
551
+ open.push({ edge, ...sides });
552
+ }
553
+ return open;
554
+ }
555
+ /**
556
+ * Both memories of a contradiction as they stand right now, or null when a
557
+ * side is gone or asleep. A pair with a sleeping side is already settled;
558
+ * skipping it is also what stops the same contradiction being re-decided
559
+ * every night - and, read again just before each decision, what stops a
560
+ * memory that lost one contradiction a moment ago from being put in front
561
+ * of the model, or merged, in the next.
562
+ */
563
+ #openSides(edge) {
564
+ const a = this.#store.getMemory(edge.srcId);
565
+ const b = this.#store.getMemory(edge.dstId);
566
+ if (!a || !b || a.dormantAt || b.dormantAt || a.forgotten || b.forgotten)
567
+ return null;
568
+ return { a, b };
501
569
  }
502
570
  /**
503
571
  * Read the day again.
@@ -532,16 +600,7 @@ export class SleepRunner extends EventEmitter {
532
600
  * at: it lands session-wide, counts for the agreement check and the
533
601
  * calibration, and never for a gain (S3).
534
602
  */
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
- };
603
+ async #replay(scope, triage, sessions) {
545
604
  // Corrections written from here on are this replay's, whatever else the
546
605
  // owner's table already holds - the label pass reads them back by id
547
606
  // afterwards, because `addCorrection` hands none out.
@@ -551,103 +610,119 @@ export class SleepRunner extends EventEmitter {
551
610
  // those transcripts to quote. The candidate list arrives pre-measured
552
611
  // from `#replayCandidates`, which applied the same two-turn filter the
553
612
  // 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;
613
+ if (scope.voice.signal.aborted || scope.owner !== ASSISTANT_MEMORY_OWNER || !sessions.length) {
614
+ return { read: 0, learned: 0, corrections: 0, labelled: 0, labels: 0, labelFailures: 0, calls: 0 };
615
+ }
616
+ const total = { read: 0, learned: 0, corrections: 0, calls: 0 };
560
617
  for (const session of sessions) {
561
- if (signal.aborted)
618
+ if (scope.voice.signal.aborted)
562
619
  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
- });
620
+ const reading = await this.#replaySession(scope, triage, session);
621
+ total.read += reading.read;
622
+ total.learned += reading.learned;
623
+ total.corrections += reading.corrections;
624
+ total.calls += reading.calls;
637
625
  }
638
626
  // One pass over what the night just wrote, once every session is read:
639
627
  // the labels need the correction ids, and those only exist in the table.
640
- const written = this.#writeCorrectionLabels(owner, sessions, since);
628
+ const written = this.#dreaming.writeCorrectionLabels(scope.owner, sessions, since);
641
629
  return {
642
- read,
643
- learned,
644
- corrections,
630
+ ...total,
645
631
  labelled: written.labelled,
646
632
  labels: written.labels,
647
633
  labelFailures: written.failed,
648
- calls,
649
634
  };
650
635
  }
636
+ async #replaySession(scope, triage, session) {
637
+ const messages = this.#store.getMessages(session.id).filter((message) => message.content.trim());
638
+ const spoken = userTurns(messages);
639
+ // Nothing was said, or barely: no model needed to know there is nothing
640
+ // durable in "thanks" followed by "you're welcome".
641
+ if (spoken.length < MIN_SPOKEN_TURNS)
642
+ return { read: 0, learned: 0, corrections: 0, calls: 0 };
643
+ if (!(await this.#worthReading(triage, spoken))) {
644
+ return { read: 0, learned: 0, corrections: 0, calls: 1 };
645
+ }
646
+ const conversation = {
647
+ session,
648
+ messages,
649
+ said: spoken.map((message) => message.content).join('\n'),
650
+ };
651
+ const transcript = messages
652
+ .map((message) => (message.role === 'user' ? 'USER: ' : 'ASSISTANT: ') + clipText(message.content, TURN_CLIP_CHARS))
653
+ .join('\n\n');
654
+ const raw = await ask(scope.voice, REPLAY_PROMPT +
655
+ '\n\nCURRENT DATE: ' + isoDay(Date.now()) +
656
+ '\n\nALREADY KNOWN:\n' + this.#knownFor(scope.owner, conversation.said) +
657
+ '\n\nTHE CONVERSATION:\n' + clipText(transcript, TRANSCRIPT_CHARS));
658
+ const parsed = parseObject(raw);
659
+ const learned = this.#admitReplayed(scope, conversation, parsed);
660
+ const corrections = this.#recordCorrections(scope, conversation, parsed);
661
+ this.#log.info('Replayed a conversation', {
662
+ session: session.id,
663
+ title: session.title,
664
+ learned,
665
+ corrections,
666
+ });
667
+ return { read: 1, learned, corrections, calls: 2 };
668
+ }
669
+ /**
670
+ * Triage, on the user's turns alone and heavily clipped. The question is
671
+ * only "is there anything here worth a proper look", and the assistant's
672
+ * side cannot answer that - nothing it said may back a memory anyway.
673
+ */
674
+ async #worthReading(triage, spoken) {
675
+ const verdict = await ask(triage, TRIAGE_PROMPT + '\n\nWHAT THE USER SAID:\n' +
676
+ spoken.map((message) => '- ' + clipText(message.content, TRIAGE_CLIP_CHARS)).join('\n'));
677
+ return parseObject(verdict)?.worth === true;
678
+ }
679
+ /** Run what the deep read found through the same gate as the day's extraction. */
680
+ #admitReplayed(scope, { session, said }, parsed) {
681
+ const candidates = parseCandidates(JSON.stringify(parsed?.memories ?? []));
682
+ if (!candidates.length)
683
+ return 0;
684
+ const admitted = admitCandidates(this.#store, {
685
+ candidates,
686
+ owner: scope.owner,
687
+ config: this.#config.memory,
688
+ // The user's words only, exactly as during the day.
689
+ sources: [said],
690
+ sourceSessionId: session.id,
691
+ sleepRunId: scope.runId,
692
+ });
693
+ if (admitted.rejected.length) {
694
+ this.#log.debug('Replay gate rejected candidates', {
695
+ session: session.id,
696
+ reasons: admitted.rejected.map((entry) => entry.reason).join(','),
697
+ });
698
+ }
699
+ return admitted.stored.length;
700
+ }
701
+ /**
702
+ * Write down what the user corrected. A correction has to be quotable too:
703
+ * "The user seemed unhappy" is not a correction, it is a mood.
704
+ */
705
+ #recordCorrections(scope, { session, messages, said }, parsed) {
706
+ let recorded = 0;
707
+ for (const { text, quote } of readCorrectionClaims(parsed)) {
708
+ if (!confirmedBy(quote, [said]))
709
+ continue;
710
+ // From the session reference to the turn reference (concept 4.2a,
711
+ // step 1): exactly one user message carries the quote, or there is
712
+ // no turn. `locateTurn` reads the same containment test that just
713
+ // admitted the quote, so the two can never disagree.
714
+ const located = locateTurn(messages, quote);
715
+ this.#store.addCorrection({
716
+ owner: scope.owner,
717
+ text,
718
+ quote,
719
+ sessionId: session.id,
720
+ ...(located.turnId ? { turnId: located.turnId } : {}),
721
+ });
722
+ recorded += 1;
723
+ }
724
+ return recorded;
725
+ }
651
726
  /** What the extractor must not write again: whatever this talk touches. */
652
727
  #knownFor(owner, text) {
653
728
  const matched = recall(this.#store, { text, owner, limit: 25, threshold: 0.05, touch: false, expand: false });
@@ -667,7 +742,7 @@ export class SleepRunner extends EventEmitter {
667
742
  #decay(runId, live) {
668
743
  const sleep = this.#config.memory.sleep;
669
744
  const now = Date.now();
670
- const cutoff = now - sleep.dormantAfterDays * 24 * 60 * 60 * 1000;
745
+ const cutoff = now - sleep.dormantAfterDays * DAY_MS;
671
746
  let count = 0;
672
747
  for (const memory of live) {
673
748
  if (isProtected(memory))
@@ -678,8 +753,10 @@ export class SleepRunner extends EventEmitter {
678
753
  const lastTouch = memory.lastAccessedAt ?? memory.createdAt;
679
754
  if (lastTouch > cutoff)
680
755
  continue;
681
- const recency = Math.pow(0.5, (now - memory.updatedAt) / (30 * 24 * 60 * 60 * 1000));
682
- const strength = 0.5 * memory.importance + 0.3 * memory.usefulness + 0.2 * recency;
756
+ const recency = Math.pow(0.5, (now - memory.updatedAt) / RECENCY_HALF_LIFE_MS);
757
+ const strength = IMPORTANCE_WEIGHT * memory.importance +
758
+ USEFULNESS_WEIGHT * memory.usefulness +
759
+ RECENCY_WEIGHT * recency;
683
760
  if (strength >= sleep.minStrength)
684
761
  continue;
685
762
  this.#store.sleepMemory(memory.id, { runId });
@@ -688,6 +765,46 @@ export class SleepRunner extends EventEmitter {
688
765
  return count;
689
766
  }
690
767
  /* ------------------------------ phase 2 ------------------------------ */
768
+ /**
769
+ * Everything the night may fold together: insights that restate one
770
+ * another first, then what the links and the entities say belongs
771
+ * together. A restated insight leaves the second pass, so one memory
772
+ * never stands in two clusters of the same night.
773
+ */
774
+ #cluster(owner, live) {
775
+ const restated = this.#restatedInsights(live);
776
+ const taken = new Set(restated.flatMap((cluster) => cluster.members.map((member) => member.id)));
777
+ const linked = this.#clusterByLinks(owner, live.filter((memory) => !taken.has(memory.id)));
778
+ return [...restated, ...linked];
779
+ }
780
+ /**
781
+ * Insights that say the same thing in other words, one cluster per
782
+ * observation. Their own source rather than a third kind of pair in
783
+ * `#clusterByLinks`: those clusters are unions over shared entities, which
784
+ * pull a dozen unrelated insights into one pile that is cut at eight and
785
+ * that no model will fold, while a restated observation is a small, tight
786
+ * group the condensation can actually merge. Oldest first, so the oldest
787
+ * wording seeds the group.
788
+ */
789
+ #restatedInsights(live) {
790
+ const groups = [];
791
+ for (const insight of live.filter((memory) => memory.kind === 'insight')) {
792
+ const tokens = normalizeTokens(insight.content);
793
+ const group = groups.find((candidate) => candidate.tokens.some((other) => similarity(tokens, other) >= INSIGHT_RESTATEMENT_SIMILARITY));
794
+ if (group) {
795
+ group.members.push(insight);
796
+ group.tokens.push(tokens);
797
+ }
798
+ else {
799
+ groups.push({ members: [insight], tokens: [tokens] });
800
+ }
801
+ }
802
+ return groups
803
+ .filter((group) => group.members.length >= 2)
804
+ .map((group) => ({ members: group.members.slice(0, CLUSTER_LIMIT), reason: 'restated' }))
805
+ .filter((cluster) => !cluster.members.every(isProtected))
806
+ .sort((a, b) => b.members.length - a.members.length);
807
+ }
691
808
  /**
692
809
  * Group what belongs together, without asking anyone.
693
810
  *
@@ -696,7 +813,7 @@ export class SleepRunner extends EventEmitter {
696
813
  * pairs into groups; groups of one are not groups, and anything over eight
697
814
  * is too big to judge in one call and gets cut.
698
815
  */
699
- #cluster(owner, live) {
816
+ #clusterByLinks(owner, live) {
700
817
  const byId = new Map(live.map((memory) => [memory.id, memory]));
701
818
  const parent = new Map();
702
819
  for (const memory of live)
@@ -715,7 +832,7 @@ export class SleepRunner extends EventEmitter {
715
832
  };
716
833
  const gatePairs = new Set();
717
834
  // Pairs the gate marked during the day.
718
- for (const edge of this.#store.listEdges(owner, 2000)) {
835
+ for (const edge of this.#store.listEdges(owner, CO_OCCURRENCE_SCAN)) {
719
836
  if (edge.relation !== 'co_occurs')
720
837
  continue;
721
838
  if (!byId.has(edge.srcId) || !byId.has(edge.dstId))
@@ -755,15 +872,18 @@ export class SleepRunner extends EventEmitter {
755
872
  groups.set(root, [memory]);
756
873
  }
757
874
  const clusters = [];
758
- for (const members of groups.values()) {
759
- if (members.length < 2)
875
+ for (const group of groups.values()) {
876
+ if (group.length < 2)
760
877
  continue;
761
- // A cluster made only of protected memories has nothing the night may do.
878
+ const members = group.slice(0, CLUSTER_LIMIT);
879
+ // A cluster made only of protected memories has nothing the night may
880
+ // do - and neither has one whose first eight are, which would only
881
+ // cost a call that retires nobody.
762
882
  if (members.every(isProtected))
763
883
  continue;
764
884
  clusters.push({
765
- members: members.slice(0, 8),
766
- reason: members.some((memory) => gatePairs.has(memory.id)) ? 'gate' : 'entities',
885
+ members,
886
+ reason: group.some((memory) => gatePairs.has(memory.id)) ? 'gate' : 'entities',
767
887
  });
768
888
  }
769
889
  // Biggest first: the largest pile is where condensing pays most.
@@ -771,10 +891,8 @@ export class SleepRunner extends EventEmitter {
771
891
  }
772
892
  /* ------------------------------ phase 3 ------------------------------ */
773
893
  /** Fold each cluster into one sentence, or leave it alone. One call each. */
774
- async #condense(provider, model, owner, runId, clusters, signal, budget) {
775
- let merged = 0;
776
- let retired = 0;
777
- let calls = 0;
894
+ async #condense(scope, clusters, budget) {
895
+ const result = { merged: 0, retired: 0, calls: 0 };
778
896
  /**
779
897
  * Victim id to the condensed row that took its place - the one hop the
780
898
  * `merge` label source is allowed to walk (concept 4.2c, S7). Collected
@@ -784,88 +902,61 @@ export class SleepRunner extends EventEmitter {
784
902
  */
785
903
  const superseded = new Map();
786
904
  for (const cluster of clusters) {
787
- if (calls >= budget || signal.aborted)
905
+ if (result.calls >= budget || scope.voice.signal.aborted)
788
906
  break;
789
- const numbered = cluster.members
790
- .map((memory, index) => {
791
- const date = new Date(memory.createdAt).toISOString().slice(0, 10);
792
- const lock = isProtected(memory) ? ' [protected]' : '';
793
- return (index + 1 + '. [' + memory.kind + ', ' + memory.importance.toFixed(2) + ', ' + date + ']' +
794
- lock + ' ' + memory.content);
795
- })
796
- .join('\n');
797
- const raw = await ask(provider, CONDENSE_PROMPT + '\n\nMEMORIES:\n' + numbered, model, signal);
798
- calls += 1;
799
- const parsed = parseObject(raw);
800
- if (!parsed || parsed.merge !== true)
801
- continue;
802
- const content = typeof parsed.content === 'string' ? parsed.content.trim() : '';
803
- if (content.length < 8 || content.length > 500)
804
- continue;
805
- const indices = Array.isArray(parsed.supersedes)
806
- ? parsed.supersedes
807
- .map((value) => Number(value))
808
- .filter((value) => Number.isInteger(value) && value >= 1 && value <= cluster.members.length)
809
- : [];
810
- const victims = [...new Set(indices)]
811
- .map((index) => cluster.members[index - 1])
812
- // Protected memories are named in the prompt so the model sees the
813
- // whole picture, but it may not retire them. This is the enforcement.
814
- .filter((memory) => !isProtected(memory));
815
- if (!victims.length)
907
+ result.calls += 1;
908
+ const raw = await ask(scope.voice, CONDENSE_PROMPT + '\n\nMEMORIES:\n' + describeCluster(cluster.members));
909
+ const verdict = readMergeVerdict(parseObject(raw), cluster.members);
910
+ if (!verdict)
816
911
  continue;
817
- // Replacing one memory with a near-identical one gains nothing and
818
- // costs its history.
819
- if (victims.length < 2 &&
820
- similarity(normalizeTokens(content), normalizeTokens(victims[0].content)) > 0.9) {
821
- continue;
822
- }
823
- const kind = MEMORY_KINDS.includes(parsed.kind)
824
- ? parsed.kind
825
- : 'summary';
826
- const importance = clamp01(typeof parsed.importance === 'number'
827
- ? parsed.importance
828
- : Math.max(...victims.map((memory) => memory.importance)));
829
- const tags = [
830
- ...new Set([
831
- ...victims.flatMap((memory) => memory.tags),
832
- ...(Array.isArray(parsed.tags)
833
- ? parsed.tags.filter((tag) => typeof tag === 'string')
834
- : []),
835
- ]),
836
- ].slice(0, 8);
837
- const record = this.#store.upsertMemory({
838
- kind,
839
- content,
840
- tags,
841
- importance,
912
+ const { into, retired } = this.#writeCondensed(scope, verdict);
913
+ for (const id of retired)
914
+ superseded.set(id, into);
915
+ result.retired += retired.length;
916
+ result.merged += 1;
917
+ }
918
+ const written = this.#dreaming.writeMergeLabels(scope.owner, superseded);
919
+ return { ...result, labels: written.labels, labelFailures: written.failed };
920
+ }
921
+ /** Write the condensed sentence and file its sources away, each under it. */
922
+ #writeCondensed(scope, verdict) {
923
+ const { owner, runId } = scope;
924
+ const record = this.#store.upsertMemory({
925
+ kind: verdict.kind,
926
+ content: verdict.content,
927
+ tags: verdict.tags,
928
+ importance: verdict.importance,
929
+ owner,
930
+ origin: 'sleep',
931
+ sleepRunId: runId,
932
+ });
933
+ // `upsertMemory` reinforces a row that already says exactly this sentence,
934
+ // and that row can be one of the memories being replaced. It then IS the
935
+ // condensed memory: filing it away as superseded by itself would lose
936
+ // the sentence and its sources together.
937
+ const victims = verdict.victims.filter((victim) => victim.id !== record.id);
938
+ // The condensed memory inherits the entities of everything it replaces,
939
+ // so the graph keeps its shape when the originals fall asleep.
940
+ for (const victim of victims) {
941
+ this.#carryEntities(victim.id, record.id);
942
+ this.#store.addEdge({
842
943
  owner,
944
+ srcId: record.id,
945
+ dstId: victim.id,
946
+ relation: 'supersedes',
947
+ weight: 1,
843
948
  origin: 'sleep',
844
- sleepRunId: runId,
949
+ runId,
845
950
  });
846
- // The condensed memory inherits the entities of everything it replaces,
847
- // so the graph keeps its shape when the originals fall asleep.
848
- for (const victim of victims) {
849
- for (const entity of this.#store.entitiesFor(victim.id)) {
850
- this.#store.linkEntity(record.id, entity.id);
851
- }
852
- this.#store.addEdge({
853
- owner,
854
- srcId: record.id,
855
- dstId: victim.id,
856
- relation: 'supersedes',
857
- weight: 1,
858
- origin: 'sleep',
859
- runId,
860
- });
861
- this.#store.sleepMemory(victim.id, { runId, supersededBy: record.id });
862
- superseded.set(victim.id, record.id);
863
- retired += 1;
864
- }
865
- merged += 1;
951
+ this.#store.sleepMemory(victim.id, { runId, supersededBy: record.id });
952
+ }
953
+ return { into: record.id, retired: victims.map((victim) => victim.id) };
954
+ }
955
+ /** Link every entity of one memory to another, so the graph follows a rewrite. */
956
+ #carryEntities(fromMemoryId, toMemoryId) {
957
+ for (const entity of this.#store.entitiesFor(fromMemoryId)) {
958
+ this.#store.linkEntity(toMemoryId, entity.id);
866
959
  }
867
- const written = this.#writeMergeLabels(owner, superseded);
868
- return { merged, retired, calls, labels: written.labels, labelFailures: written.failed };
869
960
  }
870
961
  /* --------------------- deep sleep: the decision --------------------- */
871
962
  /**
@@ -882,106 +973,91 @@ export class SleepRunner extends EventEmitter {
882
973
  * protected, that side wins: what the user wrote themselves outranks
883
974
  * anything an extraction inferred from a conversation.
884
975
  */
885
- async #resolve(provider, model, owner, runId, signal, budget) {
886
- let resolved = 0;
887
- let retired = 0;
888
- let merged = 0;
889
- let calls = 0;
890
- const open = this.#store
891
- .listEdges(owner, 500)
892
- .filter((edge) => edge.relation === 'contradicts')
893
- .map((edge) => ({
894
- edge,
895
- a: this.#store.getMemory(edge.srcId),
896
- b: this.#store.getMemory(edge.dstId),
897
- }))
898
- // A pair with a sleeping side is already settled; skipping it is also
899
- // what stops the same contradiction being re-decided every night.
900
- .filter((pair) => Boolean(pair.a && pair.b) &&
901
- !pair.a.dormantAt && !pair.b.dormantAt &&
902
- !pair.a.forgotten && !pair.b.forgotten);
903
- for (const { a, b } of open) {
904
- if (signal.aborted)
976
+ async #resolve(scope, budget) {
977
+ const result = { resolved: 0, retired: 0, merged: 0, calls: 0 };
978
+ for (const { edge } of this.#openContradictions(scope.owner)) {
979
+ if (scope.voice.signal.aborted)
905
980
  break;
981
+ const sides = this.#openSides(edge);
982
+ if (!sides)
983
+ continue;
984
+ const { a, b } = sides;
906
985
  // Both untouchable: the user has to sort this one out.
907
986
  if (isProtected(a) && isProtected(b))
908
987
  continue;
909
988
  // Exactly one untouchable: it wins, and it costs nothing to know that.
910
989
  if (isProtected(a) || isProtected(b)) {
911
990
  const winner = isProtected(a) ? a : b;
912
- const loser = isProtected(a) ? b : a;
913
- this.#retire(owner, runId, loser, winner);
914
- resolved += 1;
915
- retired += 1;
991
+ this.#retire(scope, winner === a ? b : a, winner);
992
+ result.resolved += 1;
993
+ result.retired += 1;
916
994
  continue;
917
995
  }
918
- if (calls >= budget)
996
+ if (result.calls >= budget)
919
997
  break;
920
- const pair = '1. [' + a.kind + ', ' + new Date(a.createdAt).toISOString().slice(0, 10) + '] ' + a.content +
921
- '\n2. [' + b.kind + ', ' + new Date(b.createdAt).toISOString().slice(0, 10) + '] ' + b.content;
922
- const raw = await ask(provider, RESOLVE_PROMPT + '\n\nTHE TWO SENTENCES:\n' + pair, model, signal);
923
- calls += 1;
924
- const parsed = parseObject(raw);
925
- if (!parsed)
926
- continue;
927
- const decision = typeof parsed.decision === 'string' ? parsed.decision : '';
928
- if (decision === 'first' || decision === 'second') {
929
- const winner = decision === 'first' ? a : b;
930
- const loser = decision === 'first' ? b : a;
931
- this.#retire(owner, runId, loser, winner);
932
- resolved += 1;
933
- retired += 1;
934
- continue;
935
- }
936
- if (decision === 'merge') {
937
- const content = typeof parsed.content === 'string' ? parsed.content.trim() : '';
938
- if (content.length < 8 || content.length > 500)
939
- continue;
940
- const record = this.#store.upsertMemory({
941
- kind: a.kind,
942
- content,
943
- tags: [...new Set([...a.tags, ...b.tags])].slice(0, 8),
944
- importance: clamp01(Math.max(a.importance, b.importance)),
945
- owner,
946
- origin: 'sleep',
947
- sleepRunId: runId,
948
- });
949
- for (const loser of [a, b]) {
950
- for (const entity of this.#store.entitiesFor(loser.id)) {
951
- this.#store.linkEntity(record.id, entity.id);
952
- }
953
- this.#retire(owner, runId, loser, record);
954
- retired += 1;
955
- }
956
- resolved += 1;
957
- merged += 1;
958
- continue;
959
- }
960
- // "both": not a real contradiction after all. Drop the claim rather
961
- // than leaving a red line in the graph that says something untrue.
962
- if (decision === 'both') {
963
- const edge = this.#store
964
- .edgesFrom([a.id, b.id], ['contradicts'])
965
- .find((candidate) => candidate.dstId === b.id || candidate.dstId === a.id);
966
- if (edge)
967
- this.#store.deleteEdge(edge.id);
968
- resolved += 1;
969
- }
998
+ result.calls += 1;
999
+ const settlement = await this.#askSettlement(scope, { edge, a, b });
1000
+ result.resolved += settlement.resolved;
1001
+ result.retired += settlement.retired;
1002
+ result.merged += settlement.merged;
1003
+ }
1004
+ return result;
1005
+ }
1006
+ /** Put one contradiction to the model and act on its decision. */
1007
+ async #askSettlement(scope, { edge, a, b }) {
1008
+ const raw = await ask(scope.voice, RESOLVE_PROMPT + '\n\nTHE TWO SENTENCES:\n' + describePair(a, b));
1009
+ const parsed = parseObject(raw);
1010
+ const decision = typeof parsed?.decision === 'string' ? parsed.decision : '';
1011
+ if (decision === 'first' || decision === 'second') {
1012
+ const winner = decision === 'first' ? a : b;
1013
+ this.#retire(scope, winner === a ? b : a, winner);
1014
+ return { resolved: 1, retired: 1, merged: 0 };
1015
+ }
1016
+ if (decision === 'merge')
1017
+ return this.#mergeContradiction(scope, a, b, parsed?.content);
1018
+ if (decision === 'both') {
1019
+ // Not a real contradiction after all. Drop the claim rather than
1020
+ // leaving a red line in the graph that says something untrue.
1021
+ this.#store.deleteEdge(edge.id);
1022
+ return { resolved: 1, retired: 0, merged: 0 };
970
1023
  }
971
- return { resolved, retired, merged, calls };
1024
+ return UNSETTLED;
1025
+ }
1026
+ /** Both sides were half right: one new sentence takes both places. */
1027
+ #mergeContradiction(scope, a, b, content) {
1028
+ const merged = readCondensed(content);
1029
+ if (!merged)
1030
+ return UNSETTLED;
1031
+ const record = this.#store.upsertMemory({
1032
+ kind: a.kind,
1033
+ content: merged,
1034
+ tags: unionTags([...a.tags, ...b.tags], MAX_MERGED_TAGS),
1035
+ importance: clamp01(Math.max(a.importance, b.importance)),
1036
+ owner: scope.owner,
1037
+ origin: 'sleep',
1038
+ sleepRunId: scope.runId,
1039
+ });
1040
+ // As in `#writeCondensed`: when the sentence is one a side already says,
1041
+ // that side stands as the merged memory and only the other is filed away.
1042
+ const losers = [a, b].filter((side) => side.id !== record.id);
1043
+ for (const loser of losers) {
1044
+ this.#carryEntities(loser.id, record.id);
1045
+ this.#retire(scope, loser, record);
1046
+ }
1047
+ return { resolved: 1, retired: losers.length, merged: 1 };
972
1048
  }
973
1049
  /** File one side of a settled pair away, with the trail that says why. */
974
- #retire(owner, runId, loser, winner) {
1050
+ #retire(scope, loser, winner) {
975
1051
  this.#store.addEdge({
976
- owner,
1052
+ owner: scope.owner,
977
1053
  srcId: winner.id,
978
1054
  dstId: loser.id,
979
1055
  relation: 'supersedes',
980
1056
  weight: 1,
981
1057
  origin: 'sleep',
982
- runId,
1058
+ runId: scope.runId,
983
1059
  });
984
- this.#store.sleepMemory(loser.id, { runId, supersededBy: winner.id });
1060
+ this.#store.sleepMemory(loser.id, { runId: scope.runId, supersededBy: winner.id });
985
1061
  }
986
1062
  /* ------------------------------ phase 4 ------------------------------ */
987
1063
  /**
@@ -990,15 +1066,37 @@ export class SleepRunner extends EventEmitter {
990
1066
  * reported; deciding which side is right is the user's call, never the
991
1067
  * night's.
992
1068
  */
993
- async #link(provider, model, owner, runId, signal, budget) {
994
- const since = this.#store.lastSleepAt(owner);
995
- const fresh = this.#store
996
- .listMemories({ owner, since: since || undefined, limit: 150, includeDormant: false })
997
- .filter((memory) => !memory.supersededBy);
1069
+ async #link(scope, budget) {
1070
+ const result = { edges: 0, conflicts: 0, calls: 0 };
1071
+ for (const portion of chunk(this.#linkPool(scope.owner), LINK_PORTION)) {
1072
+ if (result.calls >= budget || scope.voice.signal.aborted)
1073
+ break;
1074
+ if (portion.length < 2)
1075
+ continue;
1076
+ result.calls += 1;
1077
+ const raw = await ask(scope.voice, LINK_PROMPT + '\n\nMEMORIES:\n' + numberMemories(portion));
1078
+ const parsed = parseObject(raw);
1079
+ if (!parsed)
1080
+ continue;
1081
+ const drawn = this.#drawEdges(scope, parsed, portion);
1082
+ result.edges += drawn.edges;
1083
+ result.conflicts += drawn.conflicts;
1084
+ // Entity clean-up rides along in the same reply: a name that is really
1085
+ // a person or a tool stops being an anonymous topic.
1086
+ this.#retypeEntities(scope.owner, parsed);
1087
+ this.#mergeAliases(scope.owner, parsed);
1088
+ }
1089
+ return result;
1090
+ }
1091
+ /**
1092
+ * The new memories plus the neighbours they might relate to, so
1093
+ * "contradicts" can actually be found rather than only guessed. Empty when
1094
+ * there is nothing new to relate.
1095
+ */
1096
+ #linkPool(owner) {
1097
+ const fresh = this.#freshMemories(owner);
998
1098
  if (fresh.length < 2)
999
- return { edges: 0, conflicts: 0, calls: 0 };
1000
- // Give the model the new memories plus the neighbours they might relate
1001
- // to, so "contradicts" can actually be found rather than only guessed.
1099
+ return [];
1002
1100
  const entityIds = [
1003
1101
  ...new Set(fresh.flatMap((memory) => this.#store.entitiesFor(memory.id).map((entity) => entity.id))),
1004
1102
  ];
@@ -1007,91 +1105,51 @@ export class SleepRunner extends EventEmitter {
1007
1105
  // would otherwise walk the night into another bank.
1008
1106
  owner,
1009
1107
  exclude: fresh.map((memory) => memory.id),
1010
- limit: 40,
1108
+ limit: NEIGHBOUR_LIMIT,
1011
1109
  });
1012
- const pool = [...fresh, ...neighbours];
1013
- const relations = ['refines', 'contradicts', 'caused_by'];
1014
- const kinds = ['person', 'project', 'tool', 'place', 'org', 'topic'];
1110
+ return [...fresh, ...neighbours];
1111
+ }
1112
+ #drawEdges(scope, parsed, portion) {
1015
1113
  let edges = 0;
1016
1114
  let conflicts = 0;
1017
- let calls = 0;
1018
- for (const batch of chunk(pool, 25)) {
1019
- if (calls >= budget || signal.aborted)
1020
- break;
1021
- if (batch.length < 2)
1115
+ for (const proposed of readProposedEdges(parsed, portion)) {
1116
+ const edge = this.#store.addEdge({
1117
+ owner: scope.owner,
1118
+ srcId: proposed.from.id,
1119
+ dstId: proposed.to.id,
1120
+ relation: proposed.relation,
1121
+ weight: proposed.weight,
1122
+ origin: 'sleep',
1123
+ runId: scope.runId,
1124
+ });
1125
+ if (!edge)
1022
1126
  continue;
1023
- const numbered = batch
1024
- .map((memory, index) => index + 1 + '. [' + memory.kind + '] ' + memory.content)
1025
- .join('\n');
1026
- const raw = await ask(provider, LINK_PROMPT + '\n\nMEMORIES:\n' + numbered, model, signal);
1027
- calls += 1;
1028
- const parsed = parseObject(raw);
1029
- if (!parsed)
1127
+ edges += 1;
1128
+ if (proposed.relation === 'contradicts')
1129
+ conflicts += 1;
1130
+ }
1131
+ return { edges, conflicts };
1132
+ }
1133
+ #retypeEntities(owner, parsed) {
1134
+ for (const { name, kind } of readEntityKinds(parsed)) {
1135
+ const existing = this.#store.findEntity(owner, name);
1136
+ if (!existing)
1030
1137
  continue;
1031
- const proposed = Array.isArray(parsed.edges) ? parsed.edges : [];
1032
- for (const entry of proposed.slice(0, 12)) {
1033
- if (!entry || typeof entry !== 'object')
1034
- continue;
1035
- const row = entry;
1036
- const from = Number(row.from);
1037
- const to = Number(row.to);
1038
- const relation = row.relation;
1039
- if (!relations.includes(relation))
1040
- continue;
1041
- if (!Number.isInteger(from) || !Number.isInteger(to))
1042
- continue;
1043
- if (from < 1 || to < 1 || from > batch.length || to > batch.length || from === to)
1044
- continue;
1045
- const edge = this.#store.addEdge({
1046
- owner,
1047
- srcId: batch[from - 1].id,
1048
- dstId: batch[to - 1].id,
1049
- relation,
1050
- weight: clamp01(typeof row.weight === 'number' ? row.weight : 0.6),
1051
- origin: 'sleep',
1052
- runId,
1053
- });
1054
- if (!edge)
1055
- continue;
1056
- edges += 1;
1057
- if (relation === 'contradicts')
1058
- conflicts += 1;
1059
- }
1060
- // Entity clean-up rides along in the same reply: a name that is really
1061
- // a person or a tool stops being an anonymous topic.
1062
- const named = Array.isArray(parsed.entities) ? parsed.entities : [];
1063
- for (const entry of named) {
1064
- if (!entry || typeof entry !== 'object')
1065
- continue;
1066
- const row = entry;
1067
- const name = typeof row.name === 'string' ? row.name.trim() : '';
1068
- const kind = row.kind;
1069
- if (!name || !entitySlug(name) || !kinds.includes(kind))
1070
- continue;
1071
- const existing = this.#store.findEntity(owner, name);
1072
- if (!existing)
1073
- continue;
1074
- this.#store.upsertEntity({ owner, name: existing.name, kind });
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
- }
1138
+ this.#store.upsertEntity({ owner, name: existing.name, kind });
1139
+ }
1140
+ }
1141
+ /**
1142
+ * The other half of a tidy graph: two names that mean one thing
1143
+ * ("Rookery", "Rookery-Agent") become one node, links and all. A merge that
1144
+ * would not hold - one side missing, both the same - is refused by the
1145
+ * store and costs the night nothing.
1146
+ */
1147
+ #mergeAliases(owner, parsed) {
1148
+ for (const { from, into } of readAliases(parsed)) {
1149
+ if (this.#store.mergeEntities(owner, from, into)) {
1150
+ this.#log.info('Merged duplicate entities', { owner, from, into });
1092
1151
  }
1093
1152
  }
1094
- return { edges, conflicts, calls };
1095
1153
  }
1096
1154
  /* ------------------------------ phase 5 ------------------------------ */
1097
1155
  /**
@@ -1108,117 +1166,79 @@ export class SleepRunner extends EventEmitter {
1108
1166
  * configured `insights` count caps the night's total, whichever angle
1109
1167
  * produced them.
1110
1168
  */
1111
- async #reflect(provider, model, owner, runId, signal, budget) {
1169
+ async #reflect(scope, budget) {
1112
1170
  const wanted = this.#config.memory.sleep.insights;
1113
- if (wanted <= 0 || budget <= 0 || signal.aborted)
1114
- return { written: 0, edges: 0, calls: 0 };
1115
- const window = this.#config.memory.sleep.insightWindowDays;
1116
- const since = Date.now() - window * 24 * 60 * 60 * 1000;
1117
- const recent = this.#store
1118
- .listMemories({ owner, since, limit: 80, includeDormant: false })
1119
- .filter((memory) => memory.kind !== 'insight');
1120
- if (recent.length < 4)
1121
- return { written: 0, edges: 0, calls: 0 };
1122
- const entities = this.#store.listEntities({ owner, limit: 12, minMentions: 2 });
1123
- const numbered = recent
1124
- .map((memory, index) => index + 1 + '. [' + memory.kind + '] ' + memory.content)
1125
- .join('\n');
1126
- const topics = entities.length
1127
- ? '\n\nCOMMON TOPICS:\n' + entities.map((entity) => '- ' + entity.name).join('\n')
1128
- : '';
1129
- let written = 0;
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)
1171
+ const result = { written: 0, edges: 0, calls: 0 };
1172
+ if (wanted <= 0 || budget <= 0 || scope.voice.signal.aborted)
1173
+ return result;
1174
+ const { owner } = scope;
1175
+ const recent = this.#reflectPool(owner);
1176
+ if (recent.length < MIN_REFLECT_POOL)
1177
+ return result;
1178
+ // An insight that is already on record is not knowledge gained, and
1179
+ // neither is one worded differently. Two guards, because a model told
1180
+ // to say something new still rewords last night's pattern when the pool
1181
+ // is last night's pool plus a day: the pass only runs when something
1182
+ // new is in the pool, and an insight has to stand on at least one such
1183
+ // memory. Both angles write against the same list, so a sentence from
1184
+ // earlier tonight is a restatement too.
1185
+ const onRecord = this.#insightsOnRecord(owner);
1186
+ const reflectedUntil = newestCreation(onRecord);
1187
+ if (!recent.some((memory) => memory.createdAt > reflectedUntil))
1188
+ return result;
1189
+ const stated = onRecord.map((insight) => normalizeTokens(insight.content));
1190
+ const topics = this.#store.listEntities({ owner, limit: COMMON_TOPICS, minMentions: 2 });
1191
+ const material = '\n\nMEMORIES FROM RECENT DAYS:\n' + numberMemories(recent) +
1192
+ (topics.length ? '\n\nCOMMON TOPICS:\n' + topics.map((entity) => '- ' + entity.name).join('\n') : '') +
1193
+ (onRecord.length ? '\n\nALREADY ON RECORD:\n' + listNewestInsights(onRecord) : '');
1194
+ for (const angle of INSIGHT_ANGLES) {
1195
+ if (result.calls >= budget || result.written >= wanted || scope.voice.signal.aborted)
1141
1196
  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))
1197
+ const room = wanted - result.written;
1198
+ const prompt = angle === 'user' ? INSIGHT_USER_PROMPT : INSIGHT_WORK_PROMPT;
1199
+ result.calls += 1;
1200
+ const raw = await ask(scope.voice, prompt.replace('{{MAX}}', String(room)) + material);
1201
+ for (const draft of readInsightDrafts(parseObject(raw), recent, room)) {
1202
+ if (!standsOnNews(draft, reflectedUntil) || restates(draft.content, stated))
1155
1203
  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;
1204
+ result.edges += this.#writeInsight(scope, draft);
1205
+ stated.push(normalizeTokens(draft.content));
1206
+ result.written += 1;
1192
1207
  }
1193
1208
  }
1194
- return { written, edges, calls };
1209
+ return result;
1210
+ }
1211
+ /** Write one insight and tie it to the memories it stands on; how many edges that made. */
1212
+ #writeInsight(scope, draft) {
1213
+ const { owner, runId } = scope;
1214
+ const record = this.#store.upsertMemory({
1215
+ kind: 'insight',
1216
+ content: draft.content,
1217
+ tags: unionTags(draft.evidence.flatMap((memory) => memory.tags), MAX_INSIGHT_TAGS),
1218
+ importance: draft.importance,
1219
+ owner,
1220
+ origin: 'sleep',
1221
+ sleepRunId: runId,
1222
+ });
1223
+ let edges = 0;
1224
+ for (const memory of draft.evidence) {
1225
+ this.#carryEntities(memory.id, record.id);
1226
+ // The insight refines its evidence, so recall can walk from either end.
1227
+ const edge = this.#store.addEdge({
1228
+ owner,
1229
+ srcId: record.id,
1230
+ dstId: memory.id,
1231
+ relation: 'refines',
1232
+ weight: INSIGHT_EDGE_WEIGHT,
1233
+ origin: 'sleep',
1234
+ runId,
1235
+ });
1236
+ if (edge)
1237
+ edges += 1;
1238
+ }
1239
+ return edges;
1195
1240
  }
1196
1241
  /* ------------------------------ 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
1242
  /**
1223
1243
  * Every skill of this bank that has a live reason to be looked at, worst
1224
1244
  * first. Pure database and lexical work - no model - so the demand
@@ -1239,14 +1259,14 @@ export class SleepRunner extends EventEmitter {
1239
1259
  // each is matched against the shelf by wording - the same lexical judgement
1240
1260
  // the rest of this file uses, and enough to tell "always run the tests
1241
1261
  // first" from a remark about the mail client.
1242
- const open = this.#store.openCorrections(owner, 20);
1262
+ const open = this.#store.openCorrections(owner, OPEN_CORRECTIONS);
1243
1263
  return mine
1244
1264
  .map((skill) => {
1245
1265
  // Looking counts as clearing, so the window opens at whichever came
1246
1266
  // last: the file being written, or the night last reading it.
1247
1267
  const since = Math.max(skill.updatedAt, this.#store.lastSkillReviewAt(skill.name));
1248
1268
  const changed = this.#store.changedSkillSources(skill.name, since);
1249
- const failures = this.#store.failedRunsForSkill(skill.name, since, 3);
1269
+ const failures = this.#store.failedRunsForSkill(skill.name, since, FAILED_RUNS_SHOWN);
1250
1270
  // Name and description only, never the body. What a skill is ABOUT is
1251
1271
  // its subject line; the body is implementation detail, and every extra
1252
1272
  // step in it dilutes the overlap until nothing matches. A correction
@@ -1261,82 +1281,92 @@ export class SleepRunner extends EventEmitter {
1261
1281
  .filter((entry) => entry.changed.length > 0 || entry.failures.length > 0 || entry.corrections.length > 0)
1262
1282
  .sort((a, b) => weigh(b) - weigh(a));
1263
1283
  }
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 };
1284
+ /**
1285
+ * Repair before invention.
1286
+ *
1287
+ * A skill is written once and then followed for months, which makes a
1288
+ * stale one worse than none at all: it does not merely fail to help, it
1289
+ * confidently sends whoever opens it down a path that no longer exists. So
1290
+ * before the night considers writing anything new, it asks which of the
1291
+ * procedures it already owns have had the ground move under them.
1292
+ *
1293
+ * Two signals, both already in the database and neither of them guesswork:
1294
+ *
1295
+ * sources - the memories a skill was distilled from. One of them being
1296
+ * put to sleep, decided against in a contradiction, or edited
1297
+ * means the skill was written from something that no longer
1298
+ * reads that way.
1299
+ * failures - runs that had the skill open and then failed. The error text
1300
+ * comes along, because "the run failed" locates nothing while
1301
+ * "no such script: build:core" points at the exact line that
1302
+ * is lying.
1303
+ *
1304
+ * A trigger is consumed by being looked at, whatever the outcome: every
1305
+ * review leaves a snapshot, and the next night's window starts there.
1306
+ * Otherwise one dormant memory would drag the same skill in front of the
1307
+ * model every night for ever, at the cost of a call each time.
1308
+ */
1309
+ async #revise(scope, budget) {
1310
+ const result = { written: 0, calls: 0 };
1311
+ if (budget <= 0 || scope.voice.signal.aborted)
1312
+ return result;
1271
1313
  const consumed = new Set();
1272
- let written = 0;
1273
- let calls = 0;
1274
- for (const suspect of suspects) {
1275
- if (signal.aborted)
1314
+ for (const suspect of this.#skillSuspects(scope.owner).slice(0, budget)) {
1315
+ if (scope.voice.signal.aborted)
1276
1316
  break;
1277
- const { skill, changed, failures, corrections } = suspect;
1278
- for (const entry of corrections)
1317
+ for (const entry of suspect.corrections)
1279
1318
  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
- }
1319
+ result.calls += 1;
1320
+ if (await this.#reviseSkill(scope, suspect))
1321
+ result.written += 1;
1335
1322
  }
1336
1323
  // Looked at is looked at, whatever came of it: a correction that has been
1337
1324
  // weighed must not be weighed again tomorrow.
1338
1325
  this.#store.consumeCorrections([...consumed]);
1339
- return { written, calls };
1326
+ return result;
1327
+ }
1328
+ /** Put one suspect skill in front of the model; whether it was rewritten. */
1329
+ async #reviseSkill(scope, suspect) {
1330
+ const { owner, runId } = scope;
1331
+ const { skill, changed, failures } = suspect;
1332
+ const raw = await ask(scope.voice, REVISE_PROMPT +
1333
+ '\n\nTHE SKILL AS IT READS NOW:\nname: ' + skill.name +
1334
+ '\ndescription: ' + skill.description +
1335
+ '\n\n' + skill.body +
1336
+ '\n\nWHAT HAS CHANGED SINCE IT WAS WRITTEN:\n' + describeWhy(suspect));
1337
+ const revision = readRevision(parseObject(raw), skill);
1338
+ const store = new SkillStore(this.#config.skillsDir);
1339
+ if (!revision) {
1340
+ // Reviewed and left alone. The snapshot carries no run id: there is
1341
+ // nothing for undo to take back, but the timestamp still closes the
1342
+ // window so tomorrow does not ask the same question again.
1343
+ this.#store.snapshotSkill({ skill: skill.name, content: store.raw(skill.name) });
1344
+ this.#settleSources(skill.name, owner, changed);
1345
+ this.#log.info('Sleep reviewed a skill and left it', { owner, skill: skill.name });
1346
+ return false;
1347
+ }
1348
+ try {
1349
+ this.#store.snapshotSkill({ skill: skill.name, content: store.raw(skill.name), sleepRunId: runId });
1350
+ store.save({
1351
+ name: skill.name,
1352
+ description: revision.description,
1353
+ body: revision.body,
1354
+ audience: skill.audience,
1355
+ origin: 'sleep',
1356
+ });
1357
+ this.#settleSources(skill.name, owner, changed);
1358
+ this.#log.info('Sleep revised a skill', {
1359
+ owner,
1360
+ skill: skill.name,
1361
+ changed: changed.length,
1362
+ failures: failures.length,
1363
+ });
1364
+ return true;
1365
+ }
1366
+ catch (cause) {
1367
+ this.#log.info('Sleep left a skill alone', { owner, skill: skill.name, reason: cause.message });
1368
+ return false;
1369
+ }
1340
1370
  }
1341
1371
  /**
1342
1372
  * Re-point a skill at the memories that hold now.
@@ -1378,75 +1408,62 @@ export class SleepRunner extends EventEmitter {
1378
1408
  * memories. And a skill the user wrote is never overwritten - the store
1379
1409
  * refuses, and the refusal is logged rather than worked around.
1380
1410
  */
1381
- async #practise(provider, model, owner, runId, signal, budget) {
1411
+ async #practise(scope, budget) {
1382
1412
  const wanted = this.#config.memory.sleep.skills;
1383
- if (wanted <= 0 || budget <= 0 || signal.aborted)
1384
- return { written: 0, calls: 0 };
1413
+ const none = { written: 0, calls: 0 };
1414
+ if (wanted <= 0 || budget <= 0 || scope.voice.signal.aborted)
1415
+ return none;
1385
1416
  // What this bank holds, strongest first. Insights are deliberately in:
1386
1417
  // they are precisely the "this keeps happening" observations a procedure
1387
1418
  // grows out of.
1388
1419
  const live = this.#store
1389
- .listMemories({ owner, limit: 60, includeDormant: false })
1420
+ .listMemories({ owner: scope.owner, limit: PRACTISE_POOL_LIMIT, includeDormant: false })
1390
1421
  .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');
1422
+ if (live.length < MIN_PRACTISE_MEMORIES)
1423
+ return none;
1424
+ const existing = new SkillStore(this.#config.skillsDir).for(scope.owner === ASSISTANT_MEMORY_OWNER ? 'assistant' : 'agent');
1401
1425
  const shelf = existing.length
1402
1426
  ? existing.map((skill) => '- ' + skill.name + ' (' + skill.origin + '): ' + skill.description).join('\n')
1403
1427
  : '(nothing yet)';
1404
- const raw = await ask(provider, SKILL_PROMPT.replace('{{MAX}}', String(wanted)) +
1428
+ const raw = await ask(scope.voice, SKILL_PROMPT.replace('{{MAX}}', String(wanted)) +
1405
1429
  '\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 : [];
1430
+ '\n\nWHAT THIS MEMORY HOLDS:\n' + numberMemories(live));
1409
1431
  let written = 0;
1410
- for (const entry of proposed.slice(0, wanted)) {
1411
- if (!entry || typeof entry !== 'object')
1412
- continue;
1413
- const row = entry;
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)
1421
- continue;
1422
- const evidence = Array.isArray(row.evidence)
1423
- ? [...new Set(row.evidence.map((value) => Number(value)))].filter((value) => Number.isInteger(value) && value >= 1 && value <= live.length)
1424
- : [];
1425
- // A procedure standing on fewer than three memories is one anecdote
1426
- // with ambitions.
1427
- if (evidence.length < 3)
1428
- continue;
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 });
1432
+ for (const draft of readSkillDrafts(parseObject(raw), live.length, wanted)) {
1433
+ const sourceIds = draft.evidence.map((index) => live[index - 1].id);
1434
+ if (this.#writeSkill(scope, draft, sourceIds))
1440
1435
  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
1436
  }
1448
1437
  return { written, calls: 1 };
1449
1438
  }
1439
+ /** Write one new skill and remember what it stands on; whether the store took it. */
1440
+ #writeSkill(scope, draft, sourceIds) {
1441
+ const { owner, runId } = scope;
1442
+ const { name, description, body } = draft;
1443
+ // Whose shelf this is. The assistant's bank writes skills the assistant
1444
+ // may open; an agent's bank writes skills for agents.
1445
+ const audience = owner === ASSISTANT_MEMORY_OWNER ? 'assistant' : 'agents';
1446
+ const store = new SkillStore(this.#config.skillsDir);
1447
+ try {
1448
+ // The snapshot goes in first and carries the run id: writing a skill
1449
+ // is part of the night, so undoing the night has to take it back.
1450
+ // Null content says the skill did not exist, which is how undo knows
1451
+ // to delete rather than restore.
1452
+ this.#store.snapshotSkill({ skill: name, content: store.raw(name), sleepRunId: runId });
1453
+ const skill = store.save({ name, description, body, audience, origin: 'sleep' });
1454
+ // What it stands on, kept: this is what lets a later night notice
1455
+ // that the ground under this procedure has moved.
1456
+ this.#store.setSkillSources(skill.name, owner, sourceIds);
1457
+ this.#log.info('Sleep wrote a skill', { owner, skill: skill.name, evidence: sourceIds.length });
1458
+ return true;
1459
+ }
1460
+ catch (cause) {
1461
+ // Almost always "that name belongs to the user". Not worth failing a
1462
+ // night over; the night simply does not get that name.
1463
+ this.#log.info('Sleep left a skill alone', { owner, skill: name, reason: cause.message });
1464
+ return false;
1465
+ }
1466
+ }
1450
1467
  /* -------------------------------- the dream -------------------------------- */
1451
1468
  /**
1452
1469
  * The dream: measure the retrieval policy, and - when every condition
@@ -1458,7 +1475,7 @@ export class SleepRunner extends EventEmitter {
1458
1475
  * comes out of frames frozen during the day. A night without a provider
1459
1476
  * still measures, still promotes and still freezes - and that is exactly
1460
1477
  * 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`)
1478
+ * why the candidate writer sits at the far end of the night (`#writeCandidates`)
1462
1479
  * and writes for tomorrow: a promotion path that needed tonight's model
1463
1480
  * call would stop working on the night it matters most.
1464
1481
  *
@@ -1474,1101 +1491,17 @@ export class SleepRunner extends EventEmitter {
1474
1491
  // agent's frames, so recording and measuring them would be pure cost.
1475
1492
  if (!dream.enabled || owner !== ASSISTANT_MEMORY_OWNER)
1476
1493
  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', {
1543
- owner,
1544
- calls: probe.modelCalls,
1545
- ceiling,
1546
- });
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', {
1670
- owner,
1671
- findings: verdict.findings.join(','),
1672
- });
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, {
1494
+ const sitting = {
1684
1495
  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,
1496
+ runId,
1497
+ counters,
1498
+ deadline: Date.now() + clampMs(dream.maxEvalMs),
1699
1499
  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;
2115
- }
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
1500
  };
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 };
2562
- }
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;
1501
+ this.#phase(runId, 'dream', counters, 1);
1502
+ const report = await this.#dreaming.measure(sitting);
1503
+ this.#phase(runId, 'dream', counters, 1);
1504
+ return report;
2572
1505
  }
2573
1506
  /* ------------------------------ internals ------------------------------ */
2574
1507
  async #resolveProvider(wanted) {
@@ -2593,312 +1526,6 @@ export class SleepRunner extends EventEmitter {
2593
1526
  this.emit('sleep', event);
2594
1527
  }
2595
1528
  }
2596
- /* -------------------------------- prompts -------------------------------- */
2597
- const CONDENSE_PROMPT = `You are tidying a personal assistant's long-term memory overnight.
2598
-
2599
- The memories below concern the same topic. Decide whether they describe ONE fact
2600
- that can be condensed into one sentence.
2601
-
2602
- Merge ONLY when:
2603
- - the sentences genuinely describe the same fact, or
2604
- - a newer sentence supersedes an older one (the newer one takes precedence).
2605
-
2606
- Do NOT merge different facts that merely share a keyword.
2607
- When in doubt, keep them separate: separation costs nothing; a false merge loses knowledge.
2608
-
2609
- Rules:
2610
- - The result is ONE complete sentence, understandable without any other context.
2611
- - Write in the same language as the source memories.
2612
- - Under "supersedes", list the numbers of memories the new sentence fully replaces.
2613
- - NEVER list memories marked [protected] under "supersedes". They are context only.
2614
- - Do not list a number whose content is not included in the new sentence.
2615
-
2616
- Reply ONLY with JSON, no prose or code fence:
2617
- {"merge":true,"content":"...","kind":"fact","importance":0.7,"tags":["..."],"supersedes":[1,3]}
2618
- or
2619
- {"merge":false,"reason":"different facts"}`;
2620
- const LINK_PROMPT = `You are connecting a personal assistant's memories overnight.
2621
-
2622
- Find relationships between the numbered memories below.
2623
-
2624
- Relationships:
2625
- - "refines": "from" adds detail to "to" (the same fact, more detail)
2626
- - "contradicts": "from" and "to" cannot both be true
2627
- - "caused_by": "from" is true BECAUSE "to" is true
2628
-
2629
- Rules:
2630
- - Only relationships supported by the sentences themselves. Do not speculate.
2631
- - At most 12 relationships. None is a valid answer.
2632
- - "weight" is your confidence between 0 and 1.
2633
- - Also classify recognisable proper names as:
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.
2639
-
2640
- Reply ONLY with JSON, no prose or code fence:
2641
- {"edges":[{"from":1,"to":4,"relation":"refines","weight":0.8}],
2642
- "entities":[{"name":"Rookery","kind":"project"}],
2643
- "aliases":[{"from":"Rookery-Agent","into":"Rookery"}]}
2644
- An empty result is {"edges":[],"entities":[],"aliases":[]}`;
2645
- const RESOLVE_PROMPT = `You are resolving a contradiction in a personal assistant's memory overnight.
2646
-
2647
- The two sentences below contradict each other. Decide which takes precedence. You must decide,
2648
- unless they do not actually contradict each other.
2649
-
2650
- Rules:
2651
- - The newer sentence wins when both describe the same thing and circumstances have changed.
2652
- ("has switched to" supersedes the older state.)
2653
- - The more specific sentence wins when both concern the same time and one is imprecise.
2654
- - Use "both" only when both can be true together and the contradiction label was incorrect.
2655
- - Use "merge" only when both together describe the fact correctly. Then "content" is
2656
- ONE complete sentence in the language of the source memories.
2657
-
2658
- Reply ONLY with JSON, no prose or code fence:
2659
- {"decision":"first"}
2660
- {"decision":"second"}
2661
- {"decision":"both"}
2662
- {"decision":"merge","content":"..."}`;
2663
- const INSIGHT_USER_PROMPT = `You are reflecting on a personal assistant's memory overnight.
2664
-
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.
2668
-
2669
- Rules:
2670
- - At most {{MAX}} insights. None is the right answer when nothing stands out.
2671
- - Every insight needs at least TWO sources: the numbers supporting it.
2672
- - Never repeat an individual memory as an insight. An insight says something new.
2673
- - One sentence, third person, in the same language as the source memories.
2674
- - Do not invent or speculate. Only state what the evidence actually supports.
2675
-
2676
- Reply ONLY with JSON, no prose or code fence:
2677
- {"insights":[{"content":"...","importance":0.8,"evidence":[1,4,7],"tags":["..."]}]}
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":[]}`;
2801
- /* ------------------------------- helpers ------------------------------- */
2802
- /** What the night may never touch. */
2803
- function isProtected(memory) {
2804
- return memory.origin === 'user' || memory.pinned;
2805
- }
2806
- /** One small-model call. Never throws; an empty string means "nothing usable". */
2807
- async function ask(provider, prompt, model, signal) {
2808
- let output = '';
2809
- try {
2810
- for await (const event of provider.run({
2811
- prompt,
2812
- model,
2813
- // Housekeeping must never out-think the work it is tidying up after.
2814
- effort: 'low',
2815
- permission: 'chat',
2816
- signal,
2817
- })) {
2818
- if (event.type === 'done')
2819
- output = event.text || output;
2820
- else if (event.type === 'text')
2821
- output += event.delta;
2822
- else if (event.type === 'error' && event.fatal)
2823
- return output;
2824
- }
2825
- }
2826
- catch {
2827
- return '';
2828
- }
2829
- return output;
2830
- }
2831
- /** Pull one JSON object out of a reply that may carry prose or a fence. */
2832
- export function parseObject(raw) {
2833
- const text = raw.trim();
2834
- if (!text)
2835
- return null;
2836
- const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
2837
- const body = fenced?.[1] ?? text;
2838
- const start = body.indexOf('{');
2839
- const end = body.lastIndexOf('}');
2840
- if (start === -1 || end === -1 || end < start)
2841
- return null;
2842
- try {
2843
- const parsed = JSON.parse(body.slice(start, end + 1));
2844
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
2845
- ? parsed
2846
- : null;
2847
- }
2848
- catch {
2849
- return null;
2850
- }
2851
- }
2852
- /** The night in one line, in the language the user reads. */
2853
- export function describeSleep(counters) {
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
- }
2861
- if (counters.mergedCount)
2862
- parts.push(counters.mergedCount + ' condensed');
2863
- if (counters.dormantCount)
2864
- parts.push(counters.dormantCount + ' tidied');
2865
- if (counters.edgeCount)
2866
- parts.push(counters.edgeCount + ' connections added');
2867
- if (counters.resolvedCount) {
2868
- parts.push(plural(counters.resolvedCount, 'contradiction', 'contradictions') + ' resolved');
2869
- }
2870
- const openConflicts = Math.max(0, counters.conflictCount - (counters.resolvedCount ?? 0));
2871
- if (openConflicts) {
2872
- parts.push(plural(openConflicts, 'contradiction', 'contradictions') + ' open');
2873
- }
2874
- if (counters.insightCount) {
2875
- parts.push(plural(counters.insightCount, 'insight', 'insights') + ' recorded');
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
- }
2900
- return parts.length === 1 ? parts[0] + ', nothing to do.' : parts.join(', ') + '.';
2901
- }
2902
1529
  /**
2903
1530
  * Split a budget of model calls across the cycles of one night.
2904
1531
  *
@@ -3007,201 +1634,215 @@ function distribute(funded, keys, cap) {
3007
1634
  }
3008
1635
  keys.forEach((key, index) => funded.set(key, given[index]));
3009
1636
  }
3010
- /** Use explicit singular and plural forms. */
3011
- function plural(count, one, many) {
3012
- return count + ' ' + (count === 1 ? one : many);
3013
- }
3014
- function chunk(items, size) {
3015
- const out = [];
3016
- for (let index = 0; index < items.length; index += size)
3017
- out.push(items.slice(index, index + size));
3018
- return out;
3019
- }
3020
- function clamp01(value) {
3021
- return Math.min(1, Math.max(0, Number.isFinite(value) ? value : 0));
3022
- }
1637
+ /* ------------------------------- helpers ------------------------------- */
1638
+ /** The most cycles of light, deep and rem one night may run. */
1639
+ const MAX_CYCLES = 5;
1640
+ /** One link call reads up to this many memories in one portion. */
1641
+ const LINK_PORTION = 25;
1642
+ /** The two angles insights are looked for from, one call each. */
1643
+ const INSIGHT_ANGLES = ['user', 'work'];
1644
+ /** Fewer recent memories than this have no pattern worth a call. */
1645
+ const MIN_REFLECT_POOL = 4;
1646
+ /** Fewer memories than this hold no recurring work worth writing down. */
1647
+ const MIN_PRACTISE_MEMORIES = 6;
1648
+ /** A real conversation has at least this many user turns. */
1649
+ const MIN_SPOKEN_TURNS = 2;
1650
+ /** Newest fresh memories a night looks at. */
1651
+ const FRESH_LIMIT = 150;
1652
+ /** Conversations the replay scan looks back over. */
1653
+ const REPLAY_SCAN = 150;
1654
+ /** Most memories the insight window reads. */
1655
+ const REFLECT_POOL_LIMIT = 80;
1656
+ /** Most insights already on record that a new one is compared against. */
1657
+ const ON_RECORD_LIMIT = 200;
1658
+ /** Insights already on record that the prompt shows, newest first. */
1659
+ const ON_RECORD_SHOWN = 30;
3023
1660
  /**
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.
1661
+ * Dice similarity at which a new insight counts as a restatement of one on
1662
+ * record. Read off one bank's sixty-five insights: the nearest earlier one
1663
+ * had a median similarity of 0.34 and one insight in five reached 0.5, among
1664
+ * them the same observation reworded on consecutive nights. Lower would also
1665
+ * turn away distinct insights that merely share a subject's vocabulary.
3029
1666
  */
3030
- function clampDays(value) {
3031
- const days = Number.isFinite(value) ? Math.round(value) : 0;
3032
- return Math.min(36_500, Math.max(0, days));
1667
+ const INSIGHT_RESTATEMENT_SIMILARITY = 0.5;
1668
+ /** Entities offered to the insight prompt as common topics. */
1669
+ const COMMON_TOPICS = 12;
1670
+ /** Most memories one skill distillation reads. */
1671
+ const PRACTISE_POOL_LIMIT = 60;
1672
+ /** Neighbouring memories the link pass adds to what is fresh. */
1673
+ const NEIGHBOUR_LIMIT = 40;
1674
+ /** Edges read when looking for open contradictions. */
1675
+ const CONTRADICTION_SCAN = 500;
1676
+ /** Edges read when looking for pairs the gate flagged. */
1677
+ const CO_OCCURRENCE_SCAN = 2000;
1678
+ /** More members than this are too many to judge in one call. */
1679
+ const CLUSTER_LIMIT = 8;
1680
+ /** Corrections matched against the skill shelf per night. */
1681
+ const OPEN_CORRECTIONS = 20;
1682
+ /** Failed runs shown to the model per skill. */
1683
+ const FAILED_RUNS_SHOWN = 3;
1684
+ const MAX_INSIGHT_TAGS = 6;
1685
+ const INSIGHT_EDGE_WEIGHT = 0.8;
1686
+ /** When the newest of these memories was written; zero for none. */
1687
+ function newestCreation(memories) {
1688
+ return memories.reduce((newest, memory) => Math.max(newest, memory.createdAt), 0);
3033
1689
  }
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 : '';
1690
+ /** The newest insights as bullet lines, the way the prompt lists what is on record. */
1691
+ function listNewestInsights(insights) {
1692
+ return [...insights]
1693
+ .sort((a, b) => b.createdAt - a.createdAt)
1694
+ .slice(0, ON_RECORD_SHOWN)
1695
+ .map((insight) => '- ' + insight.content)
1696
+ .join('\n');
3050
1697
  }
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;
1698
+ /** Whether an insight stands on at least one memory written after the last pass. */
1699
+ function standsOnNews(draft, reflectedUntil) {
1700
+ return draft.evidence.some((memory) => memory.createdAt > reflectedUntil);
1701
+ }
1702
+ /** Whether an insight says what one already on record says, in other words or the same. */
1703
+ function restates(content, stated) {
1704
+ const tokens = normalizeTokens(content);
1705
+ return stated.some((other) => similarity(tokens, other) >= INSIGHT_RESTATEMENT_SIMILARITY);
1706
+ }
1707
+ /** How much of one turn, and of a whole conversation, the deep read sees. */
1708
+ const TURN_CLIP_CHARS = 2500;
1709
+ const TRANSCRIPT_CHARS = 24_000;
1710
+ /** How much of one user turn the triage sees. */
1711
+ const TRIAGE_CLIP_CHARS = 220;
3064
1712
  /**
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.
1713
+ * How close a correction's wording has to be to a skill before it counts as
1714
+ * being about that skill. Low on purpose: a correction and the procedure it
1715
+ * bears on rarely share many words, and the cost of a false match is one
1716
+ * reading that concludes "leave it alone", while the cost of a miss is a skill
1717
+ * that goes on being wrong.
3068
1718
  */
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
- };
1719
+ const CORRECTION_MATCH = 0.12;
3081
1720
  /**
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).
1721
+ * How strong a memory is: what it claims to be worth, what it has
1722
+ * demonstrably been worth, and how recently it was touched, blended 5:3:2.
1723
+ * Recency halves every thirty days.
3086
1724
  */
3087
- function liftPolicy(placement, incumbent) {
1725
+ const IMPORTANCE_WEIGHT = 0.5;
1726
+ const USEFULNESS_WEIGHT = 0.3;
1727
+ const RECENCY_WEIGHT = 0.2;
1728
+ const RECENCY_HALF_LIFE_MS = 30 * DAY_MS;
1729
+ function emptyTally() {
3088
1730
  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,
1731
+ readCount: 0,
1732
+ replayedCount: 0,
1733
+ learnedCount: 0,
1734
+ mergedCount: 0,
1735
+ dormantCount: 0,
1736
+ edgeCount: 0,
1737
+ insightCount: 0,
1738
+ skillCount: 0,
1739
+ skillRevisedCount: 0,
1740
+ conflictCount: 0,
1741
+ resolvedCount: 0,
1742
+ // The dream counters (fifth of the six places in step): initialised
1743
+ // here or `tally.dreamFramesScored` is a type error before anything
1744
+ // ever increments it. `dreamCandidates` is written by the candidate
1745
+ // writer alone.
1746
+ dreamTracesSeen: 0,
1747
+ dreamFramesScored: 0,
1748
+ dreamCandidates: 0,
1749
+ // Stage 2's two: what the label writers wrote tonight, and whether a
1750
+ // parameter set went in force. Both are 0 with `dream.enabled` off,
1751
+ // because with it off nothing that could move them ever runs.
1752
+ dreamPromoted: 0,
1753
+ dreamLabelsWritten: 0,
1754
+ modelCalls: 0,
3097
1755
  };
3098
1756
  }
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
- };
1757
+ function emptySpend() {
1758
+ return Object.fromEntries(NIGHT_PHASES.map((phase) => [phase, { calls: 0, value: 0 }]));
3114
1759
  }
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;
1760
+ function bookSpend(night, phase, calls, value) {
1761
+ night.spend[phase].calls += calls;
1762
+ night.spend[phase].value += value;
1763
+ }
1764
+ /** Abort `controller` when `signal` does; the returned function stops listening. */
1765
+ function followSignal(signal, controller) {
1766
+ if (!signal)
1767
+ return () => undefined;
1768
+ if (signal.aborted) {
1769
+ controller.abort();
1770
+ return () => undefined;
3136
1771
  }
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
- };
1772
+ const onAbort = () => controller.abort();
1773
+ signal.addEventListener('abort', onAbort, { once: true });
1774
+ return () => signal.removeEventListener('abort', onAbort);
3147
1775
  }
3148
1776
  /**
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.
1777
+ * Said out loud rather than swallowed: the consolidation went on, and the
1778
+ * night is short of labels it expected to have.
3152
1779
  */
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));
1780
+ function labelFailureNote(failures) {
1781
+ if (failures <= 0)
1782
+ return '';
1783
+ return (' ' + plural(failures, 'label pass', 'label passes') +
1784
+ ' failed and left no labels; the consolidation went on.');
3156
1785
  }
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));
1786
+ /** The turns where the user actually said something. */
1787
+ function userTurns(messages) {
1788
+ return messages.filter((message) => message.role === 'user' && message.content.trim());
3161
1789
  }
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);
1790
+ /** A moment as the calendar day the prompts name. */
1791
+ function isoDay(at) {
1792
+ return new Date(at).toISOString().slice(0, 10);
3167
1793
  }
3168
- function zeroMeans() {
3169
- return { relevance: 0, importance: 0, recency: 0, usage: 0, tagHit: 0 };
1794
+ function chunk(items, size) {
1795
+ const out = [];
1796
+ for (let index = 0; index < items.length; index += size)
1797
+ out.push(items.slice(index, index + size));
1798
+ return out;
3170
1799
  }
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;
1800
+ /** Memories as the numbered list the prompts refer to by number. */
1801
+ function numberMemories(memories) {
1802
+ return memories
1803
+ .map((memory, index) => index + 1 + '. [' + memory.kind + '] ' + memory.content)
1804
+ .join('\n');
3177
1805
  }
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
- };
1806
+ /** A cluster as the numbered list the condense prompt decides over. */
1807
+ function describeCluster(members) {
1808
+ return members
1809
+ .map((memory, index) => {
1810
+ const lock = isProtected(memory) ? ' [protected]' : '';
1811
+ return (index + 1 + '. [' + memory.kind + ', ' + memory.importance.toFixed(2) + ', ' +
1812
+ isoDay(memory.createdAt) + ']' + lock + ' ' + memory.content);
1813
+ })
1814
+ .join('\n');
1815
+ }
1816
+ function describePair(a, b) {
1817
+ return ('1. [' + a.kind + ', ' + isoDay(a.createdAt) + '] ' + a.content +
1818
+ '\n2. [' + b.kind + ', ' + isoDay(b.createdAt) + '] ' + b.content);
1819
+ }
1820
+ /** What has changed under a skill, as the lines the revise prompt weighs. */
1821
+ function describeWhy({ changed, corrections, failures }) {
1822
+ const why = [];
1823
+ for (const entry of changed) {
1824
+ const line = entry.replacement
1825
+ ? 'This memory was replaced:\n BEFORE: ' + entry.memory.content + '\n NOW: ' + entry.replacement.content
1826
+ : entry.memory.dormantAt
1827
+ ? 'This memory was put to sleep as no longer worth keeping: ' + entry.memory.content
1828
+ : 'This memory was edited since the skill was written: ' + entry.memory.content;
1829
+ why.push('- ' + line);
1830
+ }
1831
+ // The user's own words go first: nothing else in the list carries as
1832
+ // much weight as being told outright that this is wrong.
1833
+ for (const entry of corrections) {
1834
+ why.unshift('- The user corrected this: ' + entry.text +
1835
+ '\n IN THEIR WORDS: "' + clipText(entry.quote, 220) + '"');
1836
+ }
1837
+ for (const failure of failures) {
1838
+ why.push('- A run that had this skill open failed.\n TASK: ' + clipText(failure.task, 200) +
1839
+ '\n ERROR: ' + clipText(failure.error, 400));
1840
+ }
1841
+ return why.join('\n');
3188
1842
  }
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
1843
  /** Which suspect gets the night's attention first. */
3198
1844
  function weigh(entry) {
3199
1845
  // Being told outright beats a failed run, which beats shifted ground.
3200
1846
  return entry.corrections.length * 4 + entry.failures.length * 2 + entry.changed.length;
3201
1847
  }
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
- }
3207
1848
  //# sourceMappingURL=sleep.js.map