@cleocode/cleo 2026.4.59 → 2026.4.62

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 (773) hide show
  1. package/dist/cli/index.js +1917 -314
  2. package/dist/cli/index.js.map +4 -4
  3. package/package.json +8 -8
  4. package/dist/cli/commander-shim.d.ts +0 -112
  5. package/dist/cli/commander-shim.d.ts.map +0 -1
  6. package/dist/cli/commander-shim.js +0 -233
  7. package/dist/cli/commander-shim.js.map +0 -1
  8. package/dist/cli/commands/adapter.d.ts +0 -21
  9. package/dist/cli/commands/adapter.d.ts.map +0 -1
  10. package/dist/cli/commands/adapter.js +0 -73
  11. package/dist/cli/commands/adapter.js.map +0 -1
  12. package/dist/cli/commands/add-batch.d.ts +0 -16
  13. package/dist/cli/commands/add-batch.d.ts.map +0 -1
  14. package/dist/cli/commands/add-batch.js +0 -133
  15. package/dist/cli/commands/add-batch.js.map +0 -1
  16. package/dist/cli/commands/add.d.ts +0 -12
  17. package/dist/cli/commands/add.d.ts.map +0 -1
  18. package/dist/cli/commands/add.js +0 -238
  19. package/dist/cli/commands/add.js.map +0 -1
  20. package/dist/cli/commands/admin.d.ts +0 -15
  21. package/dist/cli/commands/admin.d.ts.map +0 -1
  22. package/dist/cli/commands/admin.js +0 -143
  23. package/dist/cli/commands/admin.js.map +0 -1
  24. package/dist/cli/commands/adr.d.ts +0 -27
  25. package/dist/cli/commands/adr.d.ts.map +0 -1
  26. package/dist/cli/commands/adr.js +0 -79
  27. package/dist/cli/commands/adr.js.map +0 -1
  28. package/dist/cli/commands/agent-profile-status.d.ts +0 -98
  29. package/dist/cli/commands/agent-profile-status.d.ts.map +0 -1
  30. package/dist/cli/commands/agent-profile-status.js +0 -71
  31. package/dist/cli/commands/agent-profile-status.js.map +0 -1
  32. package/dist/cli/commands/agent.d.ts +0 -41
  33. package/dist/cli/commands/agent.d.ts.map +0 -1
  34. package/dist/cli/commands/agent.js +0 -2270
  35. package/dist/cli/commands/agent.js.map +0 -1
  36. package/dist/cli/commands/agents.d.ts +0 -17
  37. package/dist/cli/commands/agents.d.ts.map +0 -1
  38. package/dist/cli/commands/agents.js +0 -20
  39. package/dist/cli/commands/agents.js.map +0 -1
  40. package/dist/cli/commands/analyze.d.ts +0 -12
  41. package/dist/cli/commands/analyze.d.ts.map +0 -1
  42. package/dist/cli/commands/analyze.js +0 -20
  43. package/dist/cli/commands/analyze.js.map +0 -1
  44. package/dist/cli/commands/archive-stats.d.ts +0 -18
  45. package/dist/cli/commands/archive-stats.d.ts.map +0 -1
  46. package/dist/cli/commands/archive-stats.js +0 -49
  47. package/dist/cli/commands/archive-stats.js.map +0 -1
  48. package/dist/cli/commands/archive.d.ts +0 -12
  49. package/dist/cli/commands/archive.d.ts.map +0 -1
  50. package/dist/cli/commands/archive.js +0 -32
  51. package/dist/cli/commands/archive.js.map +0 -1
  52. package/dist/cli/commands/backfill.d.ts +0 -38
  53. package/dist/cli/commands/backfill.d.ts.map +0 -1
  54. package/dist/cli/commands/backfill.js +0 -144
  55. package/dist/cli/commands/backfill.js.map +0 -1
  56. package/dist/cli/commands/backup-inspect.d.ts +0 -24
  57. package/dist/cli/commands/backup-inspect.d.ts.map +0 -1
  58. package/dist/cli/commands/backup-inspect.js +0 -417
  59. package/dist/cli/commands/backup-inspect.js.map +0 -1
  60. package/dist/cli/commands/backup.d.ts +0 -13
  61. package/dist/cli/commands/backup.d.ts.map +0 -1
  62. package/dist/cli/commands/backup.js +0 -479
  63. package/dist/cli/commands/backup.js.map +0 -1
  64. package/dist/cli/commands/blockers.d.ts +0 -7
  65. package/dist/cli/commands/blockers.d.ts.map +0 -1
  66. package/dist/cli/commands/blockers.js +0 -16
  67. package/dist/cli/commands/blockers.js.map +0 -1
  68. package/dist/cli/commands/brain.d.ts +0 -29
  69. package/dist/cli/commands/brain.d.ts.map +0 -1
  70. package/dist/cli/commands/brain.js +0 -358
  71. package/dist/cli/commands/brain.js.map +0 -1
  72. package/dist/cli/commands/briefing.d.ts +0 -22
  73. package/dist/cli/commands/briefing.d.ts.map +0 -1
  74. package/dist/cli/commands/briefing.js +0 -45
  75. package/dist/cli/commands/briefing.js.map +0 -1
  76. package/dist/cli/commands/bug.d.ts +0 -12
  77. package/dist/cli/commands/bug.d.ts.map +0 -1
  78. package/dist/cli/commands/bug.js +0 -81
  79. package/dist/cli/commands/bug.js.map +0 -1
  80. package/dist/cli/commands/cancel.d.ts +0 -17
  81. package/dist/cli/commands/cancel.d.ts.map +0 -1
  82. package/dist/cli/commands/cancel.js +0 -28
  83. package/dist/cli/commands/cancel.js.map +0 -1
  84. package/dist/cli/commands/cant.d.ts +0 -32
  85. package/dist/cli/commands/cant.d.ts.map +0 -1
  86. package/dist/cli/commands/cant.js +0 -264
  87. package/dist/cli/commands/cant.js.map +0 -1
  88. package/dist/cli/commands/chain.d.ts +0 -16
  89. package/dist/cli/commands/chain.d.ts.map +0 -1
  90. package/dist/cli/commands/chain.js +0 -52
  91. package/dist/cli/commands/chain.js.map +0 -1
  92. package/dist/cli/commands/check.d.ts +0 -25
  93. package/dist/cli/commands/check.d.ts.map +0 -1
  94. package/dist/cli/commands/check.js +0 -193
  95. package/dist/cli/commands/check.js.map +0 -1
  96. package/dist/cli/commands/checkpoint.d.ts +0 -15
  97. package/dist/cli/commands/checkpoint.d.ts.map +0 -1
  98. package/dist/cli/commands/checkpoint.js +0 -91
  99. package/dist/cli/commands/checkpoint.js.map +0 -1
  100. package/dist/cli/commands/claim.d.ts +0 -27
  101. package/dist/cli/commands/claim.d.ts.map +0 -1
  102. package/dist/cli/commands/claim.js +0 -45
  103. package/dist/cli/commands/claim.js.map +0 -1
  104. package/dist/cli/commands/code.d.ts +0 -11
  105. package/dist/cli/commands/code.d.ts.map +0 -1
  106. package/dist/cli/commands/code.js +0 -114
  107. package/dist/cli/commands/code.js.map +0 -1
  108. package/dist/cli/commands/commands.d.ts +0 -13
  109. package/dist/cli/commands/commands.d.ts.map +0 -1
  110. package/dist/cli/commands/commands.js +0 -29
  111. package/dist/cli/commands/commands.js.map +0 -1
  112. package/dist/cli/commands/complete.d.ts +0 -12
  113. package/dist/cli/commands/complete.d.ts.map +0 -1
  114. package/dist/cli/commands/complete.js +0 -92
  115. package/dist/cli/commands/complete.js.map +0 -1
  116. package/dist/cli/commands/complexity.d.ts +0 -17
  117. package/dist/cli/commands/complexity.d.ts.map +0 -1
  118. package/dist/cli/commands/complexity.js +0 -25
  119. package/dist/cli/commands/complexity.js.map +0 -1
  120. package/dist/cli/commands/compliance.d.ts +0 -9
  121. package/dist/cli/commands/compliance.d.ts.map +0 -1
  122. package/dist/cli/commands/compliance.js +0 -110
  123. package/dist/cli/commands/compliance.js.map +0 -1
  124. package/dist/cli/commands/config.d.ts +0 -10
  125. package/dist/cli/commands/config.d.ts.map +0 -1
  126. package/dist/cli/commands/config.js +0 -69
  127. package/dist/cli/commands/config.js.map +0 -1
  128. package/dist/cli/commands/consensus.d.ts +0 -13
  129. package/dist/cli/commands/consensus.d.ts.map +0 -1
  130. package/dist/cli/commands/consensus.js +0 -45
  131. package/dist/cli/commands/consensus.js.map +0 -1
  132. package/dist/cli/commands/context.d.ts +0 -15
  133. package/dist/cli/commands/context.d.ts.map +0 -1
  134. package/dist/cli/commands/context.js +0 -76
  135. package/dist/cli/commands/context.js.map +0 -1
  136. package/dist/cli/commands/contribution.d.ts +0 -13
  137. package/dist/cli/commands/contribution.d.ts.map +0 -1
  138. package/dist/cli/commands/contribution.js +0 -41
  139. package/dist/cli/commands/contribution.js.map +0 -1
  140. package/dist/cli/commands/current.d.ts +0 -13
  141. package/dist/cli/commands/current.d.ts.map +0 -1
  142. package/dist/cli/commands/current.js +0 -20
  143. package/dist/cli/commands/current.js.map +0 -1
  144. package/dist/cli/commands/dash.d.ts +0 -12
  145. package/dist/cli/commands/dash.d.ts.map +0 -1
  146. package/dist/cli/commands/dash.js +0 -20
  147. package/dist/cli/commands/dash.js.map +0 -1
  148. package/dist/cli/commands/decomposition.d.ts +0 -13
  149. package/dist/cli/commands/decomposition.d.ts.map +0 -1
  150. package/dist/cli/commands/decomposition.js +0 -45
  151. package/dist/cli/commands/decomposition.js.map +0 -1
  152. package/dist/cli/commands/delete.d.ts +0 -12
  153. package/dist/cli/commands/delete.d.ts.map +0 -1
  154. package/dist/cli/commands/delete.js +0 -37
  155. package/dist/cli/commands/delete.js.map +0 -1
  156. package/dist/cli/commands/deps.d.ts +0 -24
  157. package/dist/cli/commands/deps.d.ts.map +0 -1
  158. package/dist/cli/commands/deps.js +0 -98
  159. package/dist/cli/commands/deps.js.map +0 -1
  160. package/dist/cli/commands/detect-drift.d.ts +0 -15
  161. package/dist/cli/commands/detect-drift.d.ts.map +0 -1
  162. package/dist/cli/commands/detect-drift.js +0 -428
  163. package/dist/cli/commands/detect-drift.js.map +0 -1
  164. package/dist/cli/commands/detect.d.ts +0 -13
  165. package/dist/cli/commands/detect.d.ts.map +0 -1
  166. package/dist/cli/commands/detect.js +0 -20
  167. package/dist/cli/commands/detect.js.map +0 -1
  168. package/dist/cli/commands/diagnostics.d.ts +0 -16
  169. package/dist/cli/commands/diagnostics.d.ts.map +0 -1
  170. package/dist/cli/commands/diagnostics.js +0 -58
  171. package/dist/cli/commands/diagnostics.js.map +0 -1
  172. package/dist/cli/commands/docs.d.ts +0 -13
  173. package/dist/cli/commands/docs.d.ts.map +0 -1
  174. package/dist/cli/commands/docs.js +0 -169
  175. package/dist/cli/commands/docs.js.map +0 -1
  176. package/dist/cli/commands/doctor.d.ts +0 -15
  177. package/dist/cli/commands/doctor.d.ts.map +0 -1
  178. package/dist/cli/commands/doctor.js +0 -133
  179. package/dist/cli/commands/doctor.js.map +0 -1
  180. package/dist/cli/commands/dynamic.d.ts +0 -24
  181. package/dist/cli/commands/dynamic.d.ts.map +0 -1
  182. package/dist/cli/commands/dynamic.js +0 -27
  183. package/dist/cli/commands/dynamic.js.map +0 -1
  184. package/dist/cli/commands/env.d.ts +0 -12
  185. package/dist/cli/commands/env.d.ts.map +0 -1
  186. package/dist/cli/commands/env.js +0 -44
  187. package/dist/cli/commands/env.js.map +0 -1
  188. package/dist/cli/commands/exists.d.ts +0 -24
  189. package/dist/cli/commands/exists.d.ts.map +0 -1
  190. package/dist/cli/commands/exists.js +0 -53
  191. package/dist/cli/commands/exists.js.map +0 -1
  192. package/dist/cli/commands/export-tasks.d.ts +0 -10
  193. package/dist/cli/commands/export-tasks.d.ts.map +0 -1
  194. package/dist/cli/commands/export-tasks.js +0 -47
  195. package/dist/cli/commands/export-tasks.js.map +0 -1
  196. package/dist/cli/commands/export.d.ts +0 -9
  197. package/dist/cli/commands/export.d.ts.map +0 -1
  198. package/dist/cli/commands/export.js +0 -46
  199. package/dist/cli/commands/export.js.map +0 -1
  200. package/dist/cli/commands/find.d.ts +0 -14
  201. package/dist/cli/commands/find.d.ts.map +0 -1
  202. package/dist/cli/commands/find.js +0 -152
  203. package/dist/cli/commands/find.js.map +0 -1
  204. package/dist/cli/commands/generate-changelog.d.ts +0 -14
  205. package/dist/cli/commands/generate-changelog.d.ts.map +0 -1
  206. package/dist/cli/commands/generate-changelog.js +0 -252
  207. package/dist/cli/commands/generate-changelog.js.map +0 -1
  208. package/dist/cli/commands/grade.d.ts +0 -13
  209. package/dist/cli/commands/grade.d.ts.map +0 -1
  210. package/dist/cli/commands/grade.js +0 -26
  211. package/dist/cli/commands/grade.js.map +0 -1
  212. package/dist/cli/commands/history.d.ts +0 -9
  213. package/dist/cli/commands/history.d.ts.map +0 -1
  214. package/dist/cli/commands/history.js +0 -33
  215. package/dist/cli/commands/history.js.map +0 -1
  216. package/dist/cli/commands/implementation.d.ts +0 -13
  217. package/dist/cli/commands/implementation.d.ts.map +0 -1
  218. package/dist/cli/commands/implementation.js +0 -41
  219. package/dist/cli/commands/implementation.js.map +0 -1
  220. package/dist/cli/commands/import-tasks.d.ts +0 -10
  221. package/dist/cli/commands/import-tasks.d.ts.map +0 -1
  222. package/dist/cli/commands/import-tasks.js +0 -38
  223. package/dist/cli/commands/import-tasks.js.map +0 -1
  224. package/dist/cli/commands/import.d.ts +0 -9
  225. package/dist/cli/commands/import.d.ts.map +0 -1
  226. package/dist/cli/commands/import.js +0 -28
  227. package/dist/cli/commands/import.js.map +0 -1
  228. package/dist/cli/commands/init.d.ts +0 -34
  229. package/dist/cli/commands/init.d.ts.map +0 -1
  230. package/dist/cli/commands/init.js +0 -96
  231. package/dist/cli/commands/init.js.map +0 -1
  232. package/dist/cli/commands/inject.d.ts +0 -8
  233. package/dist/cli/commands/inject.d.ts.map +0 -1
  234. package/dist/cli/commands/inject.js +0 -28
  235. package/dist/cli/commands/inject.js.map +0 -1
  236. package/dist/cli/commands/intelligence.d.ts +0 -22
  237. package/dist/cli/commands/intelligence.d.ts.map +0 -1
  238. package/dist/cli/commands/intelligence.js +0 -72
  239. package/dist/cli/commands/intelligence.js.map +0 -1
  240. package/dist/cli/commands/issue.d.ts +0 -17
  241. package/dist/cli/commands/issue.d.ts.map +0 -1
  242. package/dist/cli/commands/issue.js +0 -107
  243. package/dist/cli/commands/issue.js.map +0 -1
  244. package/dist/cli/commands/labels.d.ts +0 -17
  245. package/dist/cli/commands/labels.d.ts.map +0 -1
  246. package/dist/cli/commands/labels.js +0 -48
  247. package/dist/cli/commands/labels.js.map +0 -1
  248. package/dist/cli/commands/lifecycle.d.ts +0 -8
  249. package/dist/cli/commands/lifecycle.d.ts.map +0 -1
  250. package/dist/cli/commands/lifecycle.js +0 -128
  251. package/dist/cli/commands/lifecycle.js.map +0 -1
  252. package/dist/cli/commands/list.d.ts +0 -14
  253. package/dist/cli/commands/list.d.ts.map +0 -1
  254. package/dist/cli/commands/list.js +0 -143
  255. package/dist/cli/commands/list.js.map +0 -1
  256. package/dist/cli/commands/log.d.ts +0 -12
  257. package/dist/cli/commands/log.d.ts.map +0 -1
  258. package/dist/cli/commands/log.js +0 -30
  259. package/dist/cli/commands/log.js.map +0 -1
  260. package/dist/cli/commands/map.d.ts +0 -10
  261. package/dist/cli/commands/map.d.ts.map +0 -1
  262. package/dist/cli/commands/map.js +0 -23
  263. package/dist/cli/commands/map.js.map +0 -1
  264. package/dist/cli/commands/memory-brain.d.ts +0 -15
  265. package/dist/cli/commands/memory-brain.d.ts.map +0 -1
  266. package/dist/cli/commands/memory-brain.js +0 -436
  267. package/dist/cli/commands/memory-brain.js.map +0 -1
  268. package/dist/cli/commands/migrate-claude-mem.d.ts +0 -23
  269. package/dist/cli/commands/migrate-claude-mem.d.ts.map +0 -1
  270. package/dist/cli/commands/migrate-claude-mem.js +0 -79
  271. package/dist/cli/commands/migrate-claude-mem.js.map +0 -1
  272. package/dist/cli/commands/next.d.ts +0 -9
  273. package/dist/cli/commands/next.d.ts.map +0 -1
  274. package/dist/cli/commands/next.js +0 -20
  275. package/dist/cli/commands/next.js.map +0 -1
  276. package/dist/cli/commands/nexus.d.ts +0 -20
  277. package/dist/cli/commands/nexus.d.ts.map +0 -1
  278. package/dist/cli/commands/nexus.js +0 -2290
  279. package/dist/cli/commands/nexus.js.map +0 -1
  280. package/dist/cli/commands/observe.d.ts +0 -13
  281. package/dist/cli/commands/observe.d.ts.map +0 -1
  282. package/dist/cli/commands/observe.js +0 -30
  283. package/dist/cli/commands/observe.js.map +0 -1
  284. package/dist/cli/commands/ops.d.ts +0 -10
  285. package/dist/cli/commands/ops.d.ts.map +0 -1
  286. package/dist/cli/commands/ops.js +0 -19
  287. package/dist/cli/commands/ops.js.map +0 -1
  288. package/dist/cli/commands/orchestrate.d.ts +0 -24
  289. package/dist/cli/commands/orchestrate.d.ts.map +0 -1
  290. package/dist/cli/commands/orchestrate.js +0 -254
  291. package/dist/cli/commands/orchestrate.js.map +0 -1
  292. package/dist/cli/commands/otel.d.ts +0 -12
  293. package/dist/cli/commands/otel.d.ts.map +0 -1
  294. package/dist/cli/commands/otel.js +0 -128
  295. package/dist/cli/commands/otel.js.map +0 -1
  296. package/dist/cli/commands/phase.d.ts +0 -12
  297. package/dist/cli/commands/phase.d.ts.map +0 -1
  298. package/dist/cli/commands/phase.js +0 -91
  299. package/dist/cli/commands/phase.js.map +0 -1
  300. package/dist/cli/commands/phases.d.ts +0 -14
  301. package/dist/cli/commands/phases.d.ts.map +0 -1
  302. package/dist/cli/commands/phases.js +0 -42
  303. package/dist/cli/commands/phases.js.map +0 -1
  304. package/dist/cli/commands/plan.d.ts +0 -8
  305. package/dist/cli/commands/plan.d.ts.map +0 -1
  306. package/dist/cli/commands/plan.js +0 -15
  307. package/dist/cli/commands/plan.js.map +0 -1
  308. package/dist/cli/commands/promote.d.ts +0 -11
  309. package/dist/cli/commands/promote.d.ts.map +0 -1
  310. package/dist/cli/commands/promote.js +0 -18
  311. package/dist/cli/commands/promote.js.map +0 -1
  312. package/dist/cli/commands/provider.d.ts +0 -21
  313. package/dist/cli/commands/provider.d.ts.map +0 -1
  314. package/dist/cli/commands/provider.js +0 -88
  315. package/dist/cli/commands/provider.js.map +0 -1
  316. package/dist/cli/commands/reason.d.ts +0 -36
  317. package/dist/cli/commands/reason.d.ts.map +0 -1
  318. package/dist/cli/commands/reason.js +0 -85
  319. package/dist/cli/commands/reason.js.map +0 -1
  320. package/dist/cli/commands/refresh-memory.d.ts +0 -9
  321. package/dist/cli/commands/refresh-memory.d.ts.map +0 -1
  322. package/dist/cli/commands/refresh-memory.js +0 -24
  323. package/dist/cli/commands/refresh-memory.js.map +0 -1
  324. package/dist/cli/commands/relates.d.ts +0 -12
  325. package/dist/cli/commands/relates.d.ts.map +0 -1
  326. package/dist/cli/commands/relates.js +0 -53
  327. package/dist/cli/commands/relates.js.map +0 -1
  328. package/dist/cli/commands/release.d.ts +0 -8
  329. package/dist/cli/commands/release.d.ts.map +0 -1
  330. package/dist/cli/commands/release.js +0 -82
  331. package/dist/cli/commands/release.js.map +0 -1
  332. package/dist/cli/commands/remote.d.ts +0 -12
  333. package/dist/cli/commands/remote.d.ts.map +0 -1
  334. package/dist/cli/commands/remote.js +0 -207
  335. package/dist/cli/commands/remote.js.map +0 -1
  336. package/dist/cli/commands/reorder.d.ts +0 -17
  337. package/dist/cli/commands/reorder.d.ts.map +0 -1
  338. package/dist/cli/commands/reorder.js +0 -41
  339. package/dist/cli/commands/reorder.js.map +0 -1
  340. package/dist/cli/commands/reparent.d.ts +0 -10
  341. package/dist/cli/commands/reparent.d.ts.map +0 -1
  342. package/dist/cli/commands/reparent.js +0 -19
  343. package/dist/cli/commands/reparent.js.map +0 -1
  344. package/dist/cli/commands/research.d.ts +0 -8
  345. package/dist/cli/commands/research.d.ts.map +0 -1
  346. package/dist/cli/commands/research.js +0 -164
  347. package/dist/cli/commands/research.js.map +0 -1
  348. package/dist/cli/commands/restore.d.ts +0 -54
  349. package/dist/cli/commands/restore.d.ts.map +0 -1
  350. package/dist/cli/commands/restore.js +0 -470
  351. package/dist/cli/commands/restore.js.map +0 -1
  352. package/dist/cli/commands/roadmap.d.ts +0 -14
  353. package/dist/cli/commands/roadmap.d.ts.map +0 -1
  354. package/dist/cli/commands/roadmap.js +0 -26
  355. package/dist/cli/commands/roadmap.js.map +0 -1
  356. package/dist/cli/commands/safestop.d.ts +0 -14
  357. package/dist/cli/commands/safestop.d.ts.map +0 -1
  358. package/dist/cli/commands/safestop.js +0 -32
  359. package/dist/cli/commands/safestop.js.map +0 -1
  360. package/dist/cli/commands/schema.d.ts +0 -27
  361. package/dist/cli/commands/schema.d.ts.map +0 -1
  362. package/dist/cli/commands/schema.js +0 -160
  363. package/dist/cli/commands/schema.js.map +0 -1
  364. package/dist/cli/commands/self-update.d.ts +0 -15
  365. package/dist/cli/commands/self-update.d.ts.map +0 -1
  366. package/dist/cli/commands/self-update.js +0 -363
  367. package/dist/cli/commands/self-update.js.map +0 -1
  368. package/dist/cli/commands/sequence.d.ts +0 -11
  369. package/dist/cli/commands/sequence.d.ts.map +0 -1
  370. package/dist/cli/commands/sequence.js +0 -40
  371. package/dist/cli/commands/sequence.js.map +0 -1
  372. package/dist/cli/commands/session.d.ts +0 -12
  373. package/dist/cli/commands/session.d.ts.map +0 -1
  374. package/dist/cli/commands/session.js +0 -219
  375. package/dist/cli/commands/session.js.map +0 -1
  376. package/dist/cli/commands/show.d.ts +0 -13
  377. package/dist/cli/commands/show.d.ts.map +0 -1
  378. package/dist/cli/commands/show.js +0 -40
  379. package/dist/cli/commands/show.js.map +0 -1
  380. package/dist/cli/commands/skills.d.ts +0 -13
  381. package/dist/cli/commands/skills.d.ts.map +0 -1
  382. package/dist/cli/commands/skills.js +0 -161
  383. package/dist/cli/commands/skills.js.map +0 -1
  384. package/dist/cli/commands/snapshot.d.ts +0 -9
  385. package/dist/cli/commands/snapshot.d.ts.map +0 -1
  386. package/dist/cli/commands/snapshot.js +0 -50
  387. package/dist/cli/commands/snapshot.js.map +0 -1
  388. package/dist/cli/commands/specification.d.ts +0 -13
  389. package/dist/cli/commands/specification.d.ts.map +0 -1
  390. package/dist/cli/commands/specification.js +0 -45
  391. package/dist/cli/commands/specification.js.map +0 -1
  392. package/dist/cli/commands/start.d.ts +0 -13
  393. package/dist/cli/commands/start.d.ts.map +0 -1
  394. package/dist/cli/commands/start.js +0 -20
  395. package/dist/cli/commands/start.js.map +0 -1
  396. package/dist/cli/commands/stats.d.ts +0 -12
  397. package/dist/cli/commands/stats.d.ts.map +0 -1
  398. package/dist/cli/commands/stats.js +0 -35
  399. package/dist/cli/commands/stats.js.map +0 -1
  400. package/dist/cli/commands/sticky.d.ts +0 -16
  401. package/dist/cli/commands/sticky.d.ts.map +0 -1
  402. package/dist/cli/commands/sticky.js +0 -218
  403. package/dist/cli/commands/sticky.js.map +0 -1
  404. package/dist/cli/commands/stop.d.ts +0 -13
  405. package/dist/cli/commands/stop.d.ts.map +0 -1
  406. package/dist/cli/commands/stop.js +0 -20
  407. package/dist/cli/commands/stop.js.map +0 -1
  408. package/dist/cli/commands/sync.d.ts +0 -26
  409. package/dist/cli/commands/sync.d.ts.map +0 -1
  410. package/dist/cli/commands/sync.js +0 -82
  411. package/dist/cli/commands/sync.js.map +0 -1
  412. package/dist/cli/commands/testing.d.ts +0 -13
  413. package/dist/cli/commands/testing.d.ts.map +0 -1
  414. package/dist/cli/commands/testing.js +0 -65
  415. package/dist/cli/commands/testing.js.map +0 -1
  416. package/dist/cli/commands/token.d.ts +0 -10
  417. package/dist/cli/commands/token.d.ts.map +0 -1
  418. package/dist/cli/commands/token.js +0 -135
  419. package/dist/cli/commands/token.js.map +0 -1
  420. package/dist/cli/commands/update.d.ts +0 -12
  421. package/dist/cli/commands/update.d.ts.map +0 -1
  422. package/dist/cli/commands/update.js +0 -83
  423. package/dist/cli/commands/update.js.map +0 -1
  424. package/dist/cli/commands/upgrade.d.ts +0 -18
  425. package/dist/cli/commands/upgrade.d.ts.map +0 -1
  426. package/dist/cli/commands/upgrade.js +0 -103
  427. package/dist/cli/commands/upgrade.js.map +0 -1
  428. package/dist/cli/commands/validate.d.ts +0 -12
  429. package/dist/cli/commands/validate.d.ts.map +0 -1
  430. package/dist/cli/commands/validate.js +0 -24
  431. package/dist/cli/commands/validate.js.map +0 -1
  432. package/dist/cli/commands/verify.d.ts +0 -8
  433. package/dist/cli/commands/verify.d.ts.map +0 -1
  434. package/dist/cli/commands/verify.js +0 -28
  435. package/dist/cli/commands/verify.js.map +0 -1
  436. package/dist/cli/commands/web.d.ts +0 -19
  437. package/dist/cli/commands/web.d.ts.map +0 -1
  438. package/dist/cli/commands/web.js +0 -371
  439. package/dist/cli/commands/web.js.map +0 -1
  440. package/dist/cli/field-context.d.ts +0 -32
  441. package/dist/cli/field-context.d.ts.map +0 -1
  442. package/dist/cli/field-context.js +0 -47
  443. package/dist/cli/field-context.js.map +0 -1
  444. package/dist/cli/format-context.d.ts +0 -32
  445. package/dist/cli/format-context.d.ts.map +0 -1
  446. package/dist/cli/format-context.js +0 -50
  447. package/dist/cli/format-context.js.map +0 -1
  448. package/dist/cli/help-generator.d.ts +0 -74
  449. package/dist/cli/help-generator.d.ts.map +0 -1
  450. package/dist/cli/help-generator.js +0 -229
  451. package/dist/cli/help-generator.js.map +0 -1
  452. package/dist/cli/help-renderer.d.ts +0 -28
  453. package/dist/cli/help-renderer.d.ts.map +0 -1
  454. package/dist/cli/help-renderer.js +0 -301
  455. package/dist/cli/help-renderer.js.map +0 -1
  456. package/dist/cli/index.d.ts +0 -9
  457. package/dist/cli/index.d.ts.map +0 -1
  458. package/dist/cli/logger-bootstrap.d.ts +0 -6
  459. package/dist/cli/logger-bootstrap.d.ts.map +0 -1
  460. package/dist/cli/logger-bootstrap.js +0 -10
  461. package/dist/cli/logger-bootstrap.js.map +0 -1
  462. package/dist/cli/middleware/output-format.d.ts +0 -30
  463. package/dist/cli/middleware/output-format.d.ts.map +0 -1
  464. package/dist/cli/middleware/output-format.js +0 -35
  465. package/dist/cli/middleware/output-format.js.map +0 -1
  466. package/dist/cli/progress.d.ts +0 -84
  467. package/dist/cli/progress.d.ts.map +0 -1
  468. package/dist/cli/progress.js +0 -169
  469. package/dist/cli/progress.js.map +0 -1
  470. package/dist/cli/renderers/colors.d.ts +0 -32
  471. package/dist/cli/renderers/colors.d.ts.map +0 -1
  472. package/dist/cli/renderers/colors.js +0 -141
  473. package/dist/cli/renderers/colors.js.map +0 -1
  474. package/dist/cli/renderers/error.d.ts +0 -13
  475. package/dist/cli/renderers/error.d.ts.map +0 -1
  476. package/dist/cli/renderers/error.js +0 -42
  477. package/dist/cli/renderers/error.js.map +0 -1
  478. package/dist/cli/renderers/index.d.ts +0 -87
  479. package/dist/cli/renderers/index.d.ts.map +0 -1
  480. package/dist/cli/renderers/index.js +0 -262
  481. package/dist/cli/renderers/index.js.map +0 -1
  482. package/dist/cli/renderers/lafs-validator.d.ts +0 -91
  483. package/dist/cli/renderers/lafs-validator.d.ts.map +0 -1
  484. package/dist/cli/renderers/lafs-validator.js +0 -176
  485. package/dist/cli/renderers/lafs-validator.js.map +0 -1
  486. package/dist/cli/renderers/normalizer.d.ts +0 -21
  487. package/dist/cli/renderers/normalizer.d.ts.map +0 -1
  488. package/dist/cli/renderers/normalizer.js +0 -106
  489. package/dist/cli/renderers/normalizer.js.map +0 -1
  490. package/dist/cli/renderers/system.d.ts +0 -25
  491. package/dist/cli/renderers/system.d.ts.map +0 -1
  492. package/dist/cli/renderers/system.js +0 -416
  493. package/dist/cli/renderers/system.js.map +0 -1
  494. package/dist/cli/renderers/tasks.d.ts +0 -28
  495. package/dist/cli/renderers/tasks.d.ts.map +0 -1
  496. package/dist/cli/renderers/tasks.js +0 -306
  497. package/dist/cli/renderers/tasks.js.map +0 -1
  498. package/dist/dispatch/adapters/cli.d.ts +0 -67
  499. package/dist/dispatch/adapters/cli.d.ts.map +0 -1
  500. package/dist/dispatch/adapters/cli.js +0 -331
  501. package/dist/dispatch/adapters/cli.js.map +0 -1
  502. package/dist/dispatch/context/session-context.d.ts +0 -54
  503. package/dist/dispatch/context/session-context.d.ts.map +0 -1
  504. package/dist/dispatch/context/session-context.js +0 -61
  505. package/dist/dispatch/context/session-context.js.map +0 -1
  506. package/dist/dispatch/dispatcher.d.ts +0 -23
  507. package/dist/dispatch/dispatcher.d.ts.map +0 -1
  508. package/dist/dispatch/dispatcher.js +0 -84
  509. package/dist/dispatch/dispatcher.js.map +0 -1
  510. package/dist/dispatch/domains/_base.d.ts +0 -59
  511. package/dist/dispatch/domains/_base.d.ts.map +0 -1
  512. package/dist/dispatch/domains/_base.js +0 -77
  513. package/dist/dispatch/domains/_base.js.map +0 -1
  514. package/dist/dispatch/domains/_meta.d.ts +0 -23
  515. package/dist/dispatch/domains/_meta.d.ts.map +0 -1
  516. package/dist/dispatch/domains/_meta.js +0 -25
  517. package/dist/dispatch/domains/_meta.js.map +0 -1
  518. package/dist/dispatch/domains/_routing.d.ts +0 -8
  519. package/dist/dispatch/domains/_routing.d.ts.map +0 -1
  520. package/dist/dispatch/domains/_routing.js +0 -20
  521. package/dist/dispatch/domains/_routing.js.map +0 -1
  522. package/dist/dispatch/domains/admin.d.ts +0 -25
  523. package/dist/dispatch/domains/admin.d.ts.map +0 -1
  524. package/dist/dispatch/domains/admin.js +0 -791
  525. package/dist/dispatch/domains/admin.js.map +0 -1
  526. package/dist/dispatch/domains/check.d.ts +0 -22
  527. package/dist/dispatch/domains/check.d.ts.map +0 -1
  528. package/dist/dispatch/domains/check.js +0 -381
  529. package/dist/dispatch/domains/check.js.map +0 -1
  530. package/dist/dispatch/domains/conduit.d.ts +0 -38
  531. package/dist/dispatch/domains/conduit.d.ts.map +0 -1
  532. package/dist/dispatch/domains/conduit.js +0 -360
  533. package/dist/dispatch/domains/conduit.js.map +0 -1
  534. package/dist/dispatch/domains/diagnostics.d.ts +0 -20
  535. package/dist/dispatch/domains/diagnostics.d.ts.map +0 -1
  536. package/dist/dispatch/domains/diagnostics.js +0 -77
  537. package/dist/dispatch/domains/diagnostics.js.map +0 -1
  538. package/dist/dispatch/domains/index.d.ts +0 -29
  539. package/dist/dispatch/domains/index.d.ts.map +0 -1
  540. package/dist/dispatch/domains/index.js +0 -45
  541. package/dist/dispatch/domains/index.js.map +0 -1
  542. package/dist/dispatch/domains/intelligence.d.ts +0 -26
  543. package/dist/dispatch/domains/intelligence.d.ts.map +0 -1
  544. package/dist/dispatch/domains/intelligence.js +0 -154
  545. package/dist/dispatch/domains/intelligence.js.map +0 -1
  546. package/dist/dispatch/domains/memory.d.ts +0 -22
  547. package/dist/dispatch/domains/memory.d.ts.map +0 -1
  548. package/dist/dispatch/domains/memory.js +0 -387
  549. package/dist/dispatch/domains/memory.js.map +0 -1
  550. package/dist/dispatch/domains/nexus.d.ts +0 -22
  551. package/dist/dispatch/domains/nexus.d.ts.map +0 -1
  552. package/dist/dispatch/domains/nexus.js +0 -286
  553. package/dist/dispatch/domains/nexus.js.map +0 -1
  554. package/dist/dispatch/domains/orchestrate.d.ts +0 -26
  555. package/dist/dispatch/domains/orchestrate.d.ts.map +0 -1
  556. package/dist/dispatch/domains/orchestrate.js +0 -691
  557. package/dist/dispatch/domains/orchestrate.js.map +0 -1
  558. package/dist/dispatch/domains/pipeline.d.ts +0 -35
  559. package/dist/dispatch/domains/pipeline.d.ts.map +0 -1
  560. package/dist/dispatch/domains/pipeline.js +0 -593
  561. package/dist/dispatch/domains/pipeline.js.map +0 -1
  562. package/dist/dispatch/domains/session.d.ts +0 -22
  563. package/dist/dispatch/domains/session.d.ts.map +0 -1
  564. package/dist/dispatch/domains/session.js +0 -267
  565. package/dist/dispatch/domains/session.js.map +0 -1
  566. package/dist/dispatch/domains/sticky.d.ts +0 -20
  567. package/dist/dispatch/domains/sticky.d.ts.map +0 -1
  568. package/dist/dispatch/domains/sticky.js +0 -167
  569. package/dist/dispatch/domains/sticky.js.map +0 -1
  570. package/dist/dispatch/domains/tasks.d.ts +0 -25
  571. package/dist/dispatch/domains/tasks.d.ts.map +0 -1
  572. package/dist/dispatch/domains/tasks.js +0 -368
  573. package/dist/dispatch/domains/tasks.js.map +0 -1
  574. package/dist/dispatch/domains/tools.d.ts +0 -37
  575. package/dist/dispatch/domains/tools.d.ts.map +0 -1
  576. package/dist/dispatch/domains/tools.js +0 -481
  577. package/dist/dispatch/domains/tools.js.map +0 -1
  578. package/dist/dispatch/engines/_error.d.ts +0 -119
  579. package/dist/dispatch/engines/_error.d.ts.map +0 -1
  580. package/dist/dispatch/engines/_error.js +0 -298
  581. package/dist/dispatch/engines/_error.js.map +0 -1
  582. package/dist/dispatch/engines/code-engine.d.ts +0 -18
  583. package/dist/dispatch/engines/code-engine.d.ts.map +0 -1
  584. package/dist/dispatch/engines/code-engine.js +0 -71
  585. package/dist/dispatch/engines/code-engine.js.map +0 -1
  586. package/dist/dispatch/engines/codebase-map-engine.d.ts +0 -31
  587. package/dist/dispatch/engines/codebase-map-engine.d.ts.map +0 -1
  588. package/dist/dispatch/engines/codebase-map-engine.js +0 -43
  589. package/dist/dispatch/engines/codebase-map-engine.js.map +0 -1
  590. package/dist/dispatch/engines/config-engine.d.ts +0 -32
  591. package/dist/dispatch/engines/config-engine.d.ts.map +0 -1
  592. package/dist/dispatch/engines/config-engine.js +0 -70
  593. package/dist/dispatch/engines/config-engine.js.map +0 -1
  594. package/dist/dispatch/engines/diagnostics-engine.d.ts +0 -57
  595. package/dist/dispatch/engines/diagnostics-engine.d.ts.map +0 -1
  596. package/dist/dispatch/engines/diagnostics-engine.js +0 -163
  597. package/dist/dispatch/engines/diagnostics-engine.js.map +0 -1
  598. package/dist/dispatch/engines/hooks-engine.d.ts +0 -96
  599. package/dist/dispatch/engines/hooks-engine.d.ts.map +0 -1
  600. package/dist/dispatch/engines/hooks-engine.js +0 -144
  601. package/dist/dispatch/engines/hooks-engine.js.map +0 -1
  602. package/dist/dispatch/engines/init-engine.d.ts +0 -56
  603. package/dist/dispatch/engines/init-engine.d.ts.map +0 -1
  604. package/dist/dispatch/engines/init-engine.js +0 -78
  605. package/dist/dispatch/engines/init-engine.js.map +0 -1
  606. package/dist/dispatch/engines/lifecycle-engine.d.ts +0 -66
  607. package/dist/dispatch/engines/lifecycle-engine.d.ts.map +0 -1
  608. package/dist/dispatch/engines/lifecycle-engine.js +0 -224
  609. package/dist/dispatch/engines/lifecycle-engine.js.map +0 -1
  610. package/dist/dispatch/engines/memory-engine.d.ts +0 -10
  611. package/dist/dispatch/engines/memory-engine.d.ts.map +0 -1
  612. package/dist/dispatch/engines/memory-engine.js +0 -10
  613. package/dist/dispatch/engines/memory-engine.js.map +0 -1
  614. package/dist/dispatch/engines/nexus-engine.d.ts +0 -167
  615. package/dist/dispatch/engines/nexus-engine.d.ts.map +0 -1
  616. package/dist/dispatch/engines/nexus-engine.js +0 -356
  617. package/dist/dispatch/engines/nexus-engine.js.map +0 -1
  618. package/dist/dispatch/engines/orchestrate-engine.d.ts +0 -141
  619. package/dist/dispatch/engines/orchestrate-engine.d.ts.map +0 -1
  620. package/dist/dispatch/engines/orchestrate-engine.js +0 -892
  621. package/dist/dispatch/engines/orchestrate-engine.js.map +0 -1
  622. package/dist/dispatch/engines/pipeline-engine.d.ts +0 -51
  623. package/dist/dispatch/engines/pipeline-engine.d.ts.map +0 -1
  624. package/dist/dispatch/engines/pipeline-engine.js +0 -191
  625. package/dist/dispatch/engines/pipeline-engine.js.map +0 -1
  626. package/dist/dispatch/engines/release-engine.d.ts +0 -94
  627. package/dist/dispatch/engines/release-engine.d.ts.map +0 -1
  628. package/dist/dispatch/engines/release-engine.js +0 -763
  629. package/dist/dispatch/engines/release-engine.js.map +0 -1
  630. package/dist/dispatch/engines/session-engine.d.ts +0 -387
  631. package/dist/dispatch/engines/session-engine.d.ts.map +0 -1
  632. package/dist/dispatch/engines/session-engine.js +0 -924
  633. package/dist/dispatch/engines/session-engine.js.map +0 -1
  634. package/dist/dispatch/engines/sticky-engine.d.ts +0 -100
  635. package/dist/dispatch/engines/sticky-engine.d.ts.map +0 -1
  636. package/dist/dispatch/engines/sticky-engine.js +0 -181
  637. package/dist/dispatch/engines/sticky-engine.js.map +0 -1
  638. package/dist/dispatch/engines/system-engine.d.ts +0 -543
  639. package/dist/dispatch/engines/system-engine.d.ts.map +0 -1
  640. package/dist/dispatch/engines/system-engine.js +0 -1273
  641. package/dist/dispatch/engines/system-engine.js.map +0 -1
  642. package/dist/dispatch/engines/task-engine.d.ts +0 -971
  643. package/dist/dispatch/engines/task-engine.d.ts.map +0 -1
  644. package/dist/dispatch/engines/task-engine.js +0 -1255
  645. package/dist/dispatch/engines/task-engine.js.map +0 -1
  646. package/dist/dispatch/engines/template-parser.d.ts +0 -85
  647. package/dist/dispatch/engines/template-parser.d.ts.map +0 -1
  648. package/dist/dispatch/engines/template-parser.js +0 -108
  649. package/dist/dispatch/engines/template-parser.js.map +0 -1
  650. package/dist/dispatch/engines/tools-engine.d.ts +0 -270
  651. package/dist/dispatch/engines/tools-engine.d.ts.map +0 -1
  652. package/dist/dispatch/engines/tools-engine.js +0 -663
  653. package/dist/dispatch/engines/tools-engine.js.map +0 -1
  654. package/dist/dispatch/engines/validate-engine.d.ts +0 -218
  655. package/dist/dispatch/engines/validate-engine.d.ts.map +0 -1
  656. package/dist/dispatch/engines/validate-engine.js +0 -737
  657. package/dist/dispatch/engines/validate-engine.js.map +0 -1
  658. package/dist/dispatch/index.d.ts +0 -20
  659. package/dist/dispatch/index.d.ts.map +0 -1
  660. package/dist/dispatch/index.js +0 -19
  661. package/dist/dispatch/index.js.map +0 -1
  662. package/dist/dispatch/lib/background-jobs.d.ts +0 -86
  663. package/dist/dispatch/lib/background-jobs.d.ts.map +0 -1
  664. package/dist/dispatch/lib/background-jobs.js +0 -183
  665. package/dist/dispatch/lib/background-jobs.js.map +0 -1
  666. package/dist/dispatch/lib/budget.d.ts +0 -36
  667. package/dist/dispatch/lib/budget.d.ts.map +0 -1
  668. package/dist/dispatch/lib/budget.js +0 -109
  669. package/dist/dispatch/lib/budget.js.map +0 -1
  670. package/dist/dispatch/lib/capability-matrix.d.ts +0 -11
  671. package/dist/dispatch/lib/capability-matrix.d.ts.map +0 -1
  672. package/dist/dispatch/lib/capability-matrix.js +0 -10
  673. package/dist/dispatch/lib/capability-matrix.js.map +0 -1
  674. package/dist/dispatch/lib/config-loader.d.ts +0 -42
  675. package/dist/dispatch/lib/config-loader.d.ts.map +0 -1
  676. package/dist/dispatch/lib/config-loader.js +0 -217
  677. package/dist/dispatch/lib/config-loader.js.map +0 -1
  678. package/dist/dispatch/lib/config.d.ts +0 -11
  679. package/dist/dispatch/lib/config.d.ts.map +0 -1
  680. package/dist/dispatch/lib/config.js +0 -10
  681. package/dist/dispatch/lib/config.js.map +0 -1
  682. package/dist/dispatch/lib/defaults.d.ts +0 -115
  683. package/dist/dispatch/lib/defaults.d.ts.map +0 -1
  684. package/dist/dispatch/lib/defaults.js +0 -61
  685. package/dist/dispatch/lib/defaults.js.map +0 -1
  686. package/dist/dispatch/lib/engine.d.ts +0 -26
  687. package/dist/dispatch/lib/engine.d.ts.map +0 -1
  688. package/dist/dispatch/lib/engine.js +0 -46
  689. package/dist/dispatch/lib/engine.js.map +0 -1
  690. package/dist/dispatch/lib/exit-codes.d.ts +0 -35
  691. package/dist/dispatch/lib/exit-codes.d.ts.map +0 -1
  692. package/dist/dispatch/lib/exit-codes.js +0 -60
  693. package/dist/dispatch/lib/exit-codes.js.map +0 -1
  694. package/dist/dispatch/lib/gateway-meta.d.ts +0 -37
  695. package/dist/dispatch/lib/gateway-meta.d.ts.map +0 -1
  696. package/dist/dispatch/lib/gateway-meta.js +0 -50
  697. package/dist/dispatch/lib/gateway-meta.js.map +0 -1
  698. package/dist/dispatch/lib/job-manager-accessor.d.ts +0 -9
  699. package/dist/dispatch/lib/job-manager-accessor.d.ts.map +0 -1
  700. package/dist/dispatch/lib/job-manager-accessor.js +0 -13
  701. package/dist/dispatch/lib/job-manager-accessor.js.map +0 -1
  702. package/dist/dispatch/lib/meta.d.ts +0 -26
  703. package/dist/dispatch/lib/meta.d.ts.map +0 -1
  704. package/dist/dispatch/lib/meta.js +0 -37
  705. package/dist/dispatch/lib/meta.js.map +0 -1
  706. package/dist/dispatch/lib/param-utils.d.ts +0 -11
  707. package/dist/dispatch/lib/param-utils.d.ts.map +0 -1
  708. package/dist/dispatch/lib/param-utils.js +0 -10
  709. package/dist/dispatch/lib/param-utils.js.map +0 -1
  710. package/dist/dispatch/lib/projections.d.ts +0 -56
  711. package/dist/dispatch/lib/projections.d.ts.map +0 -1
  712. package/dist/dispatch/lib/projections.js +0 -65
  713. package/dist/dispatch/lib/projections.js.map +0 -1
  714. package/dist/dispatch/lib/proto-envelope.d.ts +0 -56
  715. package/dist/dispatch/lib/proto-envelope.d.ts.map +0 -1
  716. package/dist/dispatch/lib/proto-envelope.js +0 -17
  717. package/dist/dispatch/lib/proto-envelope.js.map +0 -1
  718. package/dist/dispatch/lib/schema-utils.d.ts +0 -39
  719. package/dist/dispatch/lib/schema-utils.d.ts.map +0 -1
  720. package/dist/dispatch/lib/schema-utils.js +0 -88
  721. package/dist/dispatch/lib/schema-utils.js.map +0 -1
  722. package/dist/dispatch/lib/security.d.ts +0 -11
  723. package/dist/dispatch/lib/security.d.ts.map +0 -1
  724. package/dist/dispatch/lib/security.js +0 -10
  725. package/dist/dispatch/lib/security.js.map +0 -1
  726. package/dist/dispatch/middleware/audit.d.ts +0 -23
  727. package/dist/dispatch/middleware/audit.d.ts.map +0 -1
  728. package/dist/dispatch/middleware/audit.js +0 -169
  729. package/dist/dispatch/middleware/audit.js.map +0 -1
  730. package/dist/dispatch/middleware/field-filter.d.ts +0 -25
  731. package/dist/dispatch/middleware/field-filter.d.ts.map +0 -1
  732. package/dist/dispatch/middleware/field-filter.js +0 -70
  733. package/dist/dispatch/middleware/field-filter.js.map +0 -1
  734. package/dist/dispatch/middleware/pipeline.d.ts +0 -33
  735. package/dist/dispatch/middleware/pipeline.d.ts.map +0 -1
  736. package/dist/dispatch/middleware/pipeline.js +0 -60
  737. package/dist/dispatch/middleware/pipeline.js.map +0 -1
  738. package/dist/dispatch/middleware/projection.d.ts +0 -35
  739. package/dist/dispatch/middleware/projection.d.ts.map +0 -1
  740. package/dist/dispatch/middleware/projection.js +0 -146
  741. package/dist/dispatch/middleware/projection.js.map +0 -1
  742. package/dist/dispatch/middleware/protocol-enforcement.d.ts +0 -30
  743. package/dist/dispatch/middleware/protocol-enforcement.d.ts.map +0 -1
  744. package/dist/dispatch/middleware/protocol-enforcement.js +0 -56
  745. package/dist/dispatch/middleware/protocol-enforcement.js.map +0 -1
  746. package/dist/dispatch/middleware/rate-limiter.d.ts +0 -72
  747. package/dist/dispatch/middleware/rate-limiter.d.ts.map +0 -1
  748. package/dist/dispatch/middleware/rate-limiter.js +0 -127
  749. package/dist/dispatch/middleware/rate-limiter.js.map +0 -1
  750. package/dist/dispatch/middleware/sanitizer.d.ts +0 -24
  751. package/dist/dispatch/middleware/sanitizer.d.ts.map +0 -1
  752. package/dist/dispatch/middleware/sanitizer.js +0 -56
  753. package/dist/dispatch/middleware/sanitizer.js.map +0 -1
  754. package/dist/dispatch/middleware/session-resolver.d.ts +0 -26
  755. package/dist/dispatch/middleware/session-resolver.d.ts.map +0 -1
  756. package/dist/dispatch/middleware/session-resolver.js +0 -65
  757. package/dist/dispatch/middleware/session-resolver.js.map +0 -1
  758. package/dist/dispatch/middleware/telemetry.d.ts +0 -21
  759. package/dist/dispatch/middleware/telemetry.d.ts.map +0 -1
  760. package/dist/dispatch/middleware/telemetry.js +0 -50
  761. package/dist/dispatch/middleware/telemetry.js.map +0 -1
  762. package/dist/dispatch/middleware/verification-gates.d.ts +0 -22
  763. package/dist/dispatch/middleware/verification-gates.d.ts.map +0 -1
  764. package/dist/dispatch/middleware/verification-gates.js +0 -59
  765. package/dist/dispatch/middleware/verification-gates.js.map +0 -1
  766. package/dist/dispatch/registry.d.ts +0 -91
  767. package/dist/dispatch/registry.d.ts.map +0 -1
  768. package/dist/dispatch/registry.js +0 -3535
  769. package/dist/dispatch/registry.js.map +0 -1
  770. package/dist/dispatch/types.d.ts +0 -206
  771. package/dist/dispatch/types.d.ts.map +0 -1
  772. package/dist/dispatch/types.js +0 -27
  773. package/dist/dispatch/types.js.map +0 -1
package/dist/cli/index.js CHANGED
@@ -6,10 +6,16 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
9
15
  var __esm = (fn2, res) => function __init() {
10
16
  return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res;
11
17
  };
12
- var __commonJS = (cb, mod) => function __require() {
18
+ var __commonJS = (cb, mod) => function __require2() {
13
19
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
20
  };
15
21
  var __export = (target, all) => {
@@ -1925,7 +1931,7 @@ var init_sql = __esm({
1925
1931
  return new SQL([new StringChunk(str)]);
1926
1932
  }
1927
1933
  _sql.raw = raw;
1928
- function join135(chunks, separator) {
1934
+ function join136(chunks, separator) {
1929
1935
  const result = [];
1930
1936
  for (const [i, chunk] of chunks.entries()) {
1931
1937
  if (i > 0 && separator !== void 0) result.push(separator);
@@ -1933,7 +1939,7 @@ var init_sql = __esm({
1933
1939
  }
1934
1940
  return new SQL(result);
1935
1941
  }
1936
- _sql.join = join135;
1942
+ _sql.join = join136;
1937
1943
  function identifier(value) {
1938
1944
  return new Name(value);
1939
1945
  }
@@ -6707,7 +6713,7 @@ var init_select2 = __esm({
6707
6713
  const baseTableName = this.tableName;
6708
6714
  const tableName = getTableLikeName(table);
6709
6715
  for (const item of extractUsedTable(table)) this.usedTables.add(item);
6710
- if (typeof tableName === "string" && this.config.joins?.some((join135) => join135.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
6716
+ if (typeof tableName === "string" && this.config.joins?.some((join136) => join136.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
6711
6717
  if (!this.isPartialSelect) {
6712
6718
  if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
6713
6719
  if (typeof tableName === "string" && !is(table, SQL)) {
@@ -7992,7 +7998,7 @@ var init_dialect = __esm({
7992
7998
  if (!joins2) return;
7993
7999
  const withEntries = Object.entries(joins2).filter(([_2, v2]) => v2);
7994
8000
  if (!withEntries.length) return;
7995
- return sql.join(withEntries.map(([k2, join135]) => {
8001
+ return sql.join(withEntries.map(([k2, join136]) => {
7996
8002
  const relation = tableConfig.relations[k2];
7997
8003
  const isSingle2 = is(relation, One3);
7998
8004
  const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
@@ -8003,7 +8009,7 @@ var init_dialect = __esm({
8003
8009
  table: targetTable,
8004
8010
  mode: isSingle2 ? "first" : "many",
8005
8011
  schema,
8006
- queryConfig: join135,
8012
+ queryConfig: join136,
8007
8013
  tableConfig: schema[relation.targetTableName],
8008
8014
  relationWhere: filter,
8009
8015
  isNested: true,
@@ -8017,7 +8023,7 @@ var init_dialect = __esm({
8017
8023
  key: k2,
8018
8024
  selection: innerQuery.selection,
8019
8025
  isArray: !isSingle2,
8020
- isOptional: (relation.optional ?? false) || join135 !== true && !!join135.where
8026
+ isOptional: (relation.optional ?? false) || join136 !== true && !!join136.where
8021
8027
  });
8022
8028
  const jsonColumns = sql.join(innerQuery.selection.map((s3) => {
8023
8029
  return sql`${sql.raw(this.escapeString(s3.key))}, ${s3.selection ? sql`${jsonb2}(${sql.identifier(s3.key)})` : sql.identifier(s3.key)}`;
@@ -8416,7 +8422,7 @@ var init_update = __esm({
8416
8422
  createJoin(joinType) {
8417
8423
  return ((table, on) => {
8418
8424
  const tableName = getTableLikeName(table);
8419
- if (typeof tableName === "string" && this.config.joins.some((join135) => join135.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
8425
+ if (typeof tableName === "string" && this.config.joins.some((join136) => join136.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
8420
8426
  if (typeof on === "function") {
8421
8427
  const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
8422
8428
  on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
@@ -9064,9 +9070,11 @@ __export(brain_schema_exports, {
9064
9070
  BRAIN_STICKY_COLORS: () => BRAIN_STICKY_COLORS,
9065
9071
  BRAIN_STICKY_PRIORITIES: () => BRAIN_STICKY_PRIORITIES,
9066
9072
  BRAIN_STICKY_STATUSES: () => BRAIN_STICKY_STATUSES,
9073
+ brainConsolidationEvents: () => brainConsolidationEvents,
9067
9074
  brainDecisions: () => brainDecisions,
9068
9075
  brainLearnings: () => brainLearnings,
9069
9076
  brainMemoryLinks: () => brainMemoryLinks,
9077
+ brainModulators: () => brainModulators,
9070
9078
  brainObservations: () => brainObservations,
9071
9079
  brainPageEdges: () => brainPageEdges,
9072
9080
  brainPageNodes: () => brainPageNodes,
@@ -9074,10 +9082,11 @@ __export(brain_schema_exports, {
9074
9082
  brainPlasticityEvents: () => brainPlasticityEvents,
9075
9083
  brainRetrievalLog: () => brainRetrievalLog,
9076
9084
  brainSchemaMeta: () => brainSchemaMeta,
9077
- brainStickyNotes: () => brainStickyNotes
9085
+ brainStickyNotes: () => brainStickyNotes,
9086
+ brainWeightHistory: () => brainWeightHistory
9078
9087
  });
9079
9088
  import { sql as sql2 } from "drizzle-orm";
9080
- var BRAIN_MEMORY_TIERS, BRAIN_COGNITIVE_TYPES, BRAIN_SOURCE_CONFIDENCE, BRAIN_DECISION_TYPES, BRAIN_CONFIDENCE_LEVELS, BRAIN_OUTCOME_TYPES, BRAIN_PATTERN_TYPES, BRAIN_IMPACT_LEVELS, BRAIN_LINK_TYPES, BRAIN_OBSERVATION_TYPES2, BRAIN_OBSERVATION_SOURCE_TYPES, BRAIN_MEMORY_TYPES, BRAIN_STICKY_STATUSES, BRAIN_STICKY_COLORS, BRAIN_STICKY_PRIORITIES, brainDecisions, brainPatterns, brainLearnings, brainObservations, brainStickyNotes, brainMemoryLinks, brainSchemaMeta, BRAIN_NODE_TYPES, BRAIN_EDGE_TYPES, brainPageNodes, brainPageEdges, brainRetrievalLog, brainPlasticityEvents;
9089
+ var BRAIN_MEMORY_TIERS, BRAIN_COGNITIVE_TYPES, BRAIN_SOURCE_CONFIDENCE, BRAIN_DECISION_TYPES, BRAIN_CONFIDENCE_LEVELS, BRAIN_OUTCOME_TYPES, BRAIN_PATTERN_TYPES, BRAIN_IMPACT_LEVELS, BRAIN_LINK_TYPES, BRAIN_OBSERVATION_TYPES2, BRAIN_OBSERVATION_SOURCE_TYPES, BRAIN_MEMORY_TYPES, BRAIN_STICKY_STATUSES, BRAIN_STICKY_COLORS, BRAIN_STICKY_PRIORITIES, brainDecisions, brainPatterns, brainLearnings, brainObservations, brainStickyNotes, brainMemoryLinks, brainSchemaMeta, BRAIN_NODE_TYPES, BRAIN_EDGE_TYPES, brainPageNodes, brainPageEdges, brainRetrievalLog, brainPlasticityEvents, brainWeightHistory, brainModulators, brainConsolidationEvents;
9081
9090
  var init_brain_schema = __esm({
9082
9091
  "packages/core/src/store/brain-schema.ts"() {
9083
9092
  "use strict";
@@ -9583,13 +9592,75 @@ var init_brain_schema = __esm({
9583
9592
  * 'auto:contradiction-detected' | 'auto:consolidation' | 'manual'
9584
9593
  */
9585
9594
  provenance: text("provenance"),
9586
- createdAt: text("created_at").notNull().default(sql2`(datetime('now'))`)
9595
+ createdAt: text("created_at").notNull().default(sql2`(datetime('now'))`),
9596
+ // === T673-M3: Plasticity tracking columns ===
9597
+ /**
9598
+ * ISO 8601 timestamp of the last LTP event applied to this edge.
9599
+ * Used by the decay pass: edges with (now - last_reinforced_at) > decay_threshold_days
9600
+ * receive a per-day weight decay. Null = never reinforced (structural/semantic edges).
9601
+ * Only populated when plasticity_class IN ('hebbian', 'stdp').
9602
+ *
9603
+ * @task T706
9604
+ */
9605
+ lastReinforcedAt: text("last_reinforced_at"),
9606
+ /**
9607
+ * Count of LTP (potentiation) events applied to this edge lifetime.
9608
+ * Incremented on every LTP write. Used to compute stability_score.
9609
+ *
9610
+ * @task T706
9611
+ */
9612
+ reinforcementCount: integer("reinforcement_count").notNull().default(0),
9613
+ /**
9614
+ * Plasticity class governing which algorithm(s) write to this edge.
9615
+ *
9616
+ * - 'static': Non-plastic edge (structural, semantic, etc.). Immune to decay.
9617
+ * - 'hebbian': Written by strengthenCoRetrievedEdges. Subject to decay.
9618
+ * - 'stdp': Written or refined by applyStdpPlasticity. Subject to decay + LTD.
9619
+ *
9620
+ * Edges start 'static' for all non-co_retrieved types.
9621
+ * co_retrieved edges start 'hebbian' (seeded by M3 migration), can upgrade to 'stdp'.
9622
+ *
9623
+ * @task T706
9624
+ */
9625
+ plasticityClass: text("plasticity_class", {
9626
+ enum: ["static", "hebbian", "stdp"]
9627
+ }).notNull().default("static"),
9628
+ /**
9629
+ * ISO 8601 timestamp of the last LTD (depression) event on this edge.
9630
+ * Null = never depressed. Used for debugging and Studio viz animation.
9631
+ *
9632
+ * @task T706
9633
+ */
9634
+ lastDepressedAt: text("last_depressed_at"),
9635
+ /**
9636
+ * Count of LTD (depression) events applied to this edge lifetime.
9637
+ * Enables analysis of edges that are persistently weakened.
9638
+ *
9639
+ * @task T706
9640
+ */
9641
+ depressionCount: integer("depression_count").notNull().default(0),
9642
+ /**
9643
+ * Biological-analog stability score: 0.0 (unstable) – 1.0 (consolidated).
9644
+ *
9645
+ * Computed by runConsolidation decay pass as:
9646
+ * stability = tanh(reinforcement_count / 10) × exp(-(days_since_reinforced / 30))
9647
+ *
9648
+ * Null = not yet computed (new edges). Enables fast filtering in decay pass:
9649
+ * edges with stability > 0.9 skip the full decay recalculation.
9650
+ * Updated at session-end consolidation, NOT per-event.
9651
+ *
9652
+ * @task T706
9653
+ */
9654
+ stabilityScore: real("stability_score")
9587
9655
  },
9588
9656
  (table) => [
9589
9657
  primaryKey({ columns: [table.fromId, table.toId, table.edgeType] }),
9590
9658
  index("idx_brain_edges_from").on(table.fromId),
9591
9659
  index("idx_brain_edges_to").on(table.toId),
9592
- index("idx_brain_edges_type").on(table.edgeType)
9660
+ index("idx_brain_edges_type").on(table.edgeType),
9661
+ index("idx_brain_edges_last_reinforced").on(table.lastReinforcedAt),
9662
+ index("idx_brain_edges_plasticity_class").on(table.plasticityClass),
9663
+ index("idx_brain_edges_stability").on(table.stabilityScore)
9593
9664
  ]
9594
9665
  );
9595
9666
  brainRetrievalLog = sqliteTable(
@@ -9598,7 +9669,12 @@ var init_brain_schema = __esm({
9598
9669
  id: integer("id").primaryKey({ autoIncrement: true }),
9599
9670
  /** The search query or fetch IDs that triggered this retrieval. */
9600
9671
  query: text("query").notNull(),
9601
- /** Comma-separated list of entry IDs returned in this retrieval. */
9672
+ /**
9673
+ * JSON array of entry IDs returned in this retrieval.
9674
+ * Stored as JSON array string: '["obs:A","obs:B"]'.
9675
+ * Always write with JSON.stringify() — NEVER join(',').
9676
+ * Readers call JSON.parse(). Migration M1 converts any pre-existing CSV rows.
9677
+ */
9602
9678
  entryIds: text("entry_ids").notNull(),
9603
9679
  /** Number of entries returned. */
9604
9680
  entryCount: integer("entry_count").notNull(),
@@ -9608,12 +9684,26 @@ var init_brain_schema = __esm({
9608
9684
  tokensUsed: integer("tokens_used"),
9609
9685
  /** Session ID (soft FK to tasks.db sessions). Enables grouping retrievals by session for STDP analysis. */
9610
9686
  sessionId: text("session_id"),
9611
- createdAt: text("created_at").notNull().default(sql2`(datetime('now'))`)
9687
+ createdAt: text("created_at").notNull().default(sql2`(datetime('now'))`),
9688
+ // === T673-M1: STDP plasticity columns ===
9689
+ /** Sequence position of this retrieval within a batch query (0-based). */
9690
+ retrievalOrder: integer("retrieval_order"),
9691
+ /** Wall-clock ms since the previous retrieval row in the same batch. */
9692
+ deltaMs: integer("delta_ms"),
9693
+ /**
9694
+ * R-STDP reward signal: scalar [-1.0, +1.0], null = unlabeled.
9695
+ * Populated by backfillRewardSignals() at session end (Step 9a).
9696
+ * +1.0 = task verified and passed | +0.5 = done (unverified) | -0.5 = cancelled.
9697
+ * Per D-BRAIN-VIZ-13. backfillRewardSignals MUST skip rows where
9698
+ * session_id LIKE 'ses_backfill_%' (synthetic historical sessions, no task correlation).
9699
+ */
9700
+ rewardSignal: real("reward_signal")
9612
9701
  },
9613
9702
  (table) => [
9614
9703
  index("idx_retrieval_log_created").on(table.createdAt),
9615
9704
  index("idx_retrieval_log_source").on(table.source),
9616
- index("idx_retrieval_log_session").on(table.sessionId)
9705
+ index("idx_retrieval_log_session").on(table.sessionId),
9706
+ index("idx_retrieval_log_reward").on(table.rewardSignal)
9617
9707
  ]
9618
9708
  );
9619
9709
  brainPlasticityEvents = sqliteTable(
@@ -9637,14 +9727,182 @@ var init_brain_schema = __esm({
9637
9727
  /** ISO 8601 timestamp when this event was applied. */
9638
9728
  timestamp: text("timestamp").notNull().default(sql2`(datetime('now'))`),
9639
9729
  /** Session ID that triggered the STDP pass, if available. */
9640
- sessionId: text("session_id")
9730
+ sessionId: text("session_id"),
9731
+ // === T673-M2: Observability columns ===
9732
+ /**
9733
+ * Edge weight immediately BEFORE this plasticity event was applied.
9734
+ * Null on the first LTP event that inserts a new edge (edge didn't exist).
9735
+ * Enables "show learning history" in Studio viz without querying brain_weight_history.
9736
+ *
9737
+ * @task T696
9738
+ */
9739
+ weightBefore: real("weight_before"),
9740
+ /**
9741
+ * Edge weight immediately AFTER this plasticity event was applied.
9742
+ * Computed as CLAMP(weight_before + delta_w, 0.0, 1.0).
9743
+ * Redundant with delta_w but enables fast before/after display without arithmetic.
9744
+ *
9745
+ * @task T696
9746
+ */
9747
+ weightAfter: real("weight_after"),
9748
+ /**
9749
+ * Soft FK to brain_retrieval_log.id — the retrieval row that triggered this pair.
9750
+ * Null for externally-triggered or legacy events.
9751
+ * Enables: "which memory retrieval caused this edge to strengthen?"
9752
+ *
9753
+ * @task T696
9754
+ */
9755
+ retrievalLogId: integer("retrieval_log_id"),
9756
+ /**
9757
+ * R-STDP reward signal active when this event fired.
9758
+ * Copied from the retrieval_log row's reward_signal at time of plasticity pass.
9759
+ * Null = unmodulated. Denormalized for fast filtering without a JOIN.
9760
+ *
9761
+ * @task T696
9762
+ */
9763
+ rewardSignal: real("reward_signal"),
9764
+ /**
9765
+ * Wall-clock milliseconds between the two spikes that generated this event.
9766
+ * Pre-computed at INSERT time — avoids re-deriving from retrieval timestamps.
9767
+ * Enables analysis of STDP window distribution.
9768
+ *
9769
+ * @task T696
9770
+ */
9771
+ deltaTMs: integer("delta_t_ms")
9641
9772
  },
9642
9773
  (table) => [
9643
9774
  index("idx_plasticity_source").on(table.sourceNode),
9644
9775
  index("idx_plasticity_target").on(table.targetNode),
9645
9776
  index("idx_plasticity_timestamp").on(table.timestamp),
9646
9777
  index("idx_plasticity_session").on(table.sessionId),
9647
- index("idx_plasticity_kind").on(table.kind)
9778
+ index("idx_plasticity_kind").on(table.kind),
9779
+ index("idx_plasticity_retrieval_log").on(table.retrievalLogId),
9780
+ index("idx_plasticity_reward").on(table.rewardSignal)
9781
+ ]
9782
+ );
9783
+ brainWeightHistory = sqliteTable(
9784
+ "brain_weight_history",
9785
+ {
9786
+ id: integer("id").primaryKey({ autoIncrement: true }),
9787
+ /** from_id of the affected brain_page_edges row. */
9788
+ edgeFromId: text("edge_from_id").notNull(),
9789
+ /** to_id of the affected brain_page_edges row. */
9790
+ edgeToId: text("edge_to_id").notNull(),
9791
+ /** Edge type of the affected brain_page_edges row (e.g. 'co_retrieved'). */
9792
+ edgeType: text("edge_type").notNull(),
9793
+ /** Edge weight immediately before this event. Null if the edge was just created. */
9794
+ weightBefore: real("weight_before"),
9795
+ /** Edge weight after this event. CLAMP(weightBefore + deltaWeight, 0, 1). NOT NULL. */
9796
+ weightAfter: real("weight_after").notNull(),
9797
+ /**
9798
+ * Signed weight delta applied to the edge.
9799
+ * Positive = potentiation (LTP/Hebbian), negative = depression (LTD).
9800
+ * Prune events record the final weight that triggered deletion (negative).
9801
+ */
9802
+ deltaWeight: real("delta_weight").notNull(),
9803
+ /**
9804
+ * Plasticity event kind.
9805
+ * 'ltp' — Long-Term Potentiation (STDP pre-before-post)
9806
+ * 'ltd' — Long-Term Depression (STDP post-before-pre)
9807
+ * 'hebbian' — Co-retrieval Hebbian strengthening
9808
+ * 'decay' — Temporal decay (only prune-triggering decays written here)
9809
+ * 'prune' — Edge deleted (weight fell below min_weight threshold)
9810
+ * 'external' — Manually-applied external weight change
9811
+ */
9812
+ eventKind: text("event_kind").notNull(),
9813
+ /** Soft FK to brain_plasticity_events.id — the STDP event that caused this. */
9814
+ sourcePlasticityEventId: integer("source_plasticity_event_id"),
9815
+ /** Soft FK to brain_retrieval_log.id — the retrieval batch that triggered this. */
9816
+ retrievalLogId: integer("retrieval_log_id"),
9817
+ /** R-STDP reward signal at time of event (copied from retrieval_log.reward_signal). */
9818
+ rewardSignal: real("reward_signal"),
9819
+ /** ISO 8601 timestamp when this weight change was applied. */
9820
+ changedAt: text("changed_at").notNull().default(sql2`(datetime('now'))`)
9821
+ },
9822
+ (table) => [
9823
+ index("idx_weight_history_edge").on(table.edgeFromId, table.edgeToId, table.edgeType),
9824
+ index("idx_weight_history_from").on(table.edgeFromId),
9825
+ index("idx_weight_history_to").on(table.edgeToId),
9826
+ index("idx_weight_history_changed_at").on(table.changedAt),
9827
+ index("idx_weight_history_event_kind").on(table.eventKind),
9828
+ index("idx_weight_history_plasticity_event").on(table.sourcePlasticityEventId)
9829
+ ]
9830
+ );
9831
+ brainModulators = sqliteTable(
9832
+ "brain_modulators",
9833
+ {
9834
+ id: integer("id").primaryKey({ autoIncrement: true }),
9835
+ /**
9836
+ * Modulator event type. String (not enum constraint) for extensibility.
9837
+ * Expected values: 'task_verified'|'task_completed'|'task_cancelled'|
9838
+ * 'owner_verify'|'session_success'|'session_blocker'|'external'
9839
+ */
9840
+ modulatorType: text("modulator_type").notNull(),
9841
+ /**
9842
+ * Reward valence in range [-1.0, +1.0].
9843
+ * +1.0 = strong reward (verified correct task)
9844
+ * +0.5 = moderate reward (done, unverified)
9845
+ * -0.5 = mild correction (cancelled task)
9846
+ * -1.0 = strong correction (explicit invalidation)
9847
+ * 0.0 = neutral signal
9848
+ */
9849
+ valence: real("valence").notNull(),
9850
+ /**
9851
+ * Magnitude 0.0–1.0 confidence scaling.
9852
+ * Effective reward = valence × magnitude.
9853
+ * Defaults to 1.0 (full confidence).
9854
+ */
9855
+ magnitude: real("magnitude").notNull().default(1),
9856
+ /** Polymorphic source event ID — task ID, memory entry ID, or other string ref. */
9857
+ sourceEventId: text("source_event_id"),
9858
+ /** Session ID (soft FK to tasks.db sessions). */
9859
+ sessionId: text("session_id"),
9860
+ /** Human-readable description of why this modulator was emitted. */
9861
+ description: text("description"),
9862
+ /** ISO 8601 timestamp when this modulator event was recorded. */
9863
+ createdAt: text("created_at").notNull().default(sql2`(datetime('now'))`)
9864
+ },
9865
+ (table) => [
9866
+ index("idx_modulators_type").on(table.modulatorType),
9867
+ index("idx_modulators_session").on(table.sessionId),
9868
+ index("idx_modulators_created_at").on(table.createdAt),
9869
+ index("idx_modulators_source_event").on(table.sourceEventId),
9870
+ index("idx_modulators_valence").on(table.valence)
9871
+ ]
9872
+ );
9873
+ brainConsolidationEvents = sqliteTable(
9874
+ "brain_consolidation_events",
9875
+ {
9876
+ id: integer("id").primaryKey({ autoIncrement: true }),
9877
+ /**
9878
+ * What triggered this consolidation run. String (not enum constraint) for
9879
+ * forward compatibility with T628 scheduler.
9880
+ * Expected values: 'session_end' | 'maintenance' | 'scheduled' | 'manual'
9881
+ */
9882
+ trigger: text("trigger").notNull(),
9883
+ /** Session ID that initiated this consolidation (soft FK to tasks.db sessions). */
9884
+ sessionId: text("session_id"),
9885
+ /**
9886
+ * JSON-serialized ConsolidationResult — all per-step counts and metrics.
9887
+ * Shape: { [stepName: string]: { count: number, durationMs?: number } }
9888
+ * Required NOT NULL — every run must record its results for T628 scheduling.
9889
+ */
9890
+ stepResultsJson: text("step_results_json").notNull(),
9891
+ /** Wall-clock milliseconds from start to completion. Null if run did not complete. */
9892
+ durationMs: integer("duration_ms"),
9893
+ /**
9894
+ * Whether the run succeeded.
9895
+ * Stored as integer(boolean) per Drizzle SQLite boolean convention.
9896
+ * true = completed without unhandled error, false = partial or error.
9897
+ */
9898
+ succeeded: integer("succeeded", { mode: "boolean" }).notNull().default(true),
9899
+ /** ISO 8601 timestamp when this consolidation run started. */
9900
+ startedAt: text("started_at").notNull().default(sql2`(datetime('now'))`)
9901
+ },
9902
+ (table) => [
9903
+ index("idx_consolidation_events_started_at").on(table.startedAt),
9904
+ index("idx_consolidation_events_trigger").on(table.trigger),
9905
+ index("idx_consolidation_events_session").on(table.sessionId)
9648
9906
  ]
9649
9907
  );
9650
9908
  }
@@ -15013,56 +15271,116 @@ function runBrainMigrations(nativeDb, db) {
15013
15271
  }
15014
15272
  reconcileJournal(nativeDb, migrationsFolder, "brain_decisions", "brain");
15015
15273
  migrateWithRetry(db, migrationsFolder, nativeDb, "brain_decisions", "brain");
15016
- ensureColumns(
15017
- nativeDb,
15018
- "brain_page_nodes",
15019
- [
15020
- { name: "quality_score", ddl: "real DEFAULT 0.5" },
15021
- { name: "content_hash", ddl: "text" },
15022
- { name: "last_activity_at", ddl: "text" },
15023
- { name: "updated_at", ddl: "text" }
15024
- ],
15025
- "brain"
15026
- );
15027
- for (const table of [
15028
- "brain_decisions",
15029
- "brain_patterns",
15030
- "brain_learnings",
15031
- "brain_observations"
15032
- ]) {
15033
- ensureColumns(nativeDb, table, [{ name: "quality_score", ddl: "real" }], "brain");
15274
+ if (tableExists(nativeDb, "brain_page_edges")) {
15275
+ nativeDb.prepare(
15276
+ `UPDATE brain_page_edges
15277
+ SET edge_type = 'co_retrieved'
15278
+ WHERE edge_type = 'relates_to'
15279
+ AND provenance LIKE 'consolidation:%'`
15280
+ ).run();
15034
15281
  }
15035
- for (const table of [
15036
- "brain_decisions",
15037
- "brain_patterns",
15038
- "brain_learnings",
15039
- "brain_observations"
15040
- ]) {
15282
+ if (tableExists(nativeDb, "brain_retrieval_log")) {
15283
+ ensureColumns(
15284
+ nativeDb,
15285
+ "brain_retrieval_log",
15286
+ [
15287
+ { name: "session_id", ddl: "text" },
15288
+ { name: "reward_signal", ddl: "real" },
15289
+ { name: "retrieval_order", ddl: "integer" },
15290
+ { name: "delta_ms", ddl: "integer" }
15291
+ ],
15292
+ "brain"
15293
+ );
15294
+ }
15295
+ if (tableExists(nativeDb, "brain_plasticity_events")) {
15041
15296
  ensureColumns(
15042
15297
  nativeDb,
15043
- table,
15298
+ "brain_plasticity_events",
15044
15299
  [
15045
- { name: "memory_tier", ddl: "text DEFAULT 'short'" },
15046
- { name: "memory_type", ddl: "text DEFAULT 'episodic'" },
15047
- { name: "verified", ddl: "integer NOT NULL DEFAULT 0" },
15048
- // valid_at uses nullable text (no datetime('now') default) because
15049
- // ALTER TABLE ADD COLUMN with non-constant defaults fails on non-empty tables.
15050
- { name: "valid_at", ddl: "text" },
15051
- { name: "invalid_at", ddl: "text" },
15052
- { name: "source_confidence", ddl: "text DEFAULT 'agent'" },
15053
- { name: "citation_count", ddl: "integer NOT NULL DEFAULT 0" }
15300
+ { name: "session_id", ddl: "text" },
15301
+ { name: "weight_before", ddl: "real" },
15302
+ { name: "weight_after", ddl: "real" },
15303
+ { name: "retrieval_log_id", ddl: "integer" },
15304
+ { name: "reward_signal", ddl: "real" },
15305
+ { name: "delta_t_ms", ddl: "integer" }
15054
15306
  ],
15055
15307
  "brain"
15056
15308
  );
15057
15309
  }
15310
+ ensureColumns(
15311
+ nativeDb,
15312
+ "brain_page_edges",
15313
+ [
15314
+ { name: "last_reinforced_at", ddl: "text" },
15315
+ { name: "reinforcement_count", ddl: "integer NOT NULL DEFAULT 0" },
15316
+ { name: "plasticity_class", ddl: "text NOT NULL DEFAULT 'static'" },
15317
+ { name: "last_depressed_at", ddl: "text" },
15318
+ { name: "depression_count", ddl: "integer NOT NULL DEFAULT 0" },
15319
+ { name: "stability_score", ddl: "real" }
15320
+ ],
15321
+ "brain"
15322
+ );
15058
15323
  if (tableExists(nativeDb, "brain_page_edges")) {
15059
15324
  nativeDb.prepare(
15060
- `UPDATE brain_page_edges
15061
- SET edge_type = 'co_retrieved'
15062
- WHERE edge_type = 'relates_to'
15063
- AND provenance LIKE 'consolidation:%'`
15325
+ `UPDATE brain_page_edges SET plasticity_class = 'hebbian'
15326
+ WHERE edge_type = 'co_retrieved' AND plasticity_class = 'static'`
15064
15327
  ).run();
15065
15328
  }
15329
+ nativeDb.exec(
15330
+ `CREATE TABLE IF NOT EXISTS brain_weight_history (
15331
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
15332
+ edge_from_id TEXT NOT NULL,
15333
+ edge_to_id TEXT NOT NULL,
15334
+ edge_type TEXT NOT NULL,
15335
+ weight_before REAL,
15336
+ weight_after REAL NOT NULL,
15337
+ delta_weight REAL NOT NULL,
15338
+ event_kind TEXT NOT NULL,
15339
+ source_plasticity_event_id INTEGER,
15340
+ retrieval_log_id INTEGER,
15341
+ reward_signal REAL,
15342
+ changed_at TEXT NOT NULL DEFAULT (datetime('now'))
15343
+ )`
15344
+ );
15345
+ nativeDb.exec(
15346
+ `CREATE INDEX IF NOT EXISTS idx_weight_history_edge
15347
+ ON brain_weight_history (edge_from_id, edge_to_id, edge_type)`
15348
+ );
15349
+ nativeDb.exec(
15350
+ `CREATE INDEX IF NOT EXISTS idx_weight_history_changed_at
15351
+ ON brain_weight_history (changed_at)`
15352
+ );
15353
+ nativeDb.exec(
15354
+ `CREATE TABLE IF NOT EXISTS brain_modulators (
15355
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
15356
+ modulator_type TEXT NOT NULL,
15357
+ valence REAL NOT NULL,
15358
+ magnitude REAL NOT NULL DEFAULT 1.0,
15359
+ source_event_id TEXT,
15360
+ session_id TEXT,
15361
+ description TEXT,
15362
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
15363
+ )`
15364
+ );
15365
+ nativeDb.exec(
15366
+ `CREATE INDEX IF NOT EXISTS idx_modulators_session
15367
+ ON brain_modulators (session_id)`
15368
+ );
15369
+ nativeDb.exec(
15370
+ `CREATE TABLE IF NOT EXISTS brain_consolidation_events (
15371
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
15372
+ trigger TEXT NOT NULL,
15373
+ session_id TEXT,
15374
+ step_results_json TEXT NOT NULL,
15375
+ duration_ms INTEGER,
15376
+ succeeded INTEGER NOT NULL DEFAULT 1,
15377
+ started_at TEXT NOT NULL DEFAULT (datetime('now'))
15378
+ )`
15379
+ );
15380
+ nativeDb.exec(
15381
+ `CREATE INDEX IF NOT EXISTS idx_consolidation_events_started_at
15382
+ ON brain_consolidation_events (started_at)`
15383
+ );
15066
15384
  }
15067
15385
  function loadBrainVecExtension(nativeDb) {
15068
15386
  try {
@@ -16207,7 +16525,8 @@ async function createSqliteDataAccessor(cwd) {
16207
16525
  ["createdBy", "createdBy"],
16208
16526
  ["modifiedBy", "modifiedBy"],
16209
16527
  ["sessionId", "sessionId"],
16210
- ["assignee", "assignee"]
16528
+ ["assignee", "assignee"],
16529
+ ["pipelineStage", "pipelineStage"]
16211
16530
  ];
16212
16531
  for (const [key, col] of fieldMap) {
16213
16532
  if (fields[key] !== void 0) {
@@ -18638,13 +18957,48 @@ var init_adrs = __esm({
18638
18957
  var brain_accessor_exports = {};
18639
18958
  __export(brain_accessor_exports, {
18640
18959
  BrainDataAccessor: () => BrainDataAccessor,
18641
- getBrainAccessor: () => getBrainAccessor
18960
+ getBrainAccessor: () => getBrainAccessor,
18961
+ insertModulatorRow: () => insertModulatorRow,
18962
+ insertWeightHistoryRow: () => insertWeightHistoryRow,
18963
+ logConsolidationComplete: () => logConsolidationComplete,
18964
+ logConsolidationStart: () => logConsolidationStart
18642
18965
  });
18643
18966
  import { and as and5, asc as asc2, desc as desc2, eq as eq7, gte as gte2, or as or4 } from "drizzle-orm";
18644
18967
  async function getBrainAccessor(cwd) {
18645
18968
  const db = await getBrainDb(cwd);
18646
18969
  return new BrainDataAccessor(db);
18647
18970
  }
18971
+ async function insertWeightHistoryRow(cwd, input) {
18972
+ const db = await getBrainDb(cwd);
18973
+ const result = await db.insert(brainWeightHistory).values(input).returning();
18974
+ return result[0];
18975
+ }
18976
+ async function insertModulatorRow(cwd, input) {
18977
+ const db = await getBrainDb(cwd);
18978
+ const result = await db.insert(brainModulators).values(input).returning();
18979
+ return result[0];
18980
+ }
18981
+ async function logConsolidationStart(cwd, trigger, sessionId) {
18982
+ const db = await getBrainDb(cwd);
18983
+ const result = await db.insert(brainConsolidationEvents).values({
18984
+ trigger,
18985
+ sessionId: sessionId ?? null,
18986
+ // stepResultsJson is required NOT NULL — use empty object as placeholder
18987
+ // until logConsolidationComplete updates it with final step results.
18988
+ stepResultsJson: "{}",
18989
+ succeeded: true
18990
+ }).returning({ id: brainConsolidationEvents.id });
18991
+ return result[0].id;
18992
+ }
18993
+ async function logConsolidationComplete(cwd, id, stats2, durationMs, succeeded = true) {
18994
+ const db = await getBrainDb(cwd);
18995
+ const result = await db.update(brainConsolidationEvents).set({
18996
+ stepResultsJson: JSON.stringify(stats2),
18997
+ durationMs,
18998
+ succeeded
18999
+ }).where(eq7(brainConsolidationEvents.id, id)).returning();
19000
+ return result[0];
19001
+ }
18648
19002
  var BrainDataAccessor;
18649
19003
  var init_brain_accessor = __esm({
18650
19004
  "packages/core/src/store/brain-accessor.ts"() {
@@ -46519,13 +46873,147 @@ var init_graph_memory_bridge = __esm({
46519
46873
  }
46520
46874
  });
46521
46875
 
46876
+ // packages/core/src/memory/brain-plasticity-class.ts
46877
+ function upgradePlasticityClass(currentClass, event) {
46878
+ const current = currentClass ?? "static";
46879
+ if (current === "stdp") return "stdp";
46880
+ if (event === "stdp") return "stdp";
46881
+ if (event === "hebbian") {
46882
+ return current === "static" ? "hebbian" : current;
46883
+ }
46884
+ return current;
46885
+ }
46886
+ function computeStabilityScore(reinforcementCount, lastReinforcedAt, now2 = Date.now()) {
46887
+ if (!reinforcementCount || reinforcementCount <= 0) return null;
46888
+ if (!lastReinforcedAt) return null;
46889
+ const rcTerm = Math.tanh(reinforcementCount / 10);
46890
+ const lastReinforcedMs = new Date(lastReinforcedAt).getTime();
46891
+ const ageMs = now2 - lastReinforcedMs;
46892
+ const ageDays = ageMs / (24 * 60 * 60 * 1e3);
46893
+ const decayTerm = Math.exp(-ageDays / 30);
46894
+ const stability = rcTerm * decayTerm;
46895
+ return Math.max(0, Math.min(1, stability));
46896
+ }
46897
+ var init_brain_plasticity_class = __esm({
46898
+ "packages/core/src/memory/brain-plasticity-class.ts"() {
46899
+ "use strict";
46900
+ }
46901
+ });
46902
+
46522
46903
  // packages/core/src/memory/brain-stdp.ts
46523
46904
  var brain_stdp_exports = {};
46524
46905
  __export(brain_stdp_exports, {
46906
+ applyHomeostaticDecay: () => applyHomeostaticDecay,
46525
46907
  applyStdpPlasticity: () => applyStdpPlasticity,
46526
- getPlasticityStats: () => getPlasticityStats
46527
- });
46528
- async function applyStdpPlasticity(projectRoot, sessionWindowMs = 5 * 60 * 1e3) {
46908
+ backfillRewardSignals: () => backfillRewardSignals,
46909
+ computeTau: () => computeTau,
46910
+ getPlasticityStats: () => getPlasticityStats,
46911
+ shouldRunPlasticity: () => shouldRunPlasticity
46912
+ });
46913
+ function computeTau(deltaT) {
46914
+ if (deltaT <= TAU_NEAR_THRESHOLD_MS) return TAU_NEAR_MS;
46915
+ if (deltaT <= TAU_SESSION_THRESHOLD_MS) return TAU_SESSION_MS;
46916
+ return TAU_EPISODIC_MS;
46917
+ }
46918
+ function isPlasticityEventDuplicate(nativeDb, sourceNode, targetNode, kind, sessionId, withinHours = 1) {
46919
+ try {
46920
+ const cutoffIso = new Date(Date.now() - withinHours * 60 * 60 * 1e3).toISOString().replace("T", " ").slice(0, 19);
46921
+ const db = nativeDb;
46922
+ const stmt = db.prepare(
46923
+ `SELECT 1 FROM brain_plasticity_events
46924
+ WHERE source_node = ? AND target_node = ? AND kind = ?
46925
+ AND session_id = ?
46926
+ AND timestamp > ?
46927
+ LIMIT 1`
46928
+ );
46929
+ const result = stmt.get(sourceNode, targetNode, kind, sessionId, cutoffIso);
46930
+ return result !== void 0;
46931
+ } catch {
46932
+ return false;
46933
+ }
46934
+ }
46935
+ function hasMinimumRetrievalsSinceLastPlasticity(nativeDb, minCount = 2, sessionId = null) {
46936
+ try {
46937
+ const db = nativeDb;
46938
+ const lastPlasticityStmt = db.prepare(
46939
+ `SELECT MAX(timestamp) as last_time FROM brain_plasticity_events
46940
+ WHERE session_id = ?`
46941
+ );
46942
+ const lastPlasticityRow = lastPlasticityStmt.get(sessionId);
46943
+ const lastTime = lastPlasticityRow?.last_time ?? null;
46944
+ let newRetrievalCount;
46945
+ if (lastTime === null) {
46946
+ const countRow = db.prepare(
46947
+ `SELECT COUNT(*) as cnt FROM brain_retrieval_log
46948
+ WHERE session_id = ?`
46949
+ ).get(sessionId);
46950
+ newRetrievalCount = countRow?.cnt ?? 0;
46951
+ } else {
46952
+ const countRow = db.prepare(
46953
+ `SELECT COUNT(*) as cnt FROM brain_retrieval_log
46954
+ WHERE session_id = ? AND created_at > ?`
46955
+ ).get(sessionId, lastTime);
46956
+ newRetrievalCount = countRow?.cnt ?? 0;
46957
+ }
46958
+ return newRetrievalCount >= minCount;
46959
+ } catch {
46960
+ return true;
46961
+ }
46962
+ }
46963
+ async function shouldRunPlasticity(projectRoot, sessionId = null, minRetrievalsForPlasticity = 2) {
46964
+ const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
46965
+ await getBrainDb2(projectRoot);
46966
+ const nativeDb = getBrainNativeDb2();
46967
+ if (!nativeDb) return true;
46968
+ const hasMinimum = hasMinimumRetrievalsSinceLastPlasticity(
46969
+ nativeDb,
46970
+ minRetrievalsForPlasticity,
46971
+ sessionId
46972
+ );
46973
+ if (!hasMinimum) {
46974
+ const count5 = (() => {
46975
+ try {
46976
+ const db = nativeDb;
46977
+ const lastPlasticityStmt = db.prepare(
46978
+ `SELECT MAX(timestamp) as last_time FROM brain_plasticity_events WHERE session_id = ?`
46979
+ );
46980
+ const lastPlasticityRow = lastPlasticityStmt.get(sessionId);
46981
+ const lastTime = lastPlasticityRow?.last_time ?? null;
46982
+ if (lastTime === null) {
46983
+ const countStmt = db.prepare(
46984
+ `SELECT COUNT(*) as cnt FROM brain_retrieval_log WHERE session_id = ?`
46985
+ );
46986
+ const countRow = countStmt.get(sessionId);
46987
+ return countRow?.cnt ?? 0;
46988
+ } else {
46989
+ const countStmt = db.prepare(
46990
+ `SELECT COUNT(*) as cnt FROM brain_retrieval_log WHERE session_id = ? AND created_at > ?`
46991
+ );
46992
+ const countRow = countStmt.get(sessionId, lastTime);
46993
+ return countRow?.cnt ?? 0;
46994
+ }
46995
+ } catch {
46996
+ return 0;
46997
+ }
46998
+ })();
46999
+ console.warn(
47000
+ `[plasticity] Minimum-pair gate: skipped STDP Step 9b (${count5} retrievals, need >=${minRetrievalsForPlasticity})`
47001
+ );
47002
+ }
47003
+ return hasMinimum;
47004
+ }
47005
+ async function applyStdpPlasticity(projectRoot, options) {
47006
+ let lookbackDays = DEFAULT_LOOKBACK_DAYS;
47007
+ let pairingWindowMs = DEFAULT_PAIRING_WINDOW_MS;
47008
+ if (typeof options === "number") {
47009
+ console.warn(
47010
+ "[brain-stdp] Deprecated: passing sessionWindowMs as a number. Use StdpPlasticityOptions { lookbackDays, pairingWindowMs } instead. (T679)"
47011
+ );
47012
+ pairingWindowMs = options;
47013
+ } else if (options !== void 0) {
47014
+ lookbackDays = options.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;
47015
+ pairingWindowMs = options.pairingWindowMs ?? DEFAULT_PAIRING_WINDOW_MS;
47016
+ }
46529
47017
  const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
46530
47018
  await getBrainDb2(projectRoot);
46531
47019
  const nativeDb = getBrainNativeDb2();
@@ -46533,7 +47021,8 @@ async function applyStdpPlasticity(projectRoot, sessionWindowMs = 5 * 60 * 1e3)
46533
47021
  ltpEvents: 0,
46534
47022
  ltdEvents: 0,
46535
47023
  edgesCreated: 0,
46536
- pairsExamined: 0
47024
+ pairsExamined: 0,
47025
+ rewardModulatedEvents: 0
46537
47026
  };
46538
47027
  if (!nativeDb) return result;
46539
47028
  try {
@@ -46547,14 +47036,14 @@ async function applyStdpPlasticity(projectRoot, sessionWindowMs = 5 * 60 * 1e3)
46547
47036
  return result;
46548
47037
  }
46549
47038
  const now2 = Date.now();
46550
- const cutoffMs = now2 - sessionWindowMs;
47039
+ const cutoffMs = now2 - lookbackDays * 24 * 60 * 60 * 1e3;
46551
47040
  const cutoffIso = new Date(cutoffMs).toISOString().replace("T", " ").slice(0, 19);
46552
47041
  const nowIso = new Date(now2).toISOString().replace("T", " ").slice(0, 19);
46553
47042
  let logRows = [];
46554
47043
  try {
46555
47044
  logRows = typedAll(
46556
47045
  nativeDb.prepare(
46557
- `SELECT id, entry_ids, created_at, retrieval_order, delta_ms
47046
+ `SELECT id, entry_ids, created_at, retrieval_order, delta_ms, session_id, reward_signal
46558
47047
  FROM brain_retrieval_log
46559
47048
  WHERE created_at >= ?
46560
47049
  ORDER BY created_at ASC, id ASC
@@ -46575,68 +47064,318 @@ async function applyStdpPlasticity(projectRoot, sessionWindowMs = 5 * 60 * 1e3)
46575
47064
  } catch {
46576
47065
  continue;
46577
47066
  }
47067
+ if (!Array.isArray(ids)) continue;
46578
47068
  const rowTime = (/* @__PURE__ */ new Date(row.created_at.replace(" ", "T") + "Z")).getTime();
46579
47069
  for (const rawId of ids) {
47070
+ if (typeof rawId !== "string" || rawId.length === 0) continue;
46580
47071
  const entryId = rawId.includes(":") ? rawId : `observation:${rawId}`;
46581
47072
  spikes.push({
46582
47073
  entryId,
46583
47074
  rowId: row.id,
46584
47075
  retrievedAt: rowTime,
46585
- order: row.retrieval_order ?? globalOrder
47076
+ order: row.retrieval_order ?? globalOrder,
47077
+ sessionId: row.session_id ?? null,
47078
+ rewardSignal: row.reward_signal ?? null
46586
47079
  });
46587
47080
  globalOrder++;
46588
47081
  }
46589
47082
  }
47083
+ if (spikes.length < 2) return result;
46590
47084
  spikes.sort((a, b2) => a.retrievedAt - b2.retrievedAt || a.order - b2.order);
47085
+ const MAX_PAIRS_PER_SESSION = 50;
47086
+ const sessionBucketMap = /* @__PURE__ */ new Map();
47087
+ for (const spike of spikes) {
47088
+ const key = spike.sessionId ?? "null";
47089
+ const bucket = sessionBucketMap.get(key);
47090
+ if (bucket !== void 0) {
47091
+ bucket.push(spike);
47092
+ } else {
47093
+ sessionBucketMap.set(key, [spike]);
47094
+ }
47095
+ }
47096
+ const orderedBuckets = Array.from(sessionBucketMap.entries()).sort(
47097
+ ([, a], [, b2]) => (a[0]?.retrievedAt ?? 0) - (b2[0]?.retrievedAt ?? 0)
47098
+ );
47099
+ const workingSpikes = [];
47100
+ for (let bi2 = 0; bi2 < orderedBuckets.length; bi2++) {
47101
+ const [, bucketSpikes] = orderedBuckets[bi2];
47102
+ workingSpikes.push(...bucketSpikes);
47103
+ }
47104
+ const withinSessionIndex = /* @__PURE__ */ new Map();
47105
+ const sessionSizeMap = /* @__PURE__ */ new Map();
47106
+ for (const [, bucketSpikes] of orderedBuckets) {
47107
+ for (let idx = 0; idx < bucketSpikes.length; idx++) {
47108
+ const spike = bucketSpikes[idx];
47109
+ withinSessionIndex.set(spike, idx);
47110
+ sessionSizeMap.set(spike.sessionId ?? "null", bucketSpikes.length);
47111
+ }
47112
+ }
46591
47113
  const prepareGetEdge = nativeDb.prepare(
46592
- `SELECT weight FROM brain_page_edges
47114
+ `SELECT weight, reinforcement_count, last_reinforced_at, plasticity_class, depression_count, last_depressed_at
47115
+ FROM brain_page_edges
46593
47116
  WHERE from_id = ? AND to_id = ? AND edge_type = 'co_retrieved'`
46594
47117
  );
46595
- const prepareUpdateEdge = nativeDb.prepare(
47118
+ const prepareUpdateEdgeLtp = nativeDb.prepare(
46596
47119
  `UPDATE brain_page_edges
46597
- SET weight = MAX(?, MIN(?, weight + ?))
47120
+ SET weight = MAX(?, MIN(?, weight + ?)),
47121
+ reinforcement_count = reinforcement_count + 1,
47122
+ last_reinforced_at = ?,
47123
+ plasticity_class = ?,
47124
+ stability_score = ?
47125
+ WHERE from_id = ? AND to_id = ? AND edge_type = 'co_retrieved'`
47126
+ );
47127
+ const prepareUpdateEdgeLtd = nativeDb.prepare(
47128
+ `UPDATE brain_page_edges
47129
+ SET weight = MAX(?, MIN(?, weight + ?)),
47130
+ depression_count = depression_count + 1,
47131
+ last_depressed_at = ?,
47132
+ plasticity_class = ?,
47133
+ stability_score = ?
46598
47134
  WHERE from_id = ? AND to_id = ? AND edge_type = 'co_retrieved'`
46599
47135
  );
46600
47136
  const prepareInsertEdge = nativeDb.prepare(
46601
47137
  `INSERT OR IGNORE INTO brain_page_edges
46602
- (from_id, to_id, edge_type, weight, provenance, created_at)
46603
- VALUES (?, ?, 'co_retrieved', ?, 'plasticity:stdp-ltp', ?)`
47138
+ (from_id, to_id, edge_type, weight, provenance, reinforcement_count, last_reinforced_at, plasticity_class, stability_score, created_at)
47139
+ VALUES (?, ?, 'co_retrieved', ?, 'plasticity:stdp-ltp', 1, ?, 'stdp', ?, ?)`
46604
47140
  );
46605
47141
  const prepareLogEvent = nativeDb.prepare(
46606
47142
  `INSERT INTO brain_plasticity_events
46607
- (source_node, target_node, delta_w, kind, timestamp)
46608
- VALUES (?, ?, ?, ?, ?)`
47143
+ (source_node, target_node, delta_w, kind, timestamp,
47144
+ session_id, retrieval_log_id, weight_before, weight_after, delta_t_ms)
47145
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
46609
47146
  );
46610
- for (let i = 0; i < spikes.length; i++) {
46611
- const spikeA = spikes[i];
46612
- for (let j2 = i + 1; j2 < spikes.length; j2++) {
46613
- const spikeB = spikes[j2];
47147
+ let prepareLogWeightHistory = null;
47148
+ try {
47149
+ nativeDb.prepare("SELECT 1 FROM brain_weight_history LIMIT 1").get();
47150
+ prepareLogWeightHistory = nativeDb.prepare(
47151
+ `INSERT INTO brain_weight_history
47152
+ (edge_from_id, edge_to_id, edge_type, weight_before, weight_after,
47153
+ delta_weight, event_kind, source_plasticity_event_id, retrieval_log_id,
47154
+ reward_signal, changed_at)
47155
+ VALUES (?, ?, 'co_retrieved', ?, ?, ?, ?, ?, ?, ?, ?)`
47156
+ );
47157
+ } catch {
47158
+ }
47159
+ for (let i = 0; i < workingSpikes.length; i++) {
47160
+ const spikeA = workingSpikes[i];
47161
+ const sessionKeyA = spikeA.sessionId ?? "null";
47162
+ const sessionSizeA = sessionSizeMap.get(sessionKeyA) ?? 1;
47163
+ const posInSessionA = withinSessionIndex.get(spikeA) ?? 0;
47164
+ const canCrossSession = posInSessionA >= sessionSizeA - MAX_PAIRS_PER_SESSION;
47165
+ for (let j2 = i + 1; j2 < workingSpikes.length; j2++) {
47166
+ const spikeB = workingSpikes[j2];
46614
47167
  const deltaT = spikeB.retrievedAt - spikeA.retrievedAt;
46615
- if (deltaT > sessionWindowMs) break;
47168
+ if (deltaT > pairingWindowMs) break;
46616
47169
  if (spikeA.entryId === spikeB.entryId) continue;
47170
+ const sessionKeyB = spikeB.sessionId ?? "null";
47171
+ if (sessionKeyA !== sessionKeyB && !canCrossSession) {
47172
+ continue;
47173
+ }
46617
47174
  result.pairsExamined++;
46618
- const deltaW = A_PRE * Math.exp(-deltaT / TAU_PRE_MS);
47175
+ const tau = computeTau(deltaT);
47176
+ let deltaW = A_PRE * Math.exp(-deltaT / tau);
46619
47177
  if (deltaW < 1e-6) continue;
47178
+ const eventSessionId = spikeA.sessionId ?? null;
47179
+ const eventRewardSignal = spikeA.rewardSignal ?? null;
47180
+ let wasRewardModulated = false;
47181
+ if (eventRewardSignal !== null) {
47182
+ const r = eventRewardSignal;
47183
+ deltaW = Math.min(deltaW * (1 + r), 2 * A_PRE);
47184
+ deltaW = Math.max(deltaW, 0);
47185
+ wasRewardModulated = true;
47186
+ }
47187
+ if (deltaW < 1e-6) {
47188
+ if (wasRewardModulated) result.rewardModulatedEvents++;
47189
+ continue;
47190
+ }
46620
47191
  const existingEdge = prepareGetEdge.get(spikeA.entryId, spikeB.entryId);
47192
+ let ltpEventId = null;
46621
47193
  try {
46622
47194
  if (existingEdge !== void 0) {
46623
- prepareUpdateEdge.run(WEIGHT_MIN, WEIGHT_MAX, deltaW, spikeA.entryId, spikeB.entryId);
47195
+ const currentWeight = existingEdge.weight;
47196
+ const newWeight = Math.max(WEIGHT_MIN, Math.min(WEIGHT_MAX, currentWeight + deltaW));
47197
+ const upgradedClass = upgradePlasticityClass(existingEdge.plasticity_class, "stdp");
47198
+ const newRcCount = (existingEdge.reinforcement_count ?? 0) + 1;
47199
+ const stability = computeStabilityScore(newRcCount, nowIso, now2);
47200
+ prepareUpdateEdgeLtp.run(
47201
+ WEIGHT_MIN,
47202
+ WEIGHT_MAX,
47203
+ deltaW,
47204
+ nowIso,
47205
+ // last_reinforced_at
47206
+ upgradedClass,
47207
+ stability,
47208
+ spikeA.entryId,
47209
+ spikeB.entryId
47210
+ );
47211
+ const isDuplicate = isPlasticityEventDuplicate(
47212
+ nativeDb,
47213
+ spikeA.entryId,
47214
+ spikeB.entryId,
47215
+ "ltp",
47216
+ eventSessionId,
47217
+ 1
47218
+ // within 1 hour
47219
+ );
47220
+ if (isDuplicate) {
47221
+ result.ltpEvents++;
47222
+ if (wasRewardModulated) result.rewardModulatedEvents++;
47223
+ continue;
47224
+ }
47225
+ const evtStmt = prepareLogEvent.run(
47226
+ spikeA.entryId,
47227
+ spikeB.entryId,
47228
+ deltaW,
47229
+ "ltp",
47230
+ nowIso,
47231
+ eventSessionId,
47232
+ spikeA.rowId,
47233
+ currentWeight,
47234
+ newWeight,
47235
+ deltaT
47236
+ );
47237
+ ltpEventId = evtStmt.lastInsertRowid != null ? Number(evtStmt.lastInsertRowid) : null;
47238
+ if (prepareLogWeightHistory) {
47239
+ prepareLogWeightHistory.run(
47240
+ spikeA.entryId,
47241
+ spikeB.entryId,
47242
+ currentWeight,
47243
+ newWeight,
47244
+ deltaW,
47245
+ "ltp",
47246
+ ltpEventId,
47247
+ spikeA.rowId,
47248
+ eventRewardSignal,
47249
+ nowIso
47250
+ );
47251
+ }
46624
47252
  } else {
46625
- const initialWeight = Math.min(WEIGHT_MAX, deltaW);
46626
- prepareInsertEdge.run(spikeA.entryId, spikeB.entryId, initialWeight, nowIso);
47253
+ const noveltyBoostedWeight = deltaW * K_NOVELTY;
47254
+ const initialWeight = Math.min(
47255
+ WEIGHT_MAX,
47256
+ Math.min(A_PRE * K_NOVELTY, noveltyBoostedWeight)
47257
+ );
47258
+ const stability = computeStabilityScore(1, nowIso, now2);
47259
+ prepareInsertEdge.run(
47260
+ spikeA.entryId,
47261
+ spikeB.entryId,
47262
+ initialWeight,
47263
+ nowIso,
47264
+ // last_reinforced_at
47265
+ stability,
47266
+ nowIso
47267
+ );
46627
47268
  result.edgesCreated++;
47269
+ const evtStmt = prepareLogEvent.run(
47270
+ spikeA.entryId,
47271
+ spikeB.entryId,
47272
+ initialWeight,
47273
+ "ltp",
47274
+ nowIso,
47275
+ eventSessionId,
47276
+ spikeA.rowId,
47277
+ null,
47278
+ initialWeight,
47279
+ deltaT
47280
+ );
47281
+ ltpEventId = evtStmt.lastInsertRowid != null ? Number(evtStmt.lastInsertRowid) : null;
47282
+ if (prepareLogWeightHistory) {
47283
+ prepareLogWeightHistory.run(
47284
+ spikeA.entryId,
47285
+ spikeB.entryId,
47286
+ null,
47287
+ initialWeight,
47288
+ initialWeight,
47289
+ "ltp",
47290
+ ltpEventId,
47291
+ spikeA.rowId,
47292
+ eventRewardSignal,
47293
+ nowIso
47294
+ );
47295
+ }
46628
47296
  }
46629
- prepareLogEvent.run(spikeA.entryId, spikeB.entryId, deltaW, "ltp", nowIso);
46630
47297
  result.ltpEvents++;
47298
+ if (wasRewardModulated) result.rewardModulatedEvents++;
46631
47299
  } catch {
46632
47300
  }
46633
- const deltaWNeg = -(A_POST * Math.exp(-deltaT / TAU_POST_MS));
47301
+ let deltaWNeg = -(A_POST * Math.exp(-deltaT / tau));
47302
+ let ltdWasRewardModulated = false;
47303
+ if (eventRewardSignal !== null) {
47304
+ const r = eventRewardSignal;
47305
+ deltaWNeg = Math.max(deltaWNeg * (1 - r), -2 * A_POST);
47306
+ ltdWasRewardModulated = true;
47307
+ }
46634
47308
  const existingReverseEdge = prepareGetEdge.get(spikeB.entryId, spikeA.entryId);
46635
47309
  if (existingReverseEdge !== void 0 && Math.abs(deltaWNeg) >= 1e-6) {
46636
47310
  try {
46637
- prepareUpdateEdge.run(WEIGHT_MIN, WEIGHT_MAX, deltaWNeg, spikeB.entryId, spikeA.entryId);
46638
- prepareLogEvent.run(spikeB.entryId, spikeA.entryId, deltaWNeg, "ltd", nowIso);
47311
+ const currentReverseWeight = existingReverseEdge.weight;
47312
+ const newReverseWeight = Math.max(
47313
+ WEIGHT_MIN,
47314
+ Math.min(WEIGHT_MAX, currentReverseWeight + deltaWNeg)
47315
+ );
47316
+ const upgradedClass = upgradePlasticityClass(
47317
+ existingReverseEdge.plasticity_class,
47318
+ "stdp"
47319
+ );
47320
+ const stability = computeStabilityScore(
47321
+ existingReverseEdge.reinforcement_count,
47322
+ existingReverseEdge.last_reinforced_at,
47323
+ now2
47324
+ );
47325
+ prepareUpdateEdgeLtd.run(
47326
+ WEIGHT_MIN,
47327
+ WEIGHT_MAX,
47328
+ deltaWNeg,
47329
+ nowIso,
47330
+ // last_depressed_at
47331
+ upgradedClass,
47332
+ stability,
47333
+ spikeB.entryId,
47334
+ spikeA.entryId
47335
+ );
47336
+ const isLtdDuplicate = isPlasticityEventDuplicate(
47337
+ nativeDb,
47338
+ spikeB.entryId,
47339
+ spikeA.entryId,
47340
+ "ltd",
47341
+ eventSessionId,
47342
+ 1
47343
+ // within 1 hour
47344
+ );
47345
+ if (isLtdDuplicate) {
47346
+ result.ltdEvents++;
47347
+ if (ltdWasRewardModulated) result.rewardModulatedEvents++;
47348
+ continue;
47349
+ }
47350
+ const ltdEvtStmt = prepareLogEvent.run(
47351
+ spikeB.entryId,
47352
+ spikeA.entryId,
47353
+ deltaWNeg,
47354
+ "ltd",
47355
+ nowIso,
47356
+ eventSessionId,
47357
+ spikeB.rowId,
47358
+ currentReverseWeight,
47359
+ newReverseWeight,
47360
+ deltaT
47361
+ );
47362
+ const ltdEventId = ltdEvtStmt.lastInsertRowid != null ? Number(ltdEvtStmt.lastInsertRowid) : null;
47363
+ if (prepareLogWeightHistory) {
47364
+ prepareLogWeightHistory.run(
47365
+ spikeB.entryId,
47366
+ spikeA.entryId,
47367
+ currentReverseWeight,
47368
+ newReverseWeight,
47369
+ deltaWNeg,
47370
+ "ltd",
47371
+ ltdEventId,
47372
+ spikeB.rowId,
47373
+ eventRewardSignal,
47374
+ nowIso
47375
+ );
47376
+ }
46639
47377
  result.ltdEvents++;
47378
+ if (ltdWasRewardModulated) result.rewardModulatedEvents++;
46640
47379
  } catch {
46641
47380
  }
46642
47381
  }
@@ -46706,15 +47445,240 @@ async function getPlasticityStats(projectRoot, limit = 20) {
46706
47445
  }))
46707
47446
  };
46708
47447
  }
46709
- var TAU_PRE_MS, TAU_POST_MS, A_PRE, A_POST, WEIGHT_MIN, WEIGHT_MAX;
47448
+ async function backfillRewardSignals(projectRoot, sessionId, lookbackDays = 30) {
47449
+ const result = { rowsLabeled: 0, rowsSkipped: 0 };
47450
+ if (!sessionId) {
47451
+ return result;
47452
+ }
47453
+ if (sessionId.startsWith("ses_backfill_")) {
47454
+ return result;
47455
+ }
47456
+ let taskRows = [];
47457
+ try {
47458
+ const { getDb: getDb4 } = await Promise.resolve().then(() => (init_sqlite2(), sqlite_exports));
47459
+ const tasksDb = await getDb4(projectRoot);
47460
+ const { tasks: tasks2 } = await Promise.resolve().then(() => (init_tasks_schema(), tasks_schema_exports));
47461
+ const { and: and15, eq: eq18, inArray: inArray8, gte: gte4, or: or7, isNotNull: isNotNull3 } = await import("drizzle-orm");
47462
+ const cutoffTs = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1e3).toISOString().replace("T", " ").slice(0, 19);
47463
+ const rawRows = await tasksDb.select({
47464
+ id: tasks2.id,
47465
+ status: tasks2.status,
47466
+ verificationJson: tasks2.verificationJson,
47467
+ completedAt: tasks2.completedAt,
47468
+ cancelledAt: tasks2.cancelledAt
47469
+ }).from(tasks2).where(
47470
+ and15(
47471
+ eq18(tasks2.sessionId, sessionId),
47472
+ inArray8(tasks2.status, ["done", "cancelled"]),
47473
+ or7(
47474
+ and15(isNotNull3(tasks2.completedAt), gte4(tasks2.completedAt, cutoffTs)),
47475
+ and15(isNotNull3(tasks2.cancelledAt), gte4(tasks2.cancelledAt, cutoffTs))
47476
+ )
47477
+ )
47478
+ ).all();
47479
+ taskRows = rawRows.map((r) => ({
47480
+ id: r.id,
47481
+ status: r.status,
47482
+ verificationJson: r.verificationJson ?? null,
47483
+ completedAt: r.completedAt ?? null,
47484
+ cancelledAt: r.cancelledAt ?? null
47485
+ }));
47486
+ } catch {
47487
+ return result;
47488
+ }
47489
+ if (taskRows.length === 0) {
47490
+ return result;
47491
+ }
47492
+ let sessionReward = null;
47493
+ function deriveTaskReward(task) {
47494
+ if (task.status === "cancelled") {
47495
+ return -0.5;
47496
+ }
47497
+ let verificationPassed = false;
47498
+ if (task.verificationJson) {
47499
+ try {
47500
+ const v2 = JSON.parse(task.verificationJson);
47501
+ verificationPassed = v2.passed === true;
47502
+ } catch {
47503
+ }
47504
+ }
47505
+ return verificationPassed ? 1 : 0.5;
47506
+ }
47507
+ for (const task of taskRows) {
47508
+ const taskReward = deriveTaskReward(task);
47509
+ if (sessionReward === null || taskReward > sessionReward) {
47510
+ sessionReward = taskReward;
47511
+ }
47512
+ }
47513
+ if (sessionReward === null) {
47514
+ return result;
47515
+ }
47516
+ try {
47517
+ const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
47518
+ await getBrainDb2(projectRoot);
47519
+ const nativeDb = getBrainNativeDb2();
47520
+ if (!nativeDb) return result;
47521
+ try {
47522
+ nativeDb.prepare("SELECT 1 FROM brain_retrieval_log LIMIT 1").get();
47523
+ } catch {
47524
+ return result;
47525
+ }
47526
+ const updateResult = nativeDb.prepare(
47527
+ `UPDATE brain_retrieval_log
47528
+ SET reward_signal = ?
47529
+ WHERE session_id = ?
47530
+ AND reward_signal IS NULL`
47531
+ ).run(sessionReward, sessionId);
47532
+ const updatedCount = typeof updateResult.changes === "number" ? updateResult.changes : 0;
47533
+ result.rowsLabeled = updatedCount;
47534
+ const skipRow = nativeDb.prepare(
47535
+ `SELECT COUNT(*) AS cnt FROM brain_retrieval_log
47536
+ WHERE session_id = ? AND reward_signal IS NOT NULL`
47537
+ ).get(sessionId);
47538
+ result.rowsSkipped = skipRow?.cnt ?? 0;
47539
+ let modulatorsExist = false;
47540
+ try {
47541
+ nativeDb.prepare("SELECT 1 FROM brain_modulators LIMIT 1").get();
47542
+ modulatorsExist = true;
47543
+ } catch {
47544
+ }
47545
+ if (modulatorsExist && updatedCount > 0) {
47546
+ const insertModulator = nativeDb.prepare(
47547
+ `INSERT INTO brain_modulators
47548
+ (modulator_type, valence, magnitude, source_event_id, session_id, description)
47549
+ VALUES (?, ?, 1.0, ?, ?, ?)`
47550
+ );
47551
+ for (const task of taskRows) {
47552
+ const taskReward = deriveTaskReward(task);
47553
+ let modulatorType;
47554
+ let description;
47555
+ if (task.status === "cancelled") {
47556
+ modulatorType = "task_cancelled";
47557
+ description = `Task ${task.id} cancelled`;
47558
+ } else if (taskReward >= 1) {
47559
+ modulatorType = "task_verified";
47560
+ description = `Task ${task.id} completed and verified`;
47561
+ } else {
47562
+ modulatorType = "task_completed";
47563
+ description = `Task ${task.id} completed (unverified)`;
47564
+ }
47565
+ try {
47566
+ insertModulator.run(modulatorType, taskReward, task.id, sessionId, description);
47567
+ } catch {
47568
+ }
47569
+ }
47570
+ }
47571
+ } catch {
47572
+ }
47573
+ return result;
47574
+ }
47575
+ async function applyHomeostaticDecay(projectRoot, options) {
47576
+ const decayRatePerDay = options?.decayRatePerDay ?? 0.02;
47577
+ const gracePeriodDays = options?.gracePeriodDays ?? 7;
47578
+ const pruneThreshold = options?.pruneThreshold ?? 0.05;
47579
+ const result = { edgesDecayed: 0, edgesPruned: 0 };
47580
+ const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
47581
+ await getBrainDb2(projectRoot);
47582
+ const nativeDb = getBrainNativeDb2();
47583
+ if (!nativeDb) return result;
47584
+ try {
47585
+ nativeDb.prepare("SELECT 1 FROM brain_page_edges LIMIT 1").get();
47586
+ } catch {
47587
+ return result;
47588
+ }
47589
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
47590
+ let weightHistoryExists = false;
47591
+ try {
47592
+ nativeDb.prepare("SELECT 1 FROM brain_weight_history LIMIT 1").get();
47593
+ weightHistoryExists = true;
47594
+ } catch {
47595
+ }
47596
+ let candidates = [];
47597
+ try {
47598
+ candidates = typedAll(
47599
+ nativeDb.prepare(
47600
+ `SELECT from_id, to_id, edge_type, weight, plasticity_class, last_reinforced_at
47601
+ FROM brain_page_edges
47602
+ WHERE plasticity_class IN ('hebbian', 'stdp')
47603
+ AND last_reinforced_at IS NOT NULL
47604
+ AND (julianday('now') - julianday(last_reinforced_at)) > ?`
47605
+ ),
47606
+ gracePeriodDays
47607
+ );
47608
+ } catch {
47609
+ return result;
47610
+ }
47611
+ if (candidates.length === 0) return result;
47612
+ const prepareUpdateWeight = nativeDb.prepare(
47613
+ `UPDATE brain_page_edges
47614
+ SET weight = ?
47615
+ WHERE from_id = ? AND to_id = ? AND edge_type = ?`
47616
+ );
47617
+ const prepareDeleteEdge = nativeDb.prepare(
47618
+ `DELETE FROM brain_page_edges
47619
+ WHERE from_id = ? AND to_id = ? AND edge_type = ?`
47620
+ );
47621
+ let prepareInsertHistory = null;
47622
+ if (weightHistoryExists) {
47623
+ try {
47624
+ prepareInsertHistory = nativeDb.prepare(
47625
+ `INSERT INTO brain_weight_history
47626
+ (edge_from_id, edge_to_id, edge_type, weight_before, weight_after,
47627
+ delta_weight, event_kind, changed_at)
47628
+ VALUES (?, ?, ?, ?, 0.0, ?, 'prune', ?)`
47629
+ );
47630
+ } catch {
47631
+ }
47632
+ }
47633
+ const nowMs = Date.now();
47634
+ for (const edge of candidates) {
47635
+ try {
47636
+ const lastReinforced = (/* @__PURE__ */ new Date(edge.last_reinforced_at.replace(" ", "T") + "Z")).getTime();
47637
+ const daysIdle = (nowMs - lastReinforced) / (24 * 60 * 60 * 1e3);
47638
+ const decayDays = Math.max(0, daysIdle - gracePeriodDays);
47639
+ const newWeight = edge.weight * (1 - decayRatePerDay) ** decayDays;
47640
+ if (newWeight < pruneThreshold) {
47641
+ prepareDeleteEdge.run(edge.from_id, edge.to_id, edge.edge_type);
47642
+ result.edgesPruned++;
47643
+ if (prepareInsertHistory) {
47644
+ const deltaW = -edge.weight;
47645
+ try {
47646
+ prepareInsertHistory.run(
47647
+ edge.from_id,
47648
+ edge.to_id,
47649
+ edge.edge_type,
47650
+ edge.weight,
47651
+ deltaW,
47652
+ nowIso
47653
+ );
47654
+ } catch {
47655
+ }
47656
+ }
47657
+ } else {
47658
+ prepareUpdateWeight.run(newWeight, edge.from_id, edge.to_id, edge.edge_type);
47659
+ result.edgesDecayed++;
47660
+ }
47661
+ } catch {
47662
+ }
47663
+ }
47664
+ return result;
47665
+ }
47666
+ var DEFAULT_LOOKBACK_DAYS, DEFAULT_PAIRING_WINDOW_MS, TAU_NEAR_MS, TAU_SESSION_MS, TAU_EPISODIC_MS, TAU_NEAR_THRESHOLD_MS, TAU_SESSION_THRESHOLD_MS, A_PRE, A_POST, K_NOVELTY, WEIGHT_MIN, WEIGHT_MAX;
46710
47667
  var init_brain_stdp = __esm({
46711
47668
  "packages/core/src/memory/brain-stdp.ts"() {
46712
47669
  "use strict";
46713
47670
  init_typed_query();
46714
- TAU_PRE_MS = 2e4;
46715
- TAU_POST_MS = 2e4;
47671
+ init_brain_plasticity_class();
47672
+ DEFAULT_LOOKBACK_DAYS = 30;
47673
+ DEFAULT_PAIRING_WINDOW_MS = 24 * 60 * 60 * 1e3;
47674
+ TAU_NEAR_MS = 2e4;
47675
+ TAU_SESSION_MS = 30 * 60 * 1e3;
47676
+ TAU_EPISODIC_MS = 12 * 60 * 60 * 1e3;
47677
+ TAU_NEAR_THRESHOLD_MS = 3e4;
47678
+ TAU_SESSION_THRESHOLD_MS = 2 * 60 * 60 * 1e3;
46716
47679
  A_PRE = 0.05;
46717
47680
  A_POST = 0.06;
47681
+ K_NOVELTY = 1.5;
46718
47682
  WEIGHT_MIN = 0;
46719
47683
  WEIGHT_MAX = 1;
46720
47684
  }
@@ -46963,7 +47927,8 @@ async function runTierPromotion(projectRoot) {
46963
47927
  }
46964
47928
  return { promoted, evicted };
46965
47929
  }
46966
- async function runConsolidation(projectRoot) {
47930
+ async function runConsolidation(projectRoot, sessionId, trigger = "session_end") {
47931
+ const consolidationStartMs = Date.now();
46967
47932
  const result = {
46968
47933
  deduplicated: 0,
46969
47934
  qualityRecomputed: 0,
@@ -47026,11 +47991,59 @@ async function runConsolidation(projectRoot) {
47026
47991
  console.warn("[consolidation] Step 8 graph memory bridge failed:", err);
47027
47992
  }
47028
47993
  try {
47029
- const { applyStdpPlasticity: applyStdpPlasticity2 } = await Promise.resolve().then(() => (init_brain_stdp(), brain_stdp_exports));
47030
- const stdpResult = await applyStdpPlasticity2(projectRoot);
47031
- result.stdpPlasticity = stdpResult;
47994
+ const { backfillRewardSignals: backfillRewardSignals2 } = await Promise.resolve().then(() => (init_brain_stdp(), brain_stdp_exports));
47995
+ const rewardResult = await backfillRewardSignals2(projectRoot, sessionId ?? null);
47996
+ result.rewardBackfilled = rewardResult;
47997
+ } catch (err) {
47998
+ console.warn("[consolidation] Step 9a reward backfill failed:", err);
47999
+ }
48000
+ try {
48001
+ const { applyStdpPlasticity: applyStdpPlasticity2, shouldRunPlasticity: shouldRunPlasticity2 } = await Promise.resolve().then(() => (init_brain_stdp(), brain_stdp_exports));
48002
+ const shouldRun = await shouldRunPlasticity2(projectRoot, sessionId ?? null, 2);
48003
+ if (shouldRun) {
48004
+ const stdpResult = await applyStdpPlasticity2(projectRoot);
48005
+ result.stdpPlasticity = stdpResult;
48006
+ } else {
48007
+ result.stdpPlasticity = {
48008
+ ltpEvents: 0,
48009
+ ltdEvents: 0,
48010
+ edgesCreated: 0,
48011
+ pairsExamined: 0
48012
+ };
48013
+ }
47032
48014
  } catch (err) {
47033
- console.warn("[consolidation] Step 9 STDP plasticity failed:", err);
48015
+ console.warn("[consolidation] Step 9b STDP plasticity failed:", err);
48016
+ }
48017
+ try {
48018
+ const { applyHomeostaticDecay: applyHomeostaticDecay2 } = await Promise.resolve().then(() => (init_brain_stdp(), brain_stdp_exports));
48019
+ const decayResult = await applyHomeostaticDecay2(projectRoot);
48020
+ result.homeostaticDecay = decayResult;
48021
+ } catch (err) {
48022
+ console.warn("[consolidation] Step 9c homeostatic decay failed:", err);
48023
+ }
48024
+ try {
48025
+ const { getBrainDb: getBrainDb2, getBrainNativeDb: getBrainNativeDb2 } = await Promise.resolve().then(() => (init_brain_sqlite(), brain_sqlite_exports));
48026
+ await getBrainDb2(projectRoot);
48027
+ const nativeDb = getBrainNativeDb2();
48028
+ if (nativeDb) {
48029
+ let consolidationEventsExist = false;
48030
+ try {
48031
+ nativeDb.prepare("SELECT 1 FROM brain_consolidation_events LIMIT 1").get();
48032
+ consolidationEventsExist = true;
48033
+ } catch {
48034
+ }
48035
+ if (consolidationEventsExist) {
48036
+ const durationMs = Date.now() - consolidationStartMs;
48037
+ const stepResultsJson = JSON.stringify(result);
48038
+ nativeDb.prepare(
48039
+ `INSERT INTO brain_consolidation_events
48040
+ (trigger, session_id, step_results_json, duration_ms, succeeded)
48041
+ VALUES (?, ?, ?, ?, 1)`
48042
+ ).run(trigger, sessionId ?? null, stepResultsJson, durationMs);
48043
+ }
48044
+ }
48045
+ } catch (err) {
48046
+ console.warn("[consolidation] Step 9e consolidation event log failed:", err);
47034
48047
  }
47035
48048
  return result;
47036
48049
  }
@@ -47192,7 +48205,8 @@ async function strengthenCoRetrievedEdges(projectRoot) {
47192
48205
  try {
47193
48206
  const updateStmt = nativeDb.prepare(`
47194
48207
  UPDATE brain_page_edges
47195
- SET weight = MIN(1.0, weight + 0.1)
48208
+ SET weight = MIN(1.0, weight + 0.1),
48209
+ plasticity_class = 'hebbian'
47196
48210
  WHERE from_id = ? AND to_id = ? AND edge_type = ?
47197
48211
  `);
47198
48212
  const updateResult = updateStmt.run(nodeFrom, nodeTo, EDGE_TYPES.CO_RETRIEVED);
@@ -47200,8 +48214,8 @@ async function strengthenCoRetrievedEdges(projectRoot) {
47200
48214
  if (changes === 0) {
47201
48215
  nativeDb.prepare(`
47202
48216
  INSERT OR IGNORE INTO brain_page_edges
47203
- (from_id, to_id, edge_type, weight, provenance, created_at)
47204
- VALUES (?, ?, ?, 0.3, 'consolidation:co-retrieval', ?)
48217
+ (from_id, to_id, edge_type, weight, provenance, plasticity_class, created_at)
48218
+ VALUES (?, ?, ?, 0.3, 'consolidation:co-retrieval', 'hebbian', ?)
47205
48219
  `).run(nodeFrom, nodeTo, EDGE_TYPES.CO_RETRIEVED, now2);
47206
48220
  }
47207
48221
  strengthened++;
@@ -52314,7 +53328,7 @@ async function logRetrieval(projectRoot, query, entryIds, source, tokensUsed, se
52314
53328
  "INSERT INTO brain_retrieval_log (query, entry_ids, entry_count, source, tokens_used, session_id) VALUES (?, ?, ?, ?, ?, ?)"
52315
53329
  ).run(
52316
53330
  query,
52317
- entryIds.join(","),
53331
+ JSON.stringify(entryIds),
52318
53332
  entryIds.length,
52319
53333
  source,
52320
53334
  tokensUsed ?? null,
@@ -56790,8 +57804,8 @@ async function ensureGlobalHome() {
56790
57804
  await writeFile6(globalConfigPath, resolved);
56791
57805
  }
56792
57806
  }
56793
- const homedir8 = (await import("node:os")).homedir();
56794
- const legacyCleoHome = join42(homedir8, ".cleo");
57807
+ const homedir9 = (await import("node:os")).homedir();
57808
+ const legacyCleoHome = join42(homedir9, ".cleo");
56795
57809
  const cleanupPaths = [cleoHome];
56796
57810
  if (legacyCleoHome !== cleoHome && existsSync40(legacyCleoHome)) {
56797
57811
  cleanupPaths.push(legacyCleoHome);
@@ -64894,10 +65908,10 @@ async function readProjectMeta(projectPath) {
64894
65908
  }
64895
65909
  async function readProjectId(projectPath) {
64896
65910
  try {
64897
- const { readFileSync: readFileSync107, existsSync: existsSync135 } = await import("node:fs");
65911
+ const { readFileSync: readFileSync108, existsSync: existsSync136 } = await import("node:fs");
64898
65912
  const infoPath = join64(projectPath, ".cleo", "project-info.json");
64899
- if (!existsSync135(infoPath)) return "";
64900
- const data = JSON.parse(readFileSync107(infoPath, "utf-8"));
65913
+ if (!existsSync136(infoPath)) return "";
65914
+ const data = JSON.parse(readFileSync108(infoPath, "utf-8"));
64901
65915
  return typeof data.projectId === "string" ? data.projectId : "";
64902
65916
  } catch {
64903
65917
  return "";
@@ -66601,6 +67615,10 @@ async function startTask(taskId, cwd, accessor) {
66601
67615
  }
66602
67616
  );
66603
67617
  }
67618
+ const currentStage = task.pipelineStage;
67619
+ if (currentStage && isValidPipelineStage(currentStage) && PLANNING_STAGES2.has(currentStage)) {
67620
+ await acc.updateTaskFields(taskId, { pipelineStage: "implementation" });
67621
+ }
66604
67622
  const focus = await acc.getMetaValue("focus_state") ?? {};
66605
67623
  const previousTask = focus.currentTask ?? null;
66606
67624
  focus.currentTask = taskId;
@@ -66688,16 +67706,24 @@ async function getWorkHistory(cwd, accessor) {
66688
67706
  }
66689
67707
  return history.reverse();
66690
67708
  }
66691
- var getTaskHistory;
67709
+ var PLANNING_STAGES2, getTaskHistory;
66692
67710
  var init_task_work = __esm({
66693
67711
  "packages/core/src/task-work/index.ts"() {
66694
67712
  "use strict";
67713
+ init_handlers();
66695
67714
  init_src();
66696
67715
  init_errors3();
66697
67716
  init_data_accessor();
66698
67717
  init_add();
66699
67718
  init_dependency_check();
66700
- init_handlers();
67719
+ init_pipeline_stage();
67720
+ PLANNING_STAGES2 = /* @__PURE__ */ new Set([
67721
+ "research",
67722
+ "consensus",
67723
+ "architecture_decision",
67724
+ "specification",
67725
+ "decomposition"
67726
+ ]);
66701
67727
  getTaskHistory = getWorkHistory;
66702
67728
  }
66703
67729
  });
@@ -66819,6 +67845,10 @@ async function completeTask(options, cwd, accessor) {
66819
67845
  }
66820
67846
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
66821
67847
  const before = { ...task };
67848
+ const completionStage = task.pipelineStage;
67849
+ if (completionStage && isValidPipelineStage(completionStage) && EXECUTION_STAGES_FOR_RELEASE.has(completionStage)) {
67850
+ task.pipelineStage = "release";
67851
+ }
66822
67852
  task.status = "done";
66823
67853
  task.completedAt = now2;
66824
67854
  task.updatedAt = now2;
@@ -66931,7 +67961,7 @@ async function completeTask(options, cwd, accessor) {
66931
67961
  ...unblockedTasks.length > 0 && { unblockedTasks }
66932
67962
  };
66933
67963
  }
66934
- var DEFAULT_VERIFICATION_REQUIRED_GATES, VERIFICATION_GATES;
67964
+ var EXECUTION_STAGES_FOR_RELEASE, DEFAULT_VERIFICATION_REQUIRED_GATES, VERIFICATION_GATES;
66935
67965
  var init_complete = __esm({
66936
67966
  "packages/core/src/tasks/complete.ts"() {
66937
67967
  "use strict";
@@ -66941,6 +67971,8 @@ var init_complete = __esm({
66941
67971
  init_session_enforcement();
66942
67972
  init_data_accessor();
66943
67973
  init_enforcement();
67974
+ init_pipeline_stage();
67975
+ EXECUTION_STAGES_FOR_RELEASE = /* @__PURE__ */ new Set(["implementation", "validation", "testing"]);
66944
67976
  DEFAULT_VERIFICATION_REQUIRED_GATES = [
66945
67977
  "implemented",
66946
67978
  "testsPassed",
@@ -76515,8 +77547,8 @@ async function initializeSpawnAdapters(manifests) {
76515
77547
  if (!manifest.capabilities?.supportsSpawn) continue;
76516
77548
  if (spawnRegistry.hasAdapterForProvider(manifest.provider)) continue;
76517
77549
  try {
76518
- const { join: join135 } = await import("node:path");
76519
- const modulePath = join135(manifest.packagePath, manifest.entryPoint);
77550
+ const { join: join136 } = await import("node:path");
77551
+ const modulePath = join136(manifest.packagePath, manifest.entryPoint);
76520
77552
  const adapterModule = await import(modulePath);
76521
77553
  let SpawnProviderClass;
76522
77554
  for (const [exportName, exportValue] of Object.entries(adapterModule)) {
@@ -79319,6 +80351,85 @@ function checkLegacyAgentOutputs(projectRoot) {
79319
80351
  fix: null
79320
80352
  };
79321
80353
  }
80354
+ function checkCanonicalRcasdPaths(projectRoot) {
80355
+ const root = projectRoot ?? process.cwd();
80356
+ const cleoDir = join93(root, ".cleo");
80357
+ const failures = [];
80358
+ const deprecatedDirs = ["research", "consensus", "specs", "decomposition"];
80359
+ for (const dir of deprecatedDirs) {
80360
+ const dirPath = join93(cleoDir, dir);
80361
+ if (existsSync91(dirPath)) {
80362
+ try {
80363
+ const entries = __require("node:fs").readdirSync(dirPath).filter(
80364
+ (e) => !e.startsWith(".")
80365
+ );
80366
+ if (entries.length > 0) {
80367
+ failures.push(
80368
+ `deprecated .cleo/${dir}/ contains files (should migrate to .cleo/rcasd/{epicId}/${dir}/)`
80369
+ );
80370
+ }
80371
+ } catch {
80372
+ }
80373
+ }
80374
+ }
80375
+ const rcasdPath = join93(cleoDir, "rcasd");
80376
+ if (existsSync91(rcasdPath)) {
80377
+ try {
80378
+ const rootFiles = __require("node:fs").readdirSync(rcasdPath).filter(
80379
+ (e) => e.endsWith(".md")
80380
+ );
80381
+ if (rootFiles.length > 0) {
80382
+ failures.push(
80383
+ `misplaced .md files in .cleo/rcasd/ root (audit-*.md, etc. should be in .cleo/agent-outputs/)`
80384
+ );
80385
+ }
80386
+ } catch {
80387
+ }
80388
+ }
80389
+ const claudedocsPath = join93(root, "claudedocs");
80390
+ if (existsSync91(claudedocsPath)) {
80391
+ try {
80392
+ const agentOutputs = join93(claudedocsPath, "agent-outputs");
80393
+ if (existsSync91(agentOutputs)) {
80394
+ failures.push(
80395
+ `legacy claudedocs/agent-outputs/ directory exists (should migrate to .cleo/agent-outputs/)`
80396
+ );
80397
+ }
80398
+ } catch {
80399
+ }
80400
+ }
80401
+ if (failures.length > 0) {
80402
+ return {
80403
+ id: "canonical_rcasd_paths",
80404
+ category: "configuration",
80405
+ status: "warning",
80406
+ message: `Canonical path drift detected (ADR-045): ${failures.join("; ")}`,
80407
+ details: {
80408
+ issues: failures,
80409
+ canonical: {
80410
+ rcasdStages: ".cleo/rcasd/{epicId}/{stage}/{epicId}-{stage}.md",
80411
+ agentOutputs: ".cleo/agent-outputs/{taskId}-{slug}.md",
80412
+ publishedSpecs: "docs/specs/SPEC-NAME.md"
80413
+ }
80414
+ },
80415
+ fix: "cleo upgrade (migrates old paths) or manually move files per ADR-045"
80416
+ };
80417
+ }
80418
+ return {
80419
+ id: "canonical_rcasd_paths",
80420
+ category: "configuration",
80421
+ status: "passed",
80422
+ message: "All artifacts at canonical RCASD paths (ADR-045 compliant)",
80423
+ details: {
80424
+ canonical: {
80425
+ rcasdStages: ".cleo/rcasd/{epicId}/{stage}/{epicId}-{stage}.md",
80426
+ agentOutputs: ".cleo/agent-outputs/{taskId}-{slug}.md",
80427
+ publishedSpecs: "docs/specs/SPEC-NAME.md"
80428
+ }
80429
+ },
80430
+ fix: null
80431
+ };
80432
+ }
79322
80433
  function checkCaampMarkerIntegrity(projectRoot) {
79323
80434
  const root = projectRoot ?? process.cwd();
79324
80435
  const files = ["CLAUDE.md", "AGENTS.md"];
@@ -79631,6 +80742,8 @@ function runAllGlobalChecks(cleoHome, projectRoot) {
79631
80742
  checkCoreFilesNotIgnored(projectRoot),
79632
80743
  checkSqliteNotTracked(projectRoot),
79633
80744
  checkLegacyAgentOutputs(projectRoot),
80745
+ // ADR-045 canonical paths check (T708)
80746
+ checkCanonicalRcasdPaths(projectRoot),
79634
80747
  // Injection chain checks (T5153)
79635
80748
  checkCaampMarkerIntegrity(projectRoot),
79636
80749
  checkAtReferenceTargetExists(projectRoot),
@@ -80402,6 +81515,46 @@ async function getSystemHealth(projectRoot, opts) {
80402
81515
  if (existsSync92(dbPath)) {
80403
81516
  checks.push(checkAuditLogAvailability(dbPath));
80404
81517
  }
81518
+ if (existsSync92(dbPath) && databaseSyncCtor) {
81519
+ try {
81520
+ const tasksDb = new databaseSyncCtor(dbPath, { readOnly: true });
81521
+ let taskCount = 0;
81522
+ try {
81523
+ const tableExists3 = tasksDb.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='tasks'").get();
81524
+ if (tableExists3?.name) {
81525
+ const countRow = tasksDb.prepare("SELECT COUNT(*) as cnt FROM tasks").get();
81526
+ taskCount = countRow?.cnt ?? 0;
81527
+ }
81528
+ } finally {
81529
+ tasksDb.close();
81530
+ }
81531
+ if (taskCount === 0) {
81532
+ const { listSqliteBackups: listSqliteBackups2 } = await Promise.resolve().then(() => (init_sqlite_backup(), sqlite_backup_exports));
81533
+ const backups = listSqliteBackups2(projectRoot);
81534
+ if (backups.length > 0) {
81535
+ const latestBackup = backups[0];
81536
+ checks.push({
81537
+ name: "tasks_wipe_guard",
81538
+ status: "fail",
81539
+ message: `WIPE ALERT: tasks.db has 0 tasks but ${backups.length} backup(s) exist. Latest: ${latestBackup?.name ?? "unknown"} (${new Date(latestBackup?.mtimeMs ?? 0).toISOString()}). Probable data loss \u2014 restore via: cleo restore backup --file tasks.db. See docs/RECOVERY.md for the full procedure. (T724)`
81540
+ });
81541
+ } else {
81542
+ checks.push({
81543
+ name: "tasks_wipe_guard",
81544
+ status: "warn",
81545
+ message: "tasks.db has 0 tasks and no backups exist (fresh install or data loss without backup recovery)."
81546
+ });
81547
+ }
81548
+ } else {
81549
+ checks.push({
81550
+ name: "tasks_wipe_guard",
81551
+ status: "pass",
81552
+ message: `tasks.db integrity: ${taskCount} task(s) present`
81553
+ });
81554
+ }
81555
+ } catch {
81556
+ }
81557
+ }
80405
81558
  const sdDbPath = join94(cleoDir, "signaldock.db");
80406
81559
  if (existsSync92(sdDbPath)) {
80407
81560
  try {
@@ -80855,6 +82008,7 @@ async function coreDoctorReport(projectRoot) {
80855
82008
  checks.push(mapCheckResult(checkVitalFilesTracked(projectRoot)));
80856
82009
  checks.push(mapCheckResult(checkCoreFilesNotIgnored(projectRoot)));
80857
82010
  checks.push(mapCheckResult(checkLegacyAgentOutputs(projectRoot)));
82011
+ checks.push(mapCheckResult(checkCanonicalRcasdPaths(projectRoot)));
80858
82012
  const cleoGitHeadExists = existsSync92(join94(cleoDir, ".git", "HEAD"));
80859
82013
  checks.push({
80860
82014
  check: "cleo_git_repo",
@@ -88229,6 +89383,7 @@ var init_cleo = __esm({
88229
89383
  // packages/core/src/index.ts
88230
89384
  var init_src3 = __esm({
88231
89385
  "packages/core/src/index.ts"() {
89386
+ "use strict";
88232
89387
  init_src();
88233
89388
  init_adapters();
88234
89389
  init_admin();
@@ -91698,6 +92853,197 @@ var init_claude_mem_migration = __esm({
91698
92853
  }
91699
92854
  });
91700
92855
 
92856
+ // packages/core/src/memory/dream-cycle.ts
92857
+ function countNewObservations(afterTimestamp) {
92858
+ const db = getBrainNativeDb();
92859
+ if (!db) return 0;
92860
+ try {
92861
+ const row = db.prepare(
92862
+ `SELECT COUNT(*) AS cnt FROM brain_observations
92863
+ WHERE created_at > ? AND invalid_at IS NULL`
92864
+ ).get(afterTimestamp);
92865
+ return row?.cnt ?? 0;
92866
+ } catch {
92867
+ return 0;
92868
+ }
92869
+ }
92870
+ function getLastConsolidationTimestamp() {
92871
+ const db = getBrainNativeDb();
92872
+ if (!db) return null;
92873
+ try {
92874
+ const row = db.prepare(
92875
+ `SELECT started_at FROM brain_consolidation_events
92876
+ ORDER BY started_at DESC LIMIT 1`
92877
+ ).get();
92878
+ return row?.started_at ?? null;
92879
+ } catch {
92880
+ return null;
92881
+ }
92882
+ }
92883
+ function getLastRetrievalTimestamp() {
92884
+ const db = getBrainNativeDb();
92885
+ if (!db) return null;
92886
+ try {
92887
+ const row = db.prepare(`SELECT created_at FROM brain_retrieval_log ORDER BY created_at DESC LIMIT 1`).get();
92888
+ return row?.created_at ?? null;
92889
+ } catch {
92890
+ return null;
92891
+ }
92892
+ }
92893
+ function minutesSince(isoTimestamp2) {
92894
+ if (!isoTimestamp2) return Infinity;
92895
+ const normalised = isoTimestamp2.includes("T") ? isoTimestamp2 : isoTimestamp2.replace(" ", "T") + "Z";
92896
+ const ms2 = Date.now() - new Date(normalised).getTime();
92897
+ return ms2 / 6e4;
92898
+ }
92899
+ function checkVolumeTrigger(threshold) {
92900
+ const lastConsolidated = getLastConsolidationTimestamp();
92901
+ const after = lastConsolidated ?? "1970-01-01 00:00:00";
92902
+ const newObservationCount = countNewObservations(after);
92903
+ return {
92904
+ shouldTrigger: newObservationCount >= threshold,
92905
+ newObservationCount
92906
+ };
92907
+ }
92908
+ function checkIdleTrigger(idleThresholdMinutes) {
92909
+ const lastRetrievalTs = getLastRetrievalTimestamp();
92910
+ if (lastRetrievalTs === null) {
92911
+ return { shouldTrigger: false, idleMinutes: 0 };
92912
+ }
92913
+ const idleMinutes = minutesSince(lastRetrievalTs);
92914
+ return {
92915
+ shouldTrigger: idleMinutes >= idleThresholdMinutes,
92916
+ idleMinutes
92917
+ };
92918
+ }
92919
+ async function dispatchDream(projectRoot, sessionId, inline = false) {
92920
+ if (dreamInFlight) return;
92921
+ dreamInFlight = true;
92922
+ lastDreamAt = Date.now();
92923
+ const run = async () => {
92924
+ try {
92925
+ const { runConsolidation: runConsolidation2 } = await Promise.resolve().then(() => (init_brain_lifecycle(), brain_lifecycle_exports));
92926
+ await runConsolidation2(projectRoot, sessionId ?? null, "scheduled");
92927
+ } catch (err) {
92928
+ console.warn("[dream-cycle] Consolidation failed:", err);
92929
+ } finally {
92930
+ dreamInFlight = false;
92931
+ }
92932
+ };
92933
+ if (inline) {
92934
+ await run();
92935
+ } else {
92936
+ setImmediate(run);
92937
+ }
92938
+ }
92939
+ async function checkAndDream(projectRoot, opts = {}) {
92940
+ const volumeThreshold = opts.volumeThreshold ?? VOLUME_THRESHOLD_DEFAULT;
92941
+ const idleThresholdMinutes = opts.idleThresholdMinutes ?? IDLE_MINUTES_DEFAULT;
92942
+ try {
92943
+ await getBrainDb(projectRoot);
92944
+ } catch {
92945
+ return {
92946
+ triggered: false,
92947
+ tier: null,
92948
+ skippedReason: "brain.db unavailable"
92949
+ };
92950
+ }
92951
+ const msSinceLastDream = Date.now() - lastDreamAt;
92952
+ if (msSinceLastDream < DREAM_COOLDOWN_MS) {
92953
+ return {
92954
+ triggered: false,
92955
+ tier: null,
92956
+ skippedReason: `dream cooldown active (${Math.round(msSinceLastDream / 1e3)}s since last dream)`
92957
+ };
92958
+ }
92959
+ if (dreamInFlight) {
92960
+ return {
92961
+ triggered: false,
92962
+ tier: null,
92963
+ skippedReason: "dream already in flight"
92964
+ };
92965
+ }
92966
+ const volumeCheck = checkVolumeTrigger(volumeThreshold);
92967
+ if (volumeCheck.shouldTrigger) {
92968
+ await dispatchDream(projectRoot, opts.sessionId, opts.inline);
92969
+ return {
92970
+ triggered: true,
92971
+ tier: "volume",
92972
+ newObservationCount: volumeCheck.newObservationCount
92973
+ };
92974
+ }
92975
+ const idleCheck = checkIdleTrigger(idleThresholdMinutes);
92976
+ if (idleCheck.shouldTrigger) {
92977
+ await dispatchDream(projectRoot, opts.sessionId, opts.inline);
92978
+ return {
92979
+ triggered: true,
92980
+ tier: "idle",
92981
+ idleMinutes: idleCheck.idleMinutes
92982
+ };
92983
+ }
92984
+ return {
92985
+ triggered: false,
92986
+ tier: null,
92987
+ skippedReason: `volume below threshold (${volumeCheck.newObservationCount}/${volumeThreshold}); idle below threshold (${Math.round(idleCheck.idleMinutes)}/${idleThresholdMinutes} min)`,
92988
+ newObservationCount: volumeCheck.newObservationCount,
92989
+ idleMinutes: idleCheck.idleMinutes
92990
+ };
92991
+ }
92992
+ async function triggerManualDream(projectRoot, sessionId) {
92993
+ const { runConsolidation: runConsolidation2 } = await Promise.resolve().then(() => (init_brain_lifecycle(), brain_lifecycle_exports));
92994
+ const result = await runConsolidation2(projectRoot, sessionId ?? null, "manual");
92995
+ lastDreamAt = Date.now();
92996
+ return result;
92997
+ }
92998
+ function startDreamScheduler(projectRoot, hourUTC = NIGHTLY_HOUR_DEFAULT) {
92999
+ if (nightlyTimer !== null) return false;
93000
+ const msUntilNextFire = () => {
93001
+ const now2 = /* @__PURE__ */ new Date();
93002
+ const next = new Date(now2);
93003
+ next.setUTCHours(hourUTC, 0, 0, 0);
93004
+ if (next.getTime() <= now2.getTime()) {
93005
+ next.setUTCDate(next.getUTCDate() + 1);
93006
+ }
93007
+ return next.getTime() - now2.getTime();
93008
+ };
93009
+ const scheduleNext = () => {
93010
+ nightlyTimer = setTimeout(() => {
93011
+ nightlyTimer = null;
93012
+ checkAndDream(projectRoot, { inline: false }).catch((err) => {
93013
+ console.warn("[dream-cycle] Nightly cron failed:", err);
93014
+ });
93015
+ scheduleNext();
93016
+ }, msUntilNextFire());
93017
+ };
93018
+ scheduleNext();
93019
+ return true;
93020
+ }
93021
+ function stopDreamScheduler() {
93022
+ if (nightlyTimer === null) return false;
93023
+ clearTimeout(nightlyTimer);
93024
+ nightlyTimer = null;
93025
+ return true;
93026
+ }
93027
+ function _resetDreamState() {
93028
+ lastDreamAt = 0;
93029
+ dreamInFlight = false;
93030
+ stopDreamScheduler();
93031
+ }
93032
+ var VOLUME_THRESHOLD_DEFAULT, IDLE_MINUTES_DEFAULT, DREAM_COOLDOWN_MS, NIGHTLY_HOUR_DEFAULT, lastDreamAt, dreamInFlight, nightlyTimer;
93033
+ var init_dream_cycle = __esm({
93034
+ "packages/core/src/memory/dream-cycle.ts"() {
93035
+ "use strict";
93036
+ init_brain_sqlite();
93037
+ VOLUME_THRESHOLD_DEFAULT = 10;
93038
+ IDLE_MINUTES_DEFAULT = 30;
93039
+ DREAM_COOLDOWN_MS = 5 * 60 * 1e3;
93040
+ NIGHTLY_HOUR_DEFAULT = 4;
93041
+ lastDreamAt = 0;
93042
+ dreamInFlight = false;
93043
+ nightlyTimer = null;
93044
+ }
93045
+ });
93046
+
91701
93047
  // packages/core/src/memory/mental-model-queue.ts
91702
93048
  async function drainQueue() {
91703
93049
  if (_queue.length === 0) return 0;
@@ -91994,7 +93340,14 @@ function mapEdge(raw) {
91994
93340
  edgeType: raw.edge_type,
91995
93341
  weight: raw.weight,
91996
93342
  provenance: raw.provenance,
91997
- createdAt: raw.created_at
93343
+ createdAt: raw.created_at,
93344
+ // T673-M3 plasticity columns (default to neutral values if absent from SELECT)
93345
+ lastReinforcedAt: raw.last_reinforced_at ?? null,
93346
+ reinforcementCount: raw.reinforcement_count ?? 0,
93347
+ plasticityClass: raw.plasticity_class ?? "static",
93348
+ lastDepressedAt: raw.last_depressed_at ?? null,
93349
+ depressionCount: raw.depression_count ?? 0,
93350
+ stabilityScore: raw.stability_score ?? null
91998
93351
  };
91999
93352
  }
92000
93353
  async function traceBrainGraph(projectRoot, nodeId, maxDepth = 3) {
@@ -100849,9 +102202,9 @@ async function runUpgrade(options = {}) {
100849
102202
  mkdirSync29(backupDir, { recursive: true });
100850
102203
  }
100851
102204
  copyFileSync9(dbPath2, dbBackupPath);
100852
- const { createHash: createHash17 } = await import("node:crypto");
100853
- const origChecksum = createHash17("sha256").update(readFileSync87(dbPath2)).digest("hex");
100854
- const backupChecksum = createHash17("sha256").update(readFileSync87(dbBackupPath)).digest("hex");
102205
+ const { createHash: createHash18 } = await import("node:crypto");
102206
+ const origChecksum = createHash18("sha256").update(readFileSync87(dbPath2)).digest("hex");
102207
+ const backupChecksum = createHash18("sha256").update(readFileSync87(dbBackupPath)).digest("hex");
100855
102208
  if (origChecksum !== backupChecksum) {
100856
102209
  throw new Error(
100857
102210
  `Backup verification failed: checksum mismatch. Aborting migration to prevent data loss.`
@@ -113509,6 +114862,7 @@ __export(internal_exports, {
113509
114862
  WORKFLOW_GATE_SEQUENCE: () => WORKFLOW_GATE_SEQUENCE,
113510
114863
  WorkflowGateName: () => WorkflowGateName,
113511
114864
  WorkflowGateTracker: () => WorkflowGateTracker,
114865
+ _resetDreamState: () => _resetDreamState,
113512
114866
  _resetGlobalSignaldockDb_TESTING_ONLY: () => _resetGlobalSignaldockDb_TESTING_ONLY,
113513
114867
  adapters: () => adapters_exports,
113514
114868
  addChain: () => addChain,
@@ -113581,6 +114935,7 @@ __export(internal_exports, {
113581
114935
  channelToDistTag: () => channelToDistTag,
113582
114936
  checkAgentHealth: () => checkAgentHealth2,
113583
114937
  checkAllDependencies: () => checkAllDependencies,
114938
+ checkAndDream: () => checkAndDream,
113584
114939
  checkArchitectureDecisionManifest: () => checkArchitectureDecisionManifest,
113585
114940
  checkArtifactPublishManifest: () => checkArtifactPublishManifest,
113586
114941
  checkConduitDbHealth: () => checkConduitDbHealth,
@@ -113592,6 +114947,7 @@ __export(internal_exports, {
113592
114947
  checkEpicCompleteness: () => checkEpicCompleteness,
113593
114948
  checkGate: () => checkGate,
113594
114949
  checkGlobalSignaldockDbHealth: () => checkGlobalSignaldockDbHealth,
114950
+ checkIdleTrigger: () => checkIdleTrigger,
113595
114951
  checkImplementationManifest: () => checkImplementationManifest,
113596
114952
  checkProvenanceManifest: () => checkProvenanceManifest,
113597
114953
  checkReleaseManifest: () => checkReleaseManifest,
@@ -113605,6 +114961,7 @@ __export(internal_exports, {
113605
114961
  checkStorageMigration: () => checkStorageMigration,
113606
114962
  checkTestingManifest: () => checkTestingManifest,
113607
114963
  checkValidationManifest: () => checkValidationManifest,
114964
+ checkVolumeTrigger: () => checkVolumeTrigger,
113608
114965
  classifyError: () => classifyError,
113609
114966
  classifyProject: () => classifyProject,
113610
114967
  cleanupSessions: () => cleanupSessions,
@@ -114201,6 +115558,7 @@ __export(internal_exports, {
114201
115558
  snapshot: () => snapshot_exports,
114202
115559
  spawn: () => spawn_exports,
114203
115560
  spawnRegistry: () => spawnRegistry,
115561
+ startDreamScheduler: () => startDreamScheduler,
114204
115562
  startParallelExecution: () => startParallelExecution,
114205
115563
  startPhase: () => startPhase,
114206
115564
  startSession: () => startSession,
@@ -114208,6 +115566,7 @@ __export(internal_exports, {
114208
115566
  startupHealthCheck: () => startupHealthCheck,
114209
115567
  stats: () => stats_exports,
114210
115568
  sticky: () => sticky_exports,
115569
+ stopDreamScheduler: () => stopDreamScheduler,
114211
115570
  stopTask: () => stopTask,
114212
115571
  storeDetectedPattern: () => storeDetectedPattern,
114213
115572
  storeHealingStrategy: () => storeHealingStrategy,
@@ -114242,6 +115601,7 @@ __export(internal_exports, {
114242
115601
  tokenUsageTransportSchema: () => tokenUsageTransportSchema,
114243
115602
  touchLink: () => touchLink,
114244
115603
  trackMemoryUsage: () => trackMemoryUsage,
115604
+ triggerManualDream: () => triggerManualDream,
114245
115605
  ui: () => ui_exports,
114246
115606
  uncancelTask: () => uncancelTask,
114247
115607
  unpackBundle: () => unpackBundle,
@@ -114329,6 +115689,7 @@ var init_internal = __esm({
114329
115689
  init_brain_retrieval();
114330
115690
  init_brain_stdp();
114331
115691
  init_claude_mem_migration();
115692
+ init_dream_cycle();
114332
115693
  init_engine_compat();
114333
115694
  init_pipeline_manifest_sqlite();
114334
115695
  init_quality_feedback();
@@ -121701,7 +123062,7 @@ async function systemStats(projectRoot, params) {
121701
123062
  }
121702
123063
  const byPhase = {};
121703
123064
  for (const t of activeTasks) {
121704
- const phase = t.phase || "unassigned";
123065
+ const phase = t.pipelineStage || "unassigned";
121705
123066
  byPhase[phase] = (byPhase[phase] ?? 0) + 1;
121706
123067
  }
121707
123068
  const completedTasks = tasks2.filter((t) => t.status === "done" && t.completedAt && t.createdAt);
@@ -121787,10 +123148,10 @@ async function systemLog(projectRoot, filters) {
121787
123148
  }
121788
123149
  async function queryAuditLogSqlite(projectRoot, filters) {
121789
123150
  try {
121790
- const { join: join135 } = await import("node:path");
121791
- const { existsSync: existsSync135 } = await import("node:fs");
121792
- const dbPath = join135(projectRoot, ".cleo", "tasks.db");
121793
- if (!existsSync135(dbPath)) {
123151
+ const { join: join136 } = await import("node:path");
123152
+ const { existsSync: existsSync136 } = await import("node:fs");
123153
+ const dbPath = join136(projectRoot, ".cleo", "tasks.db");
123154
+ if (!existsSync136(dbPath)) {
121794
123155
  const offset = filters?.offset ?? 0;
121795
123156
  const limit = filters?.limit ?? 20;
121796
123157
  return {
@@ -127396,16 +128757,16 @@ var init_nexus2 = __esm({
127396
128757
  async function orchestrateClassify(request, context, projectRoot) {
127397
128758
  try {
127398
128759
  const { getCleoCantWorkflowsDir: getCleoCantWorkflowsDir2 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
127399
- const { readFileSync: readFileSync107, readdirSync: readdirSync42, existsSync: existsSync135 } = await import("node:fs");
127400
- const { join: join135 } = await import("node:path");
128760
+ const { readFileSync: readFileSync108, readdirSync: readdirSync43, existsSync: existsSync136 } = await import("node:fs");
128761
+ const { join: join136 } = await import("node:path");
127401
128762
  const workflowsDir = getCleoCantWorkflowsDir2();
127402
128763
  const combined = `${request} ${context ?? ""}`.toLowerCase();
127403
128764
  const matches = [];
127404
- if (existsSync135(workflowsDir)) {
127405
- const files = readdirSync42(workflowsDir).filter((f2) => f2.endsWith(".cant"));
128765
+ if (existsSync136(workflowsDir)) {
128766
+ const files = readdirSync43(workflowsDir).filter((f2) => f2.endsWith(".cant"));
127406
128767
  for (const file2 of files) {
127407
128768
  try {
127408
- const src = readFileSync107(join135(workflowsDir, file2), "utf-8");
128769
+ const src = readFileSync108(join136(workflowsDir, file2), "utf-8");
127409
128770
  const teamMatch = /^team\s+(\S+):/m.exec(src);
127410
128771
  if (!teamMatch) continue;
127411
128772
  const teamName = teamMatch[1];
@@ -127420,12 +128781,12 @@ async function orchestrateClassify(request, context, projectRoot) {
127420
128781
  }
127421
128782
  }
127422
128783
  }
127423
- const localCantDir = join135(projectRoot, ".cleo", "workflows");
127424
- if (existsSync135(localCantDir)) {
127425
- const files = readdirSync42(localCantDir).filter((f2) => f2.endsWith(".cant"));
128784
+ const localCantDir = join136(projectRoot, ".cleo", "workflows");
128785
+ if (existsSync136(localCantDir)) {
128786
+ const files = readdirSync43(localCantDir).filter((f2) => f2.endsWith(".cant"));
127426
128787
  for (const file2 of files) {
127427
128788
  try {
127428
- const src = readFileSync107(join135(localCantDir, file2), "utf-8");
128789
+ const src = readFileSync108(join136(localCantDir, file2), "utf-8");
127429
128790
  const teamMatch = /^team\s+(\S+):/m.exec(src);
127430
128791
  if (!teamMatch) continue;
127431
128792
  const teamName = teamMatch[1];
@@ -132070,8 +133431,8 @@ var init_cli = __esm({
132070
133431
 
132071
133432
  // packages/cleo/src/cli/index.ts
132072
133433
  init_internal();
132073
- import { readFileSync as readFileSync106 } from "node:fs";
132074
- import { dirname as dirname31, join as join134 } from "node:path";
133434
+ import { readFileSync as readFileSync107 } from "node:fs";
133435
+ import { dirname as dirname31, join as join135 } from "node:path";
132075
133436
  import { fileURLToPath as fileURLToPath8 } from "node:url";
132076
133437
 
132077
133438
  // node_modules/.pnpm/citty@0.2.1/node_modules/citty/dist/_chunks/libs/scule.mjs
@@ -133573,13 +134934,13 @@ function registerAgentCommand(program) {
133573
134934
  transportConfig: {},
133574
134935
  isActive: true
133575
134936
  });
133576
- const { existsSync: existsSync135, mkdirSync: mkdirSync35, writeFileSync: writeFileSync26 } = await import("node:fs");
133577
- const { join: join135 } = await import("node:path");
133578
- const cantDir = join135(".cleo", "agents");
133579
- const cantPath = join135(cantDir, `${agentId}.cant`);
134937
+ const { existsSync: existsSync136, mkdirSync: mkdirSync36, writeFileSync: writeFileSync27 } = await import("node:fs");
134938
+ const { join: join136 } = await import("node:path");
134939
+ const cantDir = join136(".cleo", "agents");
134940
+ const cantPath = join136(cantDir, `${agentId}.cant`);
133580
134941
  let cantScaffolded = false;
133581
- if (!existsSync135(cantPath)) {
133582
- mkdirSync35(cantDir, { recursive: true });
134942
+ if (!existsSync136(cantPath)) {
134943
+ mkdirSync36(cantDir, { recursive: true });
133583
134944
  const role = classification ?? "specialist";
133584
134945
  const cantContent = `---
133585
134946
  kind: agent
@@ -133629,7 +134990,7 @@ agent ${agentId}:
133629
134990
  enforcement:
133630
134991
  1: TODO \u2014 what does this agent push back on?
133631
134992
  `;
133632
- writeFileSync26(cantPath, cantContent, "utf-8");
134993
+ writeFileSync27(cantPath, cantContent, "utf-8");
133633
134994
  cantScaffolded = true;
133634
134995
  }
133635
134996
  cliOutput(
@@ -133638,7 +134999,7 @@ agent ${agentId}:
133638
134999
  data: {
133639
135000
  agentId: credential.agentId,
133640
135001
  displayName: credential.displayName,
133641
- cantFile: cantScaffolded ? cantPath : existsSync135(cantPath) ? cantPath : null,
135002
+ cantFile: cantScaffolded ? cantPath : existsSync136(cantPath) ? cantPath : null,
133642
135003
  cantScaffolded
133643
135004
  }
133644
135005
  },
@@ -133718,8 +135079,8 @@ agent ${agentId}:
133718
135079
  try {
133719
135080
  const { AgentRegistryAccessor: AgentRegistryAccessor2, getDb: getDb4 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
133720
135081
  const { createRuntime } = await import("@cleocode/runtime");
133721
- const { existsSync: existsSync135, readFileSync: readFileSync107 } = await import("node:fs");
133722
- const { join: join135 } = await import("node:path");
135082
+ const { existsSync: existsSync136, readFileSync: readFileSync108 } = await import("node:fs");
135083
+ const { join: join136 } = await import("node:path");
133723
135084
  await getDb4();
133724
135085
  const registry2 = new AgentRegistryAccessor2(process.cwd());
133725
135086
  const credential = await registry2.get(agentId);
@@ -133739,9 +135100,9 @@ agent ${agentId}:
133739
135100
  }
133740
135101
  let profile = null;
133741
135102
  let cantValidation = null;
133742
- const cantPath = opts["cant"] ?? join135(".cleo", "agents", `${agentId}.cant`);
133743
- if (existsSync135(cantPath)) {
133744
- profile = readFileSync107(cantPath, "utf-8");
135103
+ const cantPath = opts["cant"] ?? join136(".cleo", "agents", `${agentId}.cant`);
135104
+ if (existsSync136(cantPath)) {
135105
+ profile = readFileSync108(cantPath, "utf-8");
133745
135106
  try {
133746
135107
  const cantModule = await import("@cleocode/cant");
133747
135108
  const validate = "validate" in cantModule ? cantModule.validate : null;
@@ -134136,8 +135497,8 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134136
135497
  try {
134137
135498
  const { AgentRegistryAccessor: AgentRegistryAccessor2, getDb: getDb4 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
134138
135499
  const { createRuntime } = await import("@cleocode/runtime");
134139
- const { existsSync: existsSync135 } = await import("node:fs");
134140
- const { join: join135 } = await import("node:path");
135500
+ const { existsSync: existsSync136 } = await import("node:fs");
135501
+ const { join: join136 } = await import("node:path");
134141
135502
  const { execFile: execFile8 } = await import("node:child_process");
134142
135503
  const { promisify: promisify8 } = await import("node:util");
134143
135504
  const execFileAsync6 = promisify8(execFile8);
@@ -134157,8 +135518,8 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134157
135518
  }
134158
135519
  await registry2.update(agentId, { isActive: true });
134159
135520
  await registry2.markUsed(agentId);
134160
- const cantPath = join135(".cleo", "agents", `${agentId}.cant`);
134161
- const hasProfile = existsSync135(cantPath);
135521
+ const cantPath = join136(".cleo", "agents", `${agentId}.cant`);
135522
+ const hasProfile = existsSync136(cantPath);
134162
135523
  const runtime = await createRuntime(registry2, {
134163
135524
  agentId,
134164
135525
  pollIntervalMs: 5e3,
@@ -134781,12 +136142,12 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134781
136142
  });
134782
136143
  agent.command("install <path>").description("Install an agent from a .cantz archive or agent directory").option("--global", "Install to global tier (~/.local/share/cleo/cant/agents/)").action(async (sourcePath, opts) => {
134783
136144
  try {
134784
- const { existsSync: existsSync135, mkdirSync: mkdirSync35, cpSync, readFileSync: readFileSync107, rmSync: rmSync2, statSync: statSync22 } = await import("node:fs");
134785
- const { join: join135, basename: basename19, resolve: resolve17 } = await import("node:path");
134786
- const { homedir: homedir8 } = await import("node:os");
136145
+ const { existsSync: existsSync136, mkdirSync: mkdirSync36, cpSync, readFileSync: readFileSync108, rmSync: rmSync2, statSync: statSync22 } = await import("node:fs");
136146
+ const { join: join136, basename: basename19, resolve: resolve17 } = await import("node:path");
136147
+ const { homedir: homedir9 } = await import("node:os");
134787
136148
  const { tmpdir: tmpdir2 } = await import("node:os");
134788
136149
  const resolvedPath = resolve17(sourcePath);
134789
- if (!existsSync135(resolvedPath)) {
136150
+ if (!existsSync136(resolvedPath)) {
134790
136151
  cliOutput(
134791
136152
  {
134792
136153
  success: false,
@@ -134806,8 +136167,8 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134806
136167
  const isCantzArchive = resolvedPath.endsWith(".cantz") && statSync22(resolvedPath).isFile();
134807
136168
  if (isCantzArchive) {
134808
136169
  const { execFileSync: execFileSync19 } = await import("node:child_process");
134809
- tempDir = join135(tmpdir2(), `cleo-agent-install-${Date.now()}`);
134810
- mkdirSync35(tempDir, { recursive: true });
136170
+ tempDir = join136(tmpdir2(), `cleo-agent-install-${Date.now()}`);
136171
+ mkdirSync36(tempDir, { recursive: true });
134811
136172
  try {
134812
136173
  execFileSync19("unzip", ["-o", "-q", resolvedPath, "-d", tempDir], {
134813
136174
  encoding: "utf-8",
@@ -134828,9 +136189,9 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134828
136189
  process.exitCode = 6;
134829
136190
  return;
134830
136191
  }
134831
- const { readdirSync: readdirSync42 } = await import("node:fs");
134832
- const topLevel = readdirSync42(tempDir).filter((entry) => {
134833
- const entryPath = join135(tempDir, entry);
136192
+ const { readdirSync: readdirSync43 } = await import("node:fs");
136193
+ const topLevel = readdirSync43(tempDir).filter((entry) => {
136194
+ const entryPath = join136(tempDir, entry);
134834
136195
  return statSync22(entryPath).isDirectory();
134835
136196
  });
134836
136197
  if (topLevel.length !== 1) {
@@ -134849,7 +136210,7 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134849
136210
  return;
134850
136211
  }
134851
136212
  agentName = topLevel[0];
134852
- agentDir = join135(tempDir, agentName);
136213
+ agentDir = join136(tempDir, agentName);
134853
136214
  } else if (statSync22(resolvedPath).isDirectory()) {
134854
136215
  agentDir = resolvedPath;
134855
136216
  agentName = basename19(resolvedPath);
@@ -134867,8 +136228,8 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134867
136228
  process.exitCode = 6;
134868
136229
  return;
134869
136230
  }
134870
- const personaPath = join135(agentDir, "persona.cant");
134871
- if (!existsSync135(personaPath)) {
136231
+ const personaPath = join136(agentDir, "persona.cant");
136232
+ if (!existsSync136(personaPath)) {
134872
136233
  if (tempDir) rmSync2(tempDir, { recursive: true, force: true });
134873
136234
  cliOutput(
134874
136235
  {
@@ -134886,21 +136247,21 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134886
136247
  const isGlobal = opts["global"] === true;
134887
136248
  let targetRoot;
134888
136249
  if (isGlobal) {
134889
- const home = homedir8();
134890
- const xdgData = process.env["XDG_DATA_HOME"] ?? join135(home, ".local", "share");
134891
- targetRoot = join135(xdgData, "cleo", "cant", "agents");
136250
+ const home = homedir9();
136251
+ const xdgData = process.env["XDG_DATA_HOME"] ?? join136(home, ".local", "share");
136252
+ targetRoot = join136(xdgData, "cleo", "cant", "agents");
134892
136253
  } else {
134893
- targetRoot = join135(process.cwd(), ".cleo", "cant", "agents");
136254
+ targetRoot = join136(process.cwd(), ".cleo", "cant", "agents");
134894
136255
  }
134895
- const targetDir = join135(targetRoot, agentName);
134896
- mkdirSync35(targetRoot, { recursive: true });
136256
+ const targetDir = join136(targetRoot, agentName);
136257
+ mkdirSync36(targetRoot, { recursive: true });
134897
136258
  cpSync(agentDir, targetDir, { recursive: true, force: true });
134898
136259
  if (tempDir) {
134899
136260
  rmSync2(tempDir, { recursive: true, force: true });
134900
136261
  }
134901
136262
  let registered = false;
134902
136263
  try {
134903
- const persona = readFileSync107(join135(targetDir, "persona.cant"), "utf-8");
136264
+ const persona = readFileSync108(join136(targetDir, "persona.cant"), "utf-8");
134904
136265
  const descMatch = persona.match(/description:\s*"([^"]+)"/);
134905
136266
  const displayName = descMatch?.[1] ?? agentName;
134906
136267
  const { AgentRegistryAccessor: AgentRegistryAccessor2, getDb: getDb4 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
@@ -134947,11 +136308,11 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134947
136308
  });
134948
136309
  agent.command("pack <dir>").description("Package an agent directory as a .cantz archive").action(async (dir) => {
134949
136310
  try {
134950
- const { existsSync: existsSync135, statSync: statSync22 } = await import("node:fs");
136311
+ const { existsSync: existsSync136, statSync: statSync22 } = await import("node:fs");
134951
136312
  const { resolve: resolve17, basename: basename19, dirname: dirname32 } = await import("node:path");
134952
136313
  const { execFileSync: execFileSync19 } = await import("node:child_process");
134953
136314
  const resolvedDir = resolve17(dir);
134954
- if (!existsSync135(resolvedDir) || !statSync22(resolvedDir).isDirectory()) {
136315
+ if (!existsSync136(resolvedDir) || !statSync22(resolvedDir).isDirectory()) {
134955
136316
  cliOutput(
134956
136317
  {
134957
136318
  success: false,
@@ -134965,9 +136326,9 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
134965
136326
  process.exitCode = 4;
134966
136327
  return;
134967
136328
  }
134968
- const { join: join135 } = await import("node:path");
134969
- const personaPath = join135(resolvedDir, "persona.cant");
134970
- if (!existsSync135(personaPath)) {
136329
+ const { join: join136 } = await import("node:path");
136330
+ const personaPath = join136(resolvedDir, "persona.cant");
136331
+ if (!existsSync136(personaPath)) {
134971
136332
  cliOutput(
134972
136333
  {
134973
136334
  success: false,
@@ -135006,15 +136367,15 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
135006
136367
  return;
135007
136368
  }
135008
136369
  const archiveStats = statSync22(archivePath);
135009
- const { readdirSync: readdirSync42 } = await import("node:fs");
136370
+ const { readdirSync: readdirSync43 } = await import("node:fs");
135010
136371
  let fileCount = 0;
135011
136372
  const countFiles2 = (dirPath) => {
135012
- const entries = readdirSync42(dirPath, { withFileTypes: true });
136373
+ const entries = readdirSync43(dirPath, { withFileTypes: true });
135013
136374
  for (const entry of entries) {
135014
136375
  if (entry.isFile()) {
135015
136376
  fileCount++;
135016
136377
  } else if (entry.isDirectory()) {
135017
- countFiles2(join135(dirPath, entry.name));
136378
+ countFiles2(join136(dirPath, entry.name));
135018
136379
  }
135019
136380
  }
135020
136381
  };
@@ -135041,9 +136402,9 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
135041
136402
  });
135042
136403
  agent.command("create").description("Scaffold a new agent package with persona.cant and manifest.json").requiredOption("--name <name>", "Agent name (kebab-case)").requiredOption("--role <role>", "Agent role: orchestrator, lead, worker, or docs-worker").option("--tier <tier>", "Agent tier: low, mid, or high (defaults based on role)").option("--team <teamName>", "Team this agent belongs to").option("--domain <description>", "Domain description for file permissions and context").option("--global", "Create in global tier (~/.local/share/cleo/cant/agents/)").option("--seed-brain", "Create expertise/mental-model-seed.md and seed a BRAIN observation").option("--parent <parentAgent>", "Parent agent name in the hierarchy").action(async (opts) => {
135043
136404
  try {
135044
- const { existsSync: existsSync135, mkdirSync: mkdirSync35, writeFileSync: writeFileSync26 } = await import("node:fs");
135045
- const { join: join135 } = await import("node:path");
135046
- const { homedir: homedir8 } = await import("node:os");
136405
+ const { existsSync: existsSync136, mkdirSync: mkdirSync36, writeFileSync: writeFileSync27 } = await import("node:fs");
136406
+ const { join: join136 } = await import("node:path");
136407
+ const { homedir: homedir9 } = await import("node:os");
135047
136408
  const name2 = opts["name"];
135048
136409
  const role = opts["role"];
135049
136410
  const tier = opts["tier"] ?? inferTierFromRole(role);
@@ -135101,14 +136462,14 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
135101
136462
  }
135102
136463
  let targetRoot;
135103
136464
  if (isGlobal) {
135104
- const home = homedir8();
135105
- const xdgData = process.env["XDG_DATA_HOME"] ?? join135(home, ".local", "share");
135106
- targetRoot = join135(xdgData, "cleo", "cant", "agents");
136465
+ const home = homedir9();
136466
+ const xdgData = process.env["XDG_DATA_HOME"] ?? join136(home, ".local", "share");
136467
+ targetRoot = join136(xdgData, "cleo", "cant", "agents");
135107
136468
  } else {
135108
- targetRoot = join135(process.cwd(), ".cleo", "cant", "agents");
136469
+ targetRoot = join136(process.cwd(), ".cleo", "cant", "agents");
135109
136470
  }
135110
- const agentDir = join135(targetRoot, name2);
135111
- if (existsSync135(agentDir)) {
136471
+ const agentDir = join136(targetRoot, name2);
136472
+ if (existsSync136(agentDir)) {
135112
136473
  cliOutput(
135113
136474
  {
135114
136475
  success: false,
@@ -135123,7 +136484,7 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
135123
136484
  process.exitCode = 6;
135124
136485
  return;
135125
136486
  }
135126
- mkdirSync35(agentDir, { recursive: true });
136487
+ mkdirSync36(agentDir, { recursive: true });
135127
136488
  const personaContent = generatePersonaCant({
135128
136489
  name: name2,
135129
136490
  role,
@@ -135132,29 +136493,29 @@ Task ${taskId} reassigned to you by ${active.agentId}. Run: cleo show ${taskId}
135132
136493
  domain: domain2,
135133
136494
  parent
135134
136495
  });
135135
- writeFileSync26(join135(agentDir, "persona.cant"), personaContent, "utf-8");
136496
+ writeFileSync27(join136(agentDir, "persona.cant"), personaContent, "utf-8");
135136
136497
  const manifest = generateManifest2({ name: name2, role, tier, domain: domain2 });
135137
- writeFileSync26(
135138
- join135(agentDir, "manifest.json"),
136498
+ writeFileSync27(
136499
+ join136(agentDir, "manifest.json"),
135139
136500
  `${JSON.stringify(manifest, null, 2)}
135140
136501
  `,
135141
136502
  "utf-8"
135142
136503
  );
135143
136504
  const createdFiles = [
135144
- join135(agentDir, "persona.cant"),
135145
- join135(agentDir, "manifest.json")
136505
+ join136(agentDir, "persona.cant"),
136506
+ join136(agentDir, "manifest.json")
135146
136507
  ];
135147
136508
  if (team) {
135148
136509
  const teamConfigContent = generateTeamConfig(name2, role, team);
135149
- writeFileSync26(join135(agentDir, "team-config.cant"), teamConfigContent, "utf-8");
135150
- createdFiles.push(join135(agentDir, "team-config.cant"));
136510
+ writeFileSync27(join136(agentDir, "team-config.cant"), teamConfigContent, "utf-8");
136511
+ createdFiles.push(join136(agentDir, "team-config.cant"));
135151
136512
  }
135152
136513
  if (seedBrain) {
135153
- const expertiseDir = join135(agentDir, "expertise");
135154
- mkdirSync35(expertiseDir, { recursive: true });
136514
+ const expertiseDir = join136(agentDir, "expertise");
136515
+ mkdirSync36(expertiseDir, { recursive: true });
135155
136516
  const seedContent = generateMentalModelSeed(name2, role, domain2);
135156
- writeFileSync26(join135(expertiseDir, "mental-model-seed.md"), seedContent, "utf-8");
135157
- createdFiles.push(join135(expertiseDir, "mental-model-seed.md"));
136517
+ writeFileSync27(join136(expertiseDir, "mental-model-seed.md"), seedContent, "utf-8");
136518
+ createdFiles.push(join136(expertiseDir, "mental-model-seed.md"));
135158
136519
  try {
135159
136520
  const { execFile: execFile8 } = await import("node:child_process");
135160
136521
  const { promisify: promisify8 } = await import("node:util");
@@ -137025,10 +138386,10 @@ function registerCheckCommand(program) {
137025
138386
  );
137026
138387
  });
137027
138388
  check2.command("chain-validate <file>").description("Validate a WarpChain definition from a JSON file").action(async (file2) => {
137028
- const { readFileSync: readFileSync107 } = await import("node:fs");
138389
+ const { readFileSync: readFileSync108 } = await import("node:fs");
137029
138390
  let chain;
137030
138391
  try {
137031
- chain = JSON.parse(readFileSync107(file2, "utf8"));
138392
+ chain = JSON.parse(readFileSync108(file2, "utf8"));
137032
138393
  } catch (err) {
137033
138394
  const message = err instanceof Error ? err.message : String(err);
137034
138395
  console.error(`Failed to read or parse chain file: ${message}`);
@@ -139472,6 +140833,55 @@ function registerMapCommand(program) {
139472
140833
  init_internal();
139473
140834
  init_cli();
139474
140835
  init_renderers();
140836
+ import { createHash as createHash17 } from "node:crypto";
140837
+ import { existsSync as existsSync135, mkdirSync as mkdirSync35, readdirSync as readdirSync42, readFileSync as readFileSync105, writeFileSync as writeFileSync26 } from "node:fs";
140838
+ import { homedir as homedir8 } from "node:os";
140839
+ import { join as join132 } from "node:path";
140840
+ function parseMemoryFileFrontmatter(raw) {
140841
+ const lines = raw.split("\n");
140842
+ if (!lines[0]?.trim().startsWith("---")) {
140843
+ return { body: raw.trim() };
140844
+ }
140845
+ const endIdx = lines.slice(1).findIndex((l) => /^---\s*$/.test(l));
140846
+ if (endIdx === -1) {
140847
+ return { body: raw.trim() };
140848
+ }
140849
+ const fmLines = lines.slice(1, endIdx + 1);
140850
+ const body = lines.slice(endIdx + 2).join("\n").trim();
140851
+ const fm = {};
140852
+ for (const line2 of fmLines) {
140853
+ const colonIdx = line2.indexOf(":");
140854
+ if (colonIdx === -1) continue;
140855
+ const key = line2.slice(0, colonIdx).trim();
140856
+ const value = line2.slice(colonIdx + 1).trim();
140857
+ if (key && value) fm[key] = value;
140858
+ }
140859
+ return {
140860
+ name: fm["name"],
140861
+ description: fm["description"],
140862
+ type: fm["type"],
140863
+ body
140864
+ };
140865
+ }
140866
+ function memoryContentHash(title, body) {
140867
+ return createHash17("sha256").update(`${title}
140868
+ ${body}`).digest("hex").slice(0, 16);
140869
+ }
140870
+ function loadImportHashes(stateFile) {
140871
+ try {
140872
+ if (!existsSync135(stateFile)) return /* @__PURE__ */ new Set();
140873
+ const raw = readFileSync105(stateFile, "utf-8");
140874
+ const parsed = JSON.parse(raw);
140875
+ return new Set(parsed.hashes);
140876
+ } catch {
140877
+ return /* @__PURE__ */ new Set();
140878
+ }
140879
+ }
140880
+ function saveImportHashes(stateFile, hashes) {
140881
+ const dir = stateFile.slice(0, stateFile.lastIndexOf("/"));
140882
+ if (!existsSync135(dir)) mkdirSync35(dir, { recursive: true });
140883
+ writeFileSync26(stateFile, JSON.stringify({ hashes: [...hashes] }, null, 2), "utf-8");
140884
+ }
139475
140885
  function registerMemoryBrainCommand(program) {
139476
140886
  const memory = program.command("memory").description("BRAIN memory operations (patterns, learnings)");
139477
140887
  memory.command("store").description("Store a pattern or learning to BRAIN memory").requiredOption("--type <type>", "Memory type: pattern or learning").requiredOption("--content <text>", "Content of the memory entry").option("--context <text>", "Context in which the pattern/learning was observed").option("--source <text>", "Source of the learning").option(
@@ -139887,6 +141297,206 @@ function registerMemoryBrainCommand(program) {
139887
141297
  process.exit(1);
139888
141298
  }
139889
141299
  });
141300
+ memory.command("dream").description(
141301
+ "Manually trigger the full auto-dream cycle: consolidation pipeline including R-STDP reward backfill (Step 9a), STDP plasticity (Step 9b), and homeostatic decay (Step 9c). Equivalent to autonomous autonomous nightly consolidation but triggered on demand. Idempotent \u2014 safe to run multiple times."
141302
+ ).option("--json", "Output results as JSON").action(async (opts) => {
141303
+ const root = getProjectRoot();
141304
+ const isJson = !!opts.json;
141305
+ if (!isJson) {
141306
+ console.log("Triggering dream cycle (full consolidation including STDP plasticity)...");
141307
+ }
141308
+ try {
141309
+ const result = await triggerManualDream(root);
141310
+ if (isJson) {
141311
+ console.log(
141312
+ JSON.stringify(
141313
+ {
141314
+ success: true,
141315
+ data: result,
141316
+ meta: {
141317
+ operation: "memory.dream",
141318
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
141319
+ }
141320
+ },
141321
+ null,
141322
+ 2
141323
+ )
141324
+ );
141325
+ return;
141326
+ }
141327
+ console.log("\nDream cycle complete.");
141328
+ console.log(` Deduplicated: ${result.deduplicated}`);
141329
+ console.log(` Quality recomp: ${result.qualityRecomputed}`);
141330
+ console.log(` Tier promoted: ${result.tierPromotions.promoted.length} entries promoted`);
141331
+ console.log(` Tier evicted: ${result.tierPromotions.evicted.length} entries evicted`);
141332
+ console.log(` Contradictions: ${result.contradictions}`);
141333
+ console.log(` Soft evicted: ${result.softEvicted}`);
141334
+ console.log(` Edges strength: ${result.edgesStrengthened}`);
141335
+ console.log(` Summaries gen: ${result.summariesGenerated}`);
141336
+ if (result.graphLinksCreated !== void 0) {
141337
+ console.log(` Graph links: ${result.graphLinksCreated}`);
141338
+ }
141339
+ if (result.rewardBackfilled !== void 0) {
141340
+ console.log(
141341
+ ` Reward backfill: ${result.rewardBackfilled.rowsLabeled} labeled, ${result.rewardBackfilled.rowsSkipped} skipped`
141342
+ );
141343
+ }
141344
+ if (result.stdpPlasticity !== void 0) {
141345
+ console.log(
141346
+ ` STDP plasticity: ${result.stdpPlasticity.ltpEvents} LTP, ${result.stdpPlasticity.ltdEvents} LTD, ${result.stdpPlasticity.edgesCreated} edges created`
141347
+ );
141348
+ }
141349
+ if (result.homeostaticDecay !== void 0) {
141350
+ console.log(
141351
+ ` Decay/pruning: ${result.homeostaticDecay.edgesDecayed} decayed, ${result.homeostaticDecay.edgesPruned} pruned`
141352
+ );
141353
+ }
141354
+ } catch (err) {
141355
+ const message = err instanceof Error ? err.message : String(err);
141356
+ if (isJson) {
141357
+ console.log(JSON.stringify({ success: false, error: message }));
141358
+ } else {
141359
+ console.error(`Dream cycle failed: ${message}`);
141360
+ }
141361
+ process.exit(1);
141362
+ }
141363
+ });
141364
+ memory.command("import").description(
141365
+ "Import memory files from a provider-specific directory (e.g. ~/.claude/projects/*/memory/) into brain.db. Enables provider-agnostic memory via CLEO CLI instead of Claude Code MEMORY.md."
141366
+ ).option(
141367
+ "--from <dir>",
141368
+ "Source directory containing *.md memory files (default: ~/.claude/projects/-mnt-projects-cleocode/memory)"
141369
+ ).option("--dry-run", "Print what would be imported without writing to brain.db").option("--json", "Output results as JSON").action(async (opts) => {
141370
+ const sourceDir = opts.from ?? join132(homedir8(), ".claude", "projects", "-mnt-projects-cleocode", "memory");
141371
+ const isDryRun = !!opts.dryRun;
141372
+ const isJson = !!opts.json;
141373
+ const projectRoot = getProjectRoot();
141374
+ const stateFile = join132(projectRoot, ".cleo", "migrate-memory-hashes.json");
141375
+ if (!existsSync135(sourceDir)) {
141376
+ const msg = `Source directory not found: ${sourceDir}`;
141377
+ if (isJson) {
141378
+ console.log(JSON.stringify({ success: false, error: msg }));
141379
+ } else {
141380
+ console.error(msg);
141381
+ }
141382
+ process.exit(1);
141383
+ }
141384
+ const files = readdirSync42(sourceDir).filter((f2) => f2.endsWith(".md") && f2 !== "MEMORY.md").map((f2) => join132(sourceDir, f2));
141385
+ const importedHashes = isDryRun ? /* @__PURE__ */ new Set() : loadImportHashes(stateFile);
141386
+ const stats2 = { total: files.length, imported: 0, skipped: 0, errors: 0 };
141387
+ const importedEntries = [];
141388
+ const skippedEntries = [];
141389
+ const errorEntries = [];
141390
+ if (!isJson) {
141391
+ console.log(`Importing memory from: ${sourceDir}`);
141392
+ console.log(`Files found: ${files.length}`);
141393
+ if (isDryRun) console.log("Mode: DRY RUN");
141394
+ console.log("");
141395
+ }
141396
+ for (const filePath of files) {
141397
+ const fileName = filePath.split("/").pop() ?? filePath;
141398
+ try {
141399
+ const raw = readFileSync105(filePath, "utf-8");
141400
+ if (!raw.trim()) {
141401
+ stats2.skipped++;
141402
+ skippedEntries.push({ file: fileName, reason: "empty file" });
141403
+ continue;
141404
+ }
141405
+ const { name: name2, description, type, body } = parseMemoryFileFrontmatter(raw);
141406
+ const title = name2 ?? fileName.replace(/\.md$/, "").replace(/-/g, " ");
141407
+ const bodyParts = [description, body].filter(Boolean);
141408
+ const fullText = bodyParts.join("\n\n").trim();
141409
+ if (!fullText) {
141410
+ stats2.skipped++;
141411
+ skippedEntries.push({ file: fileName, reason: "empty body" });
141412
+ continue;
141413
+ }
141414
+ const hash2 = memoryContentHash(title, fullText);
141415
+ if (!isDryRun && importedHashes.has(hash2)) {
141416
+ stats2.skipped++;
141417
+ skippedEntries.push({ file: fileName, reason: `already imported (hash: ${hash2})` });
141418
+ if (!isJson) console.log(` [SKIP] ${fileName}`);
141419
+ continue;
141420
+ }
141421
+ const entryType = type ?? "project";
141422
+ if (!isJson) {
141423
+ const prefix = isDryRun ? "[DRY-RUN]" : "[IMPORT]";
141424
+ console.log(` ${prefix} ${fileName} (type: ${entryType})`);
141425
+ }
141426
+ if (!isDryRun) {
141427
+ if (entryType === "feedback") {
141428
+ await dispatchFromCli(
141429
+ "mutate",
141430
+ "memory",
141431
+ "learning.store",
141432
+ {
141433
+ insight: `[MIGRATED] ${title}: ${fullText}`,
141434
+ source: "manual",
141435
+ confidence: 0.8,
141436
+ actionable: false
141437
+ },
141438
+ { command: "memory", operation: "memory.learning.store" }
141439
+ );
141440
+ } else {
141441
+ const observeType = entryType === "project" ? "feature" : entryType === "reference" ? "discovery" : entryType === "user" ? "change" : "discovery";
141442
+ await dispatchFromCli(
141443
+ "mutate",
141444
+ "memory",
141445
+ "observe",
141446
+ {
141447
+ text: `[MIGRATED] ${title}: ${fullText}`,
141448
+ title: `[MIGRATED] ${title}`,
141449
+ type: observeType,
141450
+ sourceType: "manual"
141451
+ },
141452
+ { command: "memory", operation: "memory.observe" }
141453
+ );
141454
+ }
141455
+ importedHashes.add(hash2);
141456
+ }
141457
+ stats2.imported++;
141458
+ importedEntries.push({ file: fileName, type: entryType, title });
141459
+ } catch (err) {
141460
+ stats2.errors++;
141461
+ const message = err instanceof Error ? err.message : String(err);
141462
+ errorEntries.push({ file: fileName, error: message });
141463
+ if (!isJson) console.error(` [ERROR] ${fileName}: ${message}`);
141464
+ }
141465
+ }
141466
+ if (!isDryRun) {
141467
+ saveImportHashes(stateFile, importedHashes);
141468
+ }
141469
+ if (isJson) {
141470
+ console.log(
141471
+ JSON.stringify(
141472
+ {
141473
+ success: stats2.errors === 0,
141474
+ data: {
141475
+ ...stats2,
141476
+ dryRun: isDryRun,
141477
+ imported: importedEntries,
141478
+ skipped: skippedEntries,
141479
+ errors: errorEntries
141480
+ },
141481
+ meta: {
141482
+ operation: "memory.import",
141483
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
141484
+ }
141485
+ },
141486
+ null,
141487
+ 2
141488
+ )
141489
+ );
141490
+ } else {
141491
+ console.log("");
141492
+ console.log("=== Import Complete ===");
141493
+ console.log(`Total: ${stats2.total}`);
141494
+ console.log(`Imported: ${stats2.imported}`);
141495
+ console.log(`Skipped: ${stats2.skipped}`);
141496
+ console.log(`Errors: ${stats2.errors}`);
141497
+ }
141498
+ if (stats2.errors > 0) process.exit(1);
141499
+ });
139890
141500
  }
139891
141501
 
139892
141502
  // packages/cleo/src/cli/commands/migrate-claude-mem.ts
@@ -141344,17 +142954,17 @@ function registerNexusCommand(program) {
141344
142954
  const autoRegister = !!opts["autoRegister"];
141345
142955
  const includeExisting = !!opts["includeExisting"];
141346
142956
  const maxDepth = Math.max(1, Math.min(opts["maxDepth"] ?? 4, 20));
141347
- const { homedir: homedir8 } = await import("node:os");
141348
- const home = homedir8();
142957
+ const { homedir: homedir9 } = await import("node:os");
142958
+ const home = homedir9();
141349
142959
  const defaultRoots = [path10.join(home, "code"), path10.join(home, "projects"), "/mnt/projects"];
141350
142960
  const rawRoots = typeof opts["roots"] === "string" && opts["roots"].trim().length > 0 ? opts["roots"].split(",").map((r) => r.trim()).filter((r) => r.length > 0).map(
141351
142961
  (r) => r.startsWith("~") ? path10.join(home, r.slice(1)) : path10.resolve(r)
141352
142962
  ) : defaultRoots;
141353
- const { existsSync: existsSync135, readdirSync: readdirSync42, statSync: statSync22 } = await import("node:fs");
142963
+ const { existsSync: existsSync136, readdirSync: readdirSync43, statSync: statSync22 } = await import("node:fs");
141354
142964
  const { Dirent } = await import("node:fs");
141355
142965
  const roots = rawRoots.filter((r) => {
141356
142966
  try {
141357
- return existsSync135(r) && statSync22(r).isDirectory();
142967
+ return existsSync136(r) && statSync22(r).isDirectory();
141358
142968
  } catch {
141359
142969
  return false;
141360
142970
  }
@@ -141395,7 +143005,7 @@ function registerNexusCommand(program) {
141395
143005
  if (depth > maxDepth) return [];
141396
143006
  let entries;
141397
143007
  try {
141398
- entries = readdirSync42(dir, { withFileTypes: true });
143008
+ entries = readdirSync43(dir, { withFileTypes: true });
141399
143009
  } catch {
141400
143010
  return [];
141401
143011
  }
@@ -141938,8 +143548,8 @@ function registerNexusCommand(program) {
141938
143548
  return;
141939
143549
  }
141940
143550
  if (outputFile) {
141941
- const { writeFileSync: writeFileSync26 } = await import("node:fs");
141942
- writeFileSync26(outputFile, output, "utf-8");
143551
+ const { writeFileSync: writeFileSync27 } = await import("node:fs");
143552
+ writeFileSync27(outputFile, output, "utf-8");
141943
143553
  process.stdout.write(
141944
143554
  `[nexus] Exported to ${outputFile} (${nodes.length} nodes, ${relations.length} edges)
141945
143555
  `
@@ -143771,7 +145381,7 @@ init_src();
143771
145381
  init_internal();
143772
145382
  import { execFile as execFile7 } from "node:child_process";
143773
145383
  import { readFile as readFile23 } from "node:fs/promises";
143774
- import { join as join132 } from "node:path";
145384
+ import { join as join133 } from "node:path";
143775
145385
  import * as readline2 from "node:readline";
143776
145386
  import { promisify as promisify7 } from "node:util";
143777
145387
  init_renderers();
@@ -143780,7 +145390,7 @@ var GITHUB_REPO = BUILD_CONFIG.repository.fullName;
143780
145390
  async function getCurrentVersion() {
143781
145391
  const cleoHome = getCleoHome();
143782
145392
  try {
143783
- const content = await readFile23(join132(cleoHome, "VERSION"), "utf-8");
145393
+ const content = await readFile23(join133(cleoHome, "VERSION"), "utf-8");
143784
145394
  return (content.split("\n")[0] ?? "unknown").trim();
143785
145395
  } catch {
143786
145396
  return "unknown";
@@ -143834,7 +145444,7 @@ async function writeRuntimeVersionMetadata(mode, source, version2) {
143834
145444
  ];
143835
145445
  await import("node:fs/promises").then(
143836
145446
  ({ writeFile: writeFile15, mkdir: mkdir20 }) => mkdir20(cleoHome, { recursive: true }).then(
143837
- () => writeFile15(join132(cleoHome, "VERSION"), `${lines.join("\n")}
145447
+ () => writeFile15(join133(cleoHome, "VERSION"), `${lines.join("\n")}
143838
145448
  `, "utf-8")
143839
145449
  )
143840
145450
  );
@@ -144887,10 +146497,10 @@ function registerSyncCommand(program) {
144887
146497
  "How to resolve conflicts: keep-cleo, keep-external, or newest (default: keep-cleo)",
144888
146498
  "keep-cleo"
144889
146499
  ).action(async (file2, opts) => {
144890
- const { readFileSync: readFileSync107 } = await import("node:fs");
146500
+ const { readFileSync: readFileSync108 } = await import("node:fs");
144891
146501
  let externalTasks;
144892
146502
  try {
144893
- externalTasks = JSON.parse(readFileSync107(file2, "utf8"));
146503
+ externalTasks = JSON.parse(readFileSync108(file2, "utf8"));
144894
146504
  } catch (err) {
144895
146505
  const message = err instanceof Error ? err.message : String(err);
144896
146506
  console.error(`Failed to read or parse external tasks file: ${message}`);
@@ -144986,11 +146596,11 @@ function registerTestingCommand(program) {
144986
146596
  init_internal();
144987
146597
  init_cli();
144988
146598
  init_renderers();
144989
- import { readFileSync as readFileSync105 } from "node:fs";
146599
+ import { readFileSync as readFileSync106 } from "node:fs";
144990
146600
  function readPayload(opts, textKey, fileKey) {
144991
146601
  const text3 = opts[textKey];
144992
146602
  const file2 = opts[fileKey];
144993
- if (file2) return readFileSync105(file2, "utf-8");
146603
+ if (file2) return readFileSync106(file2, "utf-8");
144994
146604
  return text3;
144995
146605
  }
144996
146606
  function registerTokenCommand(program) {
@@ -145240,16 +146850,16 @@ init_src3();
145240
146850
  init_renderers();
145241
146851
  import { execFileSync as execFileSync18, spawn as spawn2 } from "node:child_process";
145242
146852
  import { mkdir as mkdir19, open, readFile as readFile24, rm as rm3, stat as stat3, writeFile as writeFile14 } from "node:fs/promises";
145243
- import { join as join133 } from "node:path";
146853
+ import { join as join134 } from "node:path";
145244
146854
  var DEFAULT_PORT = 3456;
145245
146855
  var DEFAULT_HOST = "127.0.0.1";
145246
146856
  function getWebPaths() {
145247
146857
  const cleoHome = getCleoHome();
145248
146858
  return {
145249
- pidFile: join133(cleoHome, "web-server.pid"),
145250
- configFile: join133(cleoHome, "web-server.json"),
145251
- logDir: join133(cleoHome, "logs"),
145252
- logFile: join133(cleoHome, "logs", "web-server.log")
146859
+ pidFile: join134(cleoHome, "web-server.pid"),
146860
+ configFile: join134(cleoHome, "web-server.json"),
146861
+ logDir: join134(cleoHome, "logs"),
146862
+ logFile: join134(cleoHome, "logs", "web-server.log")
145253
146863
  };
145254
146864
  }
145255
146865
  function isProcessRunning(pid) {
@@ -145281,99 +146891,99 @@ async function getStatus() {
145281
146891
  return { running: false, pid: null, port: null, host: null, url: null };
145282
146892
  }
145283
146893
  }
146894
+ async function startWebServer(port, host) {
146895
+ const { pidFile, configFile, logFile, logDir } = getWebPaths();
146896
+ const status = await getStatus();
146897
+ if (status.running) {
146898
+ throw new CleoError(1 /* GENERAL_ERROR */, `Server already running (PID: ${status.pid})`);
146899
+ }
146900
+ const projectRoot = process.env["CLEO_ROOT"] ?? process.cwd();
146901
+ const studioDir = process.env["CLEO_STUDIO_DIR"] ?? join134(projectRoot, "packages", "studio", "build");
146902
+ await mkdir19(logDir, { recursive: true });
146903
+ await writeFile14(
146904
+ configFile,
146905
+ JSON.stringify({
146906
+ port,
146907
+ host,
146908
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
146909
+ })
146910
+ );
146911
+ const webIndexPath = join134(studioDir, "index.js");
146912
+ try {
146913
+ await stat3(webIndexPath);
146914
+ } catch {
146915
+ try {
146916
+ execFileSync18("pnpm", ["--filter", "@cleocode/studio", "run", "build"], {
146917
+ cwd: projectRoot,
146918
+ stdio: "ignore"
146919
+ });
146920
+ } catch {
146921
+ throw new CleoError(
146922
+ 1 /* GENERAL_ERROR */,
146923
+ `Studio build failed. Run: pnpm --filter @cleocode/studio run build
146924
+ Logs: ${logFile}`
146925
+ );
146926
+ }
146927
+ }
146928
+ const logFileHandle = await open(logFile, "a");
146929
+ const serverProcess = spawn2("node", [webIndexPath], {
146930
+ cwd: studioDir,
146931
+ env: {
146932
+ ...process.env,
146933
+ HOST: host,
146934
+ PORT: String(port),
146935
+ // Pass CLEO paths through to the studio server
146936
+ CLEO_ROOT: projectRoot
146937
+ },
146938
+ detached: true,
146939
+ stdio: ["ignore", logFileHandle.fd, logFileHandle.fd]
146940
+ });
146941
+ serverProcess.unref();
146942
+ const pidFileTmp = `${pidFile}.tmp`;
146943
+ await writeFile14(pidFileTmp, String(serverProcess.pid));
146944
+ await rm3(pidFile, { force: true });
146945
+ await writeFile14(pidFile, String(serverProcess.pid));
146946
+ await rm3(pidFileTmp, { force: true });
146947
+ await logFileHandle.close();
146948
+ const maxAttempts = 30;
146949
+ let started = false;
146950
+ for (let i = 0; i < maxAttempts; i++) {
146951
+ try {
146952
+ const response = await fetch(`http://${host}:${port}/api/health`);
146953
+ if (response.ok) {
146954
+ started = true;
146955
+ break;
146956
+ }
146957
+ } catch {
146958
+ }
146959
+ await new Promise((resolve17) => setTimeout(resolve17, 500));
146960
+ }
146961
+ if (!started) {
146962
+ try {
146963
+ process.kill(serverProcess.pid);
146964
+ } catch {
146965
+ }
146966
+ await rm3(pidFile, { force: true });
146967
+ throw new CleoError(1 /* GENERAL_ERROR */, "Server failed to start within 15 seconds");
146968
+ }
146969
+ cliOutput(
146970
+ {
146971
+ pid: serverProcess.pid,
146972
+ port,
146973
+ host,
146974
+ url: `http://${host}:${port}`,
146975
+ logFile
146976
+ },
146977
+ { command: "web", message: `CLEO Web UI running on port ${port}` }
146978
+ );
146979
+ }
145284
146980
  function registerWebCommand(program) {
145285
146981
  const webCmd = program.command("web").description("Manage CLEO Web UI server");
145286
146982
  webCmd.command("start").description("Start the web server").option("--port <port>", "Server port", String(DEFAULT_PORT)).option("--host <host>", "Server host", DEFAULT_HOST).action(async (opts) => {
145287
146983
  try {
145288
146984
  const port = parseInt(opts["port"], 10);
145289
146985
  const host = opts["host"];
145290
- const { pidFile, configFile, logFile, logDir } = getWebPaths();
145291
- const status = await getStatus();
145292
- if (status.running) {
145293
- throw new CleoError(
145294
- 1 /* GENERAL_ERROR */,
145295
- `Server already running (PID: ${status.pid})`
145296
- );
145297
- }
145298
- const projectRoot = process.env["CLEO_ROOT"] ?? process.cwd();
145299
- const studioDir = process.env["CLEO_STUDIO_DIR"] ?? join133(projectRoot, "packages", "studio", "build");
145300
- await mkdir19(logDir, { recursive: true });
145301
- await writeFile14(
145302
- configFile,
145303
- JSON.stringify({
145304
- port,
145305
- host,
145306
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
145307
- })
145308
- );
145309
- const webIndexPath = join133(studioDir, "index.js");
145310
- try {
145311
- await stat3(webIndexPath);
145312
- } catch {
145313
- try {
145314
- execFileSync18("pnpm", ["--filter", "@cleocode/studio", "run", "build"], {
145315
- cwd: projectRoot,
145316
- stdio: "ignore"
145317
- });
145318
- } catch {
145319
- throw new CleoError(
145320
- 1 /* GENERAL_ERROR */,
145321
- `Studio build failed. Run: pnpm --filter @cleocode/studio run build
145322
- Logs: ${logFile}`
145323
- );
145324
- }
145325
- }
145326
- const logFileHandle = await open(logFile, "a");
145327
- const serverProcess = spawn2("node", [webIndexPath], {
145328
- cwd: studioDir,
145329
- env: {
145330
- ...process.env,
145331
- HOST: host,
145332
- PORT: String(port),
145333
- // Pass CLEO paths through to the studio server
145334
- CLEO_ROOT: projectRoot
145335
- },
145336
- detached: true,
145337
- stdio: ["ignore", logFileHandle.fd, logFileHandle.fd]
145338
- });
145339
- serverProcess.unref();
145340
- const pidFileTmp = `${pidFile}.tmp`;
145341
- await writeFile14(pidFileTmp, String(serverProcess.pid));
145342
- await rm3(pidFile, { force: true });
145343
- await writeFile14(pidFile, String(serverProcess.pid));
145344
- await rm3(pidFileTmp, { force: true });
145345
- await logFileHandle.close();
145346
- const maxAttempts = 30;
145347
- let started = false;
145348
- for (let i = 0; i < maxAttempts; i++) {
145349
- try {
145350
- const response = await fetch(`http://${host}:${port}/api/health`);
145351
- if (response.ok) {
145352
- started = true;
145353
- break;
145354
- }
145355
- } catch {
145356
- }
145357
- await new Promise((resolve17) => setTimeout(resolve17, 500));
145358
- }
145359
- if (!started) {
145360
- try {
145361
- process.kill(serverProcess.pid);
145362
- } catch {
145363
- }
145364
- await rm3(pidFile, { force: true });
145365
- throw new CleoError(1 /* GENERAL_ERROR */, "Server failed to start within 15 seconds");
145366
- }
145367
- cliOutput(
145368
- {
145369
- pid: serverProcess.pid,
145370
- port,
145371
- host,
145372
- url: `http://${host}:${port}`,
145373
- logFile
145374
- },
145375
- { command: "web", message: `CLEO Web UI running on port ${port}` }
145376
- );
146986
+ await startWebServer(port, host);
145377
146987
  } catch (err) {
145378
146988
  if (err instanceof CleoError) {
145379
146989
  console.error(formatError3(err));
@@ -145452,16 +147062,9 @@ Logs: ${logFile}`
145452
147062
  }
145453
147063
  await rm3(pidFile, { force: true });
145454
147064
  }
145455
- const port = opts["port"] ?? String(DEFAULT_PORT);
147065
+ const port = parseInt(opts["port"] ?? String(DEFAULT_PORT), 10);
145456
147066
  const host = opts["host"] ?? DEFAULT_HOST;
145457
- const startOpts = { port, host };
145458
- const startCmd = webCmd.commands.find((c) => c.name() === "start");
145459
- const startAction = startCmd?.action;
145460
- if (startAction) {
145461
- await startAction(startOpts);
145462
- } else {
145463
- throw new CleoError(1 /* GENERAL_ERROR */, "Could not restart server");
145464
- }
147067
+ await startWebServer(port, host);
145465
147068
  } catch (err) {
145466
147069
  if (err instanceof CleoError) {
145467
147070
  console.error(formatError3(err));
@@ -145535,9 +147138,9 @@ var codeCommand = defineCommand({
145535
147138
  async run({ args }) {
145536
147139
  await requireTreeSitter();
145537
147140
  const { smartOutline: smartOutline2 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
145538
- const { join: join135 } = await import("node:path");
147141
+ const { join: join136 } = await import("node:path");
145539
147142
  const root = process.cwd();
145540
- const absPath = args.file.startsWith("/") ? args.file : join135(root, args.file);
147143
+ const absPath = args.file.startsWith("/") ? args.file : join136(root, args.file);
145541
147144
  const result = smartOutline2(absPath, root);
145542
147145
  if (result.errors.length > 0 && result.symbols.length === 0) {
145543
147146
  console.error(`Error: ${result.errors.join(", ")}`);
@@ -145603,9 +147206,9 @@ var codeCommand = defineCommand({
145603
147206
  async run({ args }) {
145604
147207
  await requireTreeSitter();
145605
147208
  const { smartUnfold: smartUnfold2 } = await Promise.resolve().then(() => (init_internal(), internal_exports));
145606
- const { join: join135 } = await import("node:path");
147209
+ const { join: join136 } = await import("node:path");
145607
147210
  const root = process.cwd();
145608
- const absPath = args.file.startsWith("/") ? args.file : join135(root, args.file);
147211
+ const absPath = args.file.startsWith("/") ? args.file : join136(root, args.file);
145609
147212
  const result = smartUnfold2(absPath, args.symbol, root);
145610
147213
  if (!result.found) {
145611
147214
  console.error(`Symbol "${args.symbol}" not found in ${args.file}`);
@@ -145624,8 +147227,8 @@ var codeCommand = defineCommand({
145624
147227
 
145625
147228
  // packages/cleo/src/cli/index.ts
145626
147229
  function getPackageVersion() {
145627
- const pkgPath = join134(dirname31(fileURLToPath8(import.meta.url)), "../../package.json");
145628
- const pkg = JSON.parse(readFileSync106(pkgPath, "utf-8"));
147230
+ const pkgPath = join135(dirname31(fileURLToPath8(import.meta.url)), "../../package.json");
147231
+ const pkg = JSON.parse(readFileSync107(pkgPath, "utf-8"));
145629
147232
  return pkg.version;
145630
147233
  }
145631
147234
  var CLI_VERSION = getPackageVersion();