cognitive-core 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (528) hide show
  1. package/.claude/settings.json +111 -2
  2. package/.sessionlog/settings.json +4 -0
  3. package/CLAUDE.md +233 -0
  4. package/README.md +370 -54
  5. package/dist/atlas.d.ts +10 -10
  6. package/dist/atlas.d.ts.map +1 -1
  7. package/dist/atlas.js +79 -48
  8. package/dist/atlas.js.map +1 -1
  9. package/dist/bin/cli-utils.d.ts +37 -0
  10. package/dist/bin/cli-utils.d.ts.map +1 -0
  11. package/dist/bin/cli-utils.js +176 -0
  12. package/dist/bin/cli-utils.js.map +1 -0
  13. package/dist/bin/cognitive-core.d.ts +2 -12
  14. package/dist/bin/cognitive-core.d.ts.map +1 -1
  15. package/dist/bin/cognitive-core.js +76 -351
  16. package/dist/bin/cognitive-core.js.map +1 -1
  17. package/dist/bin/commands/kb.d.ts +6 -0
  18. package/dist/bin/commands/kb.d.ts.map +1 -0
  19. package/dist/bin/commands/kb.js +240 -0
  20. package/dist/bin/commands/kb.js.map +1 -0
  21. package/dist/bin/commands/learn.d.ts +6 -0
  22. package/dist/bin/commands/learn.d.ts.map +1 -0
  23. package/dist/bin/commands/learn.js +91 -0
  24. package/dist/bin/commands/learn.js.map +1 -0
  25. package/dist/bin/commands/legacy.d.ts +12 -0
  26. package/dist/bin/commands/legacy.d.ts.map +1 -0
  27. package/dist/bin/commands/legacy.js +142 -0
  28. package/dist/bin/commands/legacy.js.map +1 -0
  29. package/dist/bin/commands/run.d.ts +3 -0
  30. package/dist/bin/commands/run.d.ts.map +1 -0
  31. package/dist/bin/commands/run.js +99 -0
  32. package/dist/bin/commands/run.js.map +1 -0
  33. package/dist/bin/commands/sessions.d.ts +9 -0
  34. package/dist/bin/commands/sessions.d.ts.map +1 -0
  35. package/dist/bin/commands/sessions.js +183 -0
  36. package/dist/bin/commands/sessions.js.map +1 -0
  37. package/dist/bin/commands/skills.d.ts +6 -0
  38. package/dist/bin/commands/skills.d.ts.map +1 -0
  39. package/dist/bin/commands/skills.js +135 -0
  40. package/dist/bin/commands/skills.js.map +1 -0
  41. package/dist/embeddings/index.d.ts +1 -0
  42. package/dist/embeddings/index.d.ts.map +1 -1
  43. package/dist/embeddings/index.js +2 -0
  44. package/dist/embeddings/index.js.map +1 -1
  45. package/dist/embeddings/inverted-index.d.ts +47 -0
  46. package/dist/embeddings/inverted-index.d.ts.map +1 -0
  47. package/dist/embeddings/inverted-index.js +122 -0
  48. package/dist/embeddings/inverted-index.js.map +1 -0
  49. package/dist/embeddings/manager.d.ts +3 -1
  50. package/dist/embeddings/manager.d.ts.map +1 -1
  51. package/dist/embeddings/manager.js +12 -7
  52. package/dist/embeddings/manager.js.map +1 -1
  53. package/dist/embeddings/vector-store.d.ts +7 -3
  54. package/dist/embeddings/vector-store.d.ts.map +1 -1
  55. package/dist/embeddings/vector-store.js +22 -6
  56. package/dist/embeddings/vector-store.js.map +1 -1
  57. package/dist/factory.d.ts +11 -12
  58. package/dist/factory.d.ts.map +1 -1
  59. package/dist/factory.js +20 -7
  60. package/dist/factory.js.map +1 -1
  61. package/dist/index.d.ts +8 -7
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +42 -6
  64. package/dist/index.js.map +1 -1
  65. package/dist/learning/analyzer.d.ts.map +1 -1
  66. package/dist/learning/analyzer.js +17 -35
  67. package/dist/learning/analyzer.js.map +1 -1
  68. package/dist/learning/energy-evaluator.d.ts +128 -0
  69. package/dist/learning/energy-evaluator.d.ts.map +1 -0
  70. package/dist/learning/energy-evaluator.js +175 -0
  71. package/dist/learning/energy-evaluator.js.map +1 -0
  72. package/dist/learning/healing-orchestrator.d.ts +182 -0
  73. package/dist/learning/healing-orchestrator.d.ts.map +1 -0
  74. package/dist/learning/healing-orchestrator.js +250 -0
  75. package/dist/learning/healing-orchestrator.js.map +1 -0
  76. package/dist/learning/index.d.ts +7 -2
  77. package/dist/learning/index.d.ts.map +1 -1
  78. package/dist/learning/index.js +13 -2
  79. package/dist/learning/index.js.map +1 -1
  80. package/dist/learning/instant-loop.d.ts +87 -0
  81. package/dist/learning/instant-loop.d.ts.map +1 -0
  82. package/dist/learning/instant-loop.js +264 -0
  83. package/dist/learning/instant-loop.js.map +1 -0
  84. package/dist/learning/loop-coordinator.d.ts +61 -0
  85. package/dist/learning/loop-coordinator.d.ts.map +1 -0
  86. package/dist/learning/loop-coordinator.js +96 -0
  87. package/dist/learning/loop-coordinator.js.map +1 -0
  88. package/dist/learning/maintenance-scheduler.d.ts +141 -0
  89. package/dist/learning/maintenance-scheduler.d.ts.map +1 -0
  90. package/dist/learning/maintenance-scheduler.js +186 -0
  91. package/dist/learning/maintenance-scheduler.js.map +1 -0
  92. package/dist/learning/meta-learner.d.ts.map +1 -1
  93. package/dist/learning/meta-learner.js +4 -21
  94. package/dist/learning/meta-learner.js.map +1 -1
  95. package/dist/learning/pipeline.d.ts +31 -4
  96. package/dist/learning/pipeline.d.ts.map +1 -1
  97. package/dist/learning/pipeline.js +64 -12
  98. package/dist/learning/pipeline.js.map +1 -1
  99. package/dist/learning/reflexion-generator.d.ts +64 -0
  100. package/dist/learning/reflexion-generator.d.ts.map +1 -0
  101. package/dist/learning/reflexion-generator.js +194 -0
  102. package/dist/learning/reflexion-generator.js.map +1 -0
  103. package/dist/learning/trajectory-sources/entire.d.ts +8 -5
  104. package/dist/learning/trajectory-sources/entire.d.ts.map +1 -1
  105. package/dist/learning/trajectory-sources/entire.js +13 -6
  106. package/dist/learning/trajectory-sources/entire.js.map +1 -1
  107. package/dist/learning/trajectory-sources/index.d.ts +1 -1
  108. package/dist/learning/trajectory-sources/index.d.ts.map +1 -1
  109. package/dist/learning/trajectory-sources/index.js +1 -1
  110. package/dist/learning/trajectory-sources/index.js.map +1 -1
  111. package/dist/learning/trajectory-sources/pipeline.d.ts +4 -4
  112. package/dist/learning/trajectory-sources/pipeline.d.ts.map +1 -1
  113. package/dist/learning/trajectory-sources/pipeline.js +2 -2
  114. package/dist/learning/trajectory-sources/pipeline.js.map +1 -1
  115. package/dist/learning/unified-pipeline.d.ts +311 -0
  116. package/dist/learning/unified-pipeline.d.ts.map +1 -0
  117. package/dist/learning/unified-pipeline.js +844 -0
  118. package/dist/learning/unified-pipeline.js.map +1 -0
  119. package/dist/memory/candidate-retrieval.d.ts +43 -0
  120. package/dist/memory/candidate-retrieval.d.ts.map +1 -0
  121. package/dist/memory/candidate-retrieval.js +43 -0
  122. package/dist/memory/candidate-retrieval.js.map +1 -0
  123. package/dist/memory/causal-store.d.ts +97 -0
  124. package/dist/memory/causal-store.d.ts.map +1 -0
  125. package/dist/memory/causal-store.js +209 -0
  126. package/dist/memory/causal-store.js.map +1 -0
  127. package/dist/memory/coherence.d.ts +71 -0
  128. package/dist/memory/coherence.d.ts.map +1 -0
  129. package/dist/memory/coherence.js +176 -0
  130. package/dist/memory/coherence.js.map +1 -0
  131. package/dist/memory/experience.d.ts +39 -6
  132. package/dist/memory/experience.d.ts.map +1 -1
  133. package/dist/memory/experience.js +193 -49
  134. package/dist/memory/experience.js.map +1 -1
  135. package/dist/memory/index.d.ts +7 -0
  136. package/dist/memory/index.d.ts.map +1 -1
  137. package/dist/memory/index.js +12 -0
  138. package/dist/memory/index.js.map +1 -1
  139. package/dist/memory/knowledge-bank.d.ts +14 -0
  140. package/dist/memory/knowledge-bank.d.ts.map +1 -1
  141. package/dist/memory/knowledge-bank.js +45 -0
  142. package/dist/memory/knowledge-bank.js.map +1 -1
  143. package/dist/memory/meta.d.ts +7 -8
  144. package/dist/memory/meta.d.ts.map +1 -1
  145. package/dist/memory/meta.js +73 -79
  146. package/dist/memory/meta.js.map +1 -1
  147. package/dist/memory/playbook.d.ts +26 -9
  148. package/dist/memory/playbook.d.ts.map +1 -1
  149. package/dist/memory/playbook.js +198 -74
  150. package/dist/memory/playbook.js.map +1 -1
  151. package/dist/memory/reasoning-bank.d.ts +130 -0
  152. package/dist/memory/reasoning-bank.d.ts.map +1 -0
  153. package/dist/memory/reasoning-bank.js +342 -0
  154. package/dist/memory/reasoning-bank.js.map +1 -0
  155. package/dist/memory/reflexion.d.ts +59 -0
  156. package/dist/memory/reflexion.d.ts.map +1 -0
  157. package/dist/memory/reflexion.js +96 -0
  158. package/dist/memory/reflexion.js.map +1 -0
  159. package/dist/memory/system.d.ts +7 -2
  160. package/dist/memory/system.d.ts.map +1 -1
  161. package/dist/memory/system.js +19 -7
  162. package/dist/memory/system.js.map +1 -1
  163. package/dist/memory/temporal-compressor.d.ts +126 -0
  164. package/dist/memory/temporal-compressor.d.ts.map +1 -0
  165. package/dist/memory/temporal-compressor.js +335 -0
  166. package/dist/memory/temporal-compressor.js.map +1 -0
  167. package/dist/persistence/index.d.ts +11 -0
  168. package/dist/persistence/index.d.ts.map +1 -0
  169. package/dist/persistence/index.js +11 -0
  170. package/dist/persistence/index.js.map +1 -0
  171. package/dist/persistence/migrator.d.ts +40 -0
  172. package/dist/persistence/migrator.d.ts.map +1 -0
  173. package/dist/persistence/migrator.js +238 -0
  174. package/dist/persistence/migrator.js.map +1 -0
  175. package/dist/persistence/serializers.d.ts +45 -0
  176. package/dist/persistence/serializers.d.ts.map +1 -0
  177. package/dist/persistence/serializers.js +80 -0
  178. package/dist/persistence/serializers.js.map +1 -0
  179. package/dist/persistence/sqlite-persistence.d.ts +228 -0
  180. package/dist/persistence/sqlite-persistence.d.ts.map +1 -0
  181. package/dist/persistence/sqlite-persistence.js +588 -0
  182. package/dist/persistence/sqlite-persistence.js.map +1 -0
  183. package/dist/runtime/flows/learning.d.ts +10 -12
  184. package/dist/runtime/flows/learning.d.ts.map +1 -1
  185. package/dist/runtime/flows/learning.js +10 -23
  186. package/dist/runtime/flows/learning.js.map +1 -1
  187. package/dist/search/index.d.ts +1 -0
  188. package/dist/search/index.d.ts.map +1 -1
  189. package/dist/search/index.js +2 -0
  190. package/dist/search/index.js.map +1 -1
  191. package/dist/search/moe-gate.d.ts +124 -0
  192. package/dist/search/moe-gate.d.ts.map +1 -0
  193. package/dist/search/moe-gate.js +234 -0
  194. package/dist/search/moe-gate.js.map +1 -0
  195. package/dist/search/router.d.ts +32 -2
  196. package/dist/search/router.d.ts.map +1 -1
  197. package/dist/search/router.js +87 -4
  198. package/dist/search/router.js.map +1 -1
  199. package/dist/session-bank/git-reader.d.ts +9 -4
  200. package/dist/session-bank/git-reader.d.ts.map +1 -1
  201. package/dist/session-bank/git-reader.js +22 -15
  202. package/dist/session-bank/git-reader.js.map +1 -1
  203. package/dist/session-bank/index.d.ts +2 -2
  204. package/dist/session-bank/index.d.ts.map +1 -1
  205. package/dist/session-bank/index.js +2 -2
  206. package/dist/session-bank/index.js.map +1 -1
  207. package/dist/session-bank/parser.d.ts +16 -5
  208. package/dist/session-bank/parser.d.ts.map +1 -1
  209. package/dist/session-bank/parser.js +187 -80
  210. package/dist/session-bank/parser.js.map +1 -1
  211. package/dist/session-bank/session-bank.d.ts +5 -0
  212. package/dist/session-bank/session-bank.d.ts.map +1 -1
  213. package/dist/session-bank/session-bank.js +30 -9
  214. package/dist/session-bank/session-bank.js.map +1 -1
  215. package/dist/session-bank/types.d.ts +4 -1
  216. package/dist/session-bank/types.d.ts.map +1 -1
  217. package/dist/session-bank/types.js +3 -3
  218. package/dist/session-bank/types.js.map +1 -1
  219. package/dist/surfacing/skill-publisher.d.ts.map +1 -1
  220. package/dist/surfacing/skill-publisher.js +15 -43
  221. package/dist/surfacing/skill-publisher.js.map +1 -1
  222. package/dist/surfacing/sqlite-storage-adapter.d.ts.map +1 -1
  223. package/dist/surfacing/sqlite-storage-adapter.js +13 -21
  224. package/dist/surfacing/sqlite-storage-adapter.js.map +1 -1
  225. package/dist/types/config.d.ts +100 -0
  226. package/dist/types/config.d.ts.map +1 -1
  227. package/dist/types/config.js +27 -0
  228. package/dist/types/config.js.map +1 -1
  229. package/dist/types/index.d.ts +2 -2
  230. package/dist/types/index.d.ts.map +1 -1
  231. package/dist/types/index.js +1 -1
  232. package/dist/types/index.js.map +1 -1
  233. package/dist/types/memory.d.ts +52 -0
  234. package/dist/types/memory.d.ts.map +1 -1
  235. package/dist/types/memory.js +13 -0
  236. package/dist/types/memory.js.map +1 -1
  237. package/dist/types/playbook.d.ts +4 -0
  238. package/dist/types/playbook.d.ts.map +1 -1
  239. package/dist/types/playbook.js.map +1 -1
  240. package/dist/utils/error-classifier.d.ts +30 -0
  241. package/dist/utils/error-classifier.d.ts.map +1 -0
  242. package/dist/utils/error-classifier.js +85 -0
  243. package/dist/utils/error-classifier.js.map +1 -0
  244. package/dist/utils/index.d.ts +3 -0
  245. package/dist/utils/index.d.ts.map +1 -1
  246. package/dist/utils/index.js +3 -0
  247. package/dist/utils/index.js.map +1 -1
  248. package/dist/utils/partitioned-store.d.ts +93 -0
  249. package/dist/utils/partitioned-store.d.ts.map +1 -0
  250. package/dist/utils/partitioned-store.js +251 -0
  251. package/dist/utils/partitioned-store.js.map +1 -0
  252. package/dist/utils/trajectory-helpers.d.ts +39 -0
  253. package/dist/utils/trajectory-helpers.d.ts.map +1 -0
  254. package/dist/utils/trajectory-helpers.js +57 -0
  255. package/dist/utils/trajectory-helpers.js.map +1 -0
  256. package/dist/workspace/efficacy-toolkit.d.ts +164 -0
  257. package/dist/workspace/efficacy-toolkit.d.ts.map +1 -0
  258. package/dist/workspace/efficacy-toolkit.js +281 -0
  259. package/dist/workspace/efficacy-toolkit.js.map +1 -0
  260. package/dist/workspace/index.d.ts +2 -1
  261. package/dist/workspace/index.d.ts.map +1 -1
  262. package/dist/workspace/index.js +3 -1
  263. package/dist/workspace/index.js.map +1 -1
  264. package/dist/workspace/runner.d.ts +3 -4
  265. package/dist/workspace/runner.d.ts.map +1 -1
  266. package/dist/workspace/runner.js.map +1 -1
  267. package/dist/workspace/templates/index.d.ts +3 -0
  268. package/dist/workspace/templates/index.d.ts.map +1 -1
  269. package/dist/workspace/templates/index.js +6 -0
  270. package/dist/workspace/templates/index.js.map +1 -1
  271. package/dist/workspace/templates/playbook-decay-detection.d.ts +46 -0
  272. package/dist/workspace/templates/playbook-decay-detection.d.ts.map +1 -0
  273. package/dist/workspace/templates/playbook-decay-detection.js +197 -0
  274. package/dist/workspace/templates/playbook-decay-detection.js.map +1 -0
  275. package/dist/workspace/templates/playbook-efficacy-audit.d.ts +46 -0
  276. package/dist/workspace/templates/playbook-efficacy-audit.d.ts.map +1 -0
  277. package/dist/workspace/templates/playbook-efficacy-audit.js +160 -0
  278. package/dist/workspace/templates/playbook-efficacy-audit.js.map +1 -0
  279. package/dist/workspace/templates/playbook-lifecycle-review.d.ts +51 -0
  280. package/dist/workspace/templates/playbook-lifecycle-review.d.ts.map +1 -0
  281. package/dist/workspace/templates/playbook-lifecycle-review.js +187 -0
  282. package/dist/workspace/templates/playbook-lifecycle-review.js.map +1 -0
  283. package/dist/workspace/types.d.ts +9 -2
  284. package/dist/workspace/types.d.ts.map +1 -1
  285. package/dist/workspace/types.js.map +1 -1
  286. package/package.json +12 -4
  287. package/references/sessionlog/.husky/pre-commit +1 -0
  288. package/references/sessionlog/.lintstagedrc.json +4 -0
  289. package/references/sessionlog/.prettierignore +4 -0
  290. package/references/sessionlog/.prettierrc.json +11 -0
  291. package/references/sessionlog/LICENSE +21 -0
  292. package/references/sessionlog/README.md +453 -0
  293. package/references/sessionlog/eslint.config.js +58 -0
  294. package/references/sessionlog/package-lock.json +3672 -0
  295. package/references/sessionlog/package.json +65 -0
  296. package/references/sessionlog/src/__tests__/agent-hooks.test.ts +570 -0
  297. package/references/sessionlog/src/__tests__/agent-registry.test.ts +127 -0
  298. package/references/sessionlog/src/__tests__/claude-code-hooks.test.ts +225 -0
  299. package/references/sessionlog/src/__tests__/claude-generator.test.ts +46 -0
  300. package/references/sessionlog/src/__tests__/commit-msg.test.ts +86 -0
  301. package/references/sessionlog/src/__tests__/cursor-agent.test.ts +224 -0
  302. package/references/sessionlog/src/__tests__/e2e-live.test.ts +890 -0
  303. package/references/sessionlog/src/__tests__/event-log.test.ts +183 -0
  304. package/references/sessionlog/src/__tests__/flush-sentinel.test.ts +105 -0
  305. package/references/sessionlog/src/__tests__/gemini-agent.test.ts +375 -0
  306. package/references/sessionlog/src/__tests__/git-hooks.test.ts +78 -0
  307. package/references/sessionlog/src/__tests__/hook-managers.test.ts +121 -0
  308. package/references/sessionlog/src/__tests__/lifecycle-tasks.test.ts +759 -0
  309. package/references/sessionlog/src/__tests__/opencode-agent.test.ts +338 -0
  310. package/references/sessionlog/src/__tests__/redaction.test.ts +136 -0
  311. package/references/sessionlog/src/__tests__/session-repo.test.ts +353 -0
  312. package/references/sessionlog/src/__tests__/session-store.test.ts +166 -0
  313. package/references/sessionlog/src/__tests__/setup-ccweb.test.ts +466 -0
  314. package/references/sessionlog/src/__tests__/skill-live.test.ts +461 -0
  315. package/references/sessionlog/src/__tests__/summarize.test.ts +348 -0
  316. package/references/sessionlog/src/__tests__/task-plan-e2e.test.ts +610 -0
  317. package/references/sessionlog/src/__tests__/task-plan-live.test.ts +632 -0
  318. package/references/sessionlog/src/__tests__/transcript-timestamp.test.ts +121 -0
  319. package/references/sessionlog/src/__tests__/types.test.ts +166 -0
  320. package/references/sessionlog/src/__tests__/utils.test.ts +333 -0
  321. package/references/sessionlog/src/__tests__/validation.test.ts +103 -0
  322. package/references/sessionlog/src/__tests__/worktree.test.ts +57 -0
  323. package/references/sessionlog/src/agent/agents/claude-code.ts +1089 -0
  324. package/references/sessionlog/src/agent/agents/cursor.ts +361 -0
  325. package/references/sessionlog/src/agent/agents/gemini-cli.ts +632 -0
  326. package/references/sessionlog/src/agent/agents/opencode.ts +540 -0
  327. package/references/sessionlog/src/agent/registry.ts +143 -0
  328. package/references/sessionlog/src/agent/session-types.ts +113 -0
  329. package/references/sessionlog/src/agent/types.ts +220 -0
  330. package/references/sessionlog/src/cli.ts +597 -0
  331. package/references/sessionlog/src/commands/clean.ts +133 -0
  332. package/references/sessionlog/src/commands/disable.ts +84 -0
  333. package/references/sessionlog/src/commands/doctor.ts +145 -0
  334. package/references/sessionlog/src/commands/enable.ts +202 -0
  335. package/references/sessionlog/src/commands/explain.ts +261 -0
  336. package/references/sessionlog/src/commands/reset.ts +105 -0
  337. package/references/sessionlog/src/commands/resume.ts +180 -0
  338. package/references/sessionlog/src/commands/rewind.ts +195 -0
  339. package/references/sessionlog/src/commands/setup-ccweb.ts +275 -0
  340. package/references/sessionlog/src/commands/status.ts +172 -0
  341. package/references/sessionlog/src/config.ts +165 -0
  342. package/references/sessionlog/src/events/event-log.ts +126 -0
  343. package/references/sessionlog/src/git-operations.ts +558 -0
  344. package/references/sessionlog/src/hooks/git-hooks.ts +165 -0
  345. package/references/sessionlog/src/hooks/lifecycle.ts +391 -0
  346. package/references/sessionlog/src/index.ts +650 -0
  347. package/references/sessionlog/src/security/redaction.ts +283 -0
  348. package/references/sessionlog/src/session/state-machine.ts +452 -0
  349. package/references/sessionlog/src/store/checkpoint-store.ts +509 -0
  350. package/references/sessionlog/src/store/native-store.ts +173 -0
  351. package/references/sessionlog/src/store/provider-types.ts +99 -0
  352. package/references/sessionlog/src/store/session-store.ts +266 -0
  353. package/references/sessionlog/src/strategy/attribution.ts +296 -0
  354. package/references/sessionlog/src/strategy/common.ts +207 -0
  355. package/references/sessionlog/src/strategy/content-overlap.ts +228 -0
  356. package/references/sessionlog/src/strategy/manual-commit.ts +988 -0
  357. package/references/sessionlog/src/strategy/types.ts +279 -0
  358. package/references/sessionlog/src/summarize/claude-generator.ts +115 -0
  359. package/references/sessionlog/src/summarize/summarize.ts +432 -0
  360. package/references/sessionlog/src/types.ts +508 -0
  361. package/references/sessionlog/src/utils/chunk-files.ts +49 -0
  362. package/references/sessionlog/src/utils/commit-message.ts +65 -0
  363. package/references/sessionlog/src/utils/detect-agent.ts +36 -0
  364. package/references/sessionlog/src/utils/hook-managers.ts +125 -0
  365. package/references/sessionlog/src/utils/ide-tags.ts +32 -0
  366. package/references/sessionlog/src/utils/paths.ts +79 -0
  367. package/references/sessionlog/src/utils/preview-rewind.ts +80 -0
  368. package/references/sessionlog/src/utils/rewind-conflict.ts +121 -0
  369. package/references/sessionlog/src/utils/shadow-branch.ts +109 -0
  370. package/references/sessionlog/src/utils/string-utils.ts +46 -0
  371. package/references/sessionlog/src/utils/todo-extract.ts +188 -0
  372. package/references/sessionlog/src/utils/trailers.ts +187 -0
  373. package/references/sessionlog/src/utils/transcript-parse.ts +177 -0
  374. package/references/sessionlog/src/utils/transcript-timestamp.ts +59 -0
  375. package/references/sessionlog/src/utils/tree-ops.ts +219 -0
  376. package/references/sessionlog/src/utils/tty.ts +72 -0
  377. package/references/sessionlog/src/utils/validation.ts +65 -0
  378. package/references/sessionlog/src/utils/worktree.ts +58 -0
  379. package/references/sessionlog/src/wire-types.ts +59 -0
  380. package/references/sessionlog/templates/setup-env.sh +153 -0
  381. package/references/sessionlog/tsconfig.json +18 -0
  382. package/references/sessionlog/vitest.config.ts +12 -0
  383. package/references/skill-tree/.sudocode/issues.jsonl +8 -0
  384. package/references/skill-tree/.sudocode/specs.jsonl +2 -0
  385. package/references/skill-tree/CLAUDE.md +56 -80
  386. package/references/skill-tree/README.md +188 -140
  387. package/references/skill-tree/examples/basic-usage.ts +95 -121
  388. package/references/skill-tree/package-lock.json +369 -26
  389. package/references/skill-tree/package.json +1 -1
  390. package/src/atlas.ts +97 -67
  391. package/src/bin/cli-utils.ts +220 -0
  392. package/src/bin/cognitive-core.ts +84 -392
  393. package/src/bin/commands/kb.ts +266 -0
  394. package/src/bin/commands/learn.ts +100 -0
  395. package/src/bin/commands/legacy.ts +182 -0
  396. package/src/bin/commands/run.ts +113 -0
  397. package/src/bin/commands/sessions.ts +221 -0
  398. package/src/bin/commands/skills.ts +146 -0
  399. package/src/embeddings/index.ts +3 -0
  400. package/src/embeddings/inverted-index.ts +134 -0
  401. package/src/embeddings/manager.ts +13 -8
  402. package/src/embeddings/vector-store.ts +21 -9
  403. package/src/factory.ts +33 -16
  404. package/src/index.ts +136 -9
  405. package/src/learning/analyzer.ts +21 -37
  406. package/src/learning/energy-evaluator.ts +282 -0
  407. package/src/learning/healing-orchestrator.ts +383 -0
  408. package/src/learning/index.ts +66 -9
  409. package/src/learning/instant-loop.ts +357 -0
  410. package/src/learning/maintenance-scheduler.ts +271 -0
  411. package/src/learning/meta-learner.ts +5 -23
  412. package/src/learning/reflexion-generator.ts +273 -0
  413. package/src/learning/trajectory-sources/entire.ts +24 -13
  414. package/src/learning/trajectory-sources/index.ts +2 -2
  415. package/src/learning/trajectory-sources/pipeline.ts +5 -5
  416. package/src/learning/unified-pipeline.ts +1191 -0
  417. package/src/memory/candidate-retrieval.ts +72 -0
  418. package/src/memory/causal-store.ts +273 -0
  419. package/src/memory/coherence.ts +252 -0
  420. package/src/memory/experience.ts +217 -50
  421. package/src/memory/index.ts +43 -0
  422. package/src/memory/knowledge-bank.ts +57 -0
  423. package/src/memory/meta.ts +78 -96
  424. package/src/memory/playbook.ts +239 -75
  425. package/src/memory/reasoning-bank.ts +458 -0
  426. package/src/memory/reflexion.ts +122 -0
  427. package/src/memory/system.ts +21 -5
  428. package/src/memory/temporal-compressor.ts +409 -0
  429. package/src/persistence/index.ts +37 -0
  430. package/src/persistence/migrator.ts +298 -0
  431. package/src/persistence/serializers.ts +79 -0
  432. package/src/persistence/sqlite-persistence.ts +925 -0
  433. package/src/runtime/flows/learning.ts +25 -42
  434. package/src/search/index.ts +10 -0
  435. package/src/search/moe-gate.ts +304 -0
  436. package/src/search/router.ts +111 -4
  437. package/src/session-bank/git-reader.ts +29 -19
  438. package/src/session-bank/index.ts +4 -2
  439. package/src/session-bank/parser.ts +280 -98
  440. package/src/session-bank/session-bank.ts +33 -12
  441. package/src/session-bank/types.ts +8 -5
  442. package/src/surfacing/skill-publisher.ts +17 -49
  443. package/src/surfacing/sqlite-storage-adapter.ts +16 -32
  444. package/src/types/config.ts +30 -0
  445. package/src/types/index.ts +3 -0
  446. package/src/types/memory.ts +30 -0
  447. package/src/types/playbook.ts +4 -0
  448. package/src/utils/error-classifier.ts +113 -0
  449. package/src/utils/index.ts +18 -0
  450. package/src/utils/partitioned-store.ts +299 -0
  451. package/src/utils/trajectory-helpers.ts +79 -0
  452. package/src/workspace/efficacy-toolkit.ts +496 -0
  453. package/src/workspace/index.ts +29 -0
  454. package/src/workspace/runner.ts +3 -3
  455. package/src/workspace/templates/index.ts +24 -0
  456. package/src/workspace/templates/playbook-decay-detection.ts +272 -0
  457. package/src/workspace/templates/playbook-efficacy-audit.ts +246 -0
  458. package/src/workspace/templates/playbook-lifecycle-review.ts +274 -0
  459. package/src/workspace/types.ts +10 -2
  460. package/tests/embeddings/inverted-index.test.ts +138 -0
  461. package/tests/feature-toggles.test.ts +275 -0
  462. package/tests/fixtures/behavioral-trajectories.ts +210 -0
  463. package/tests/gap-fixes.test.ts +17 -4
  464. package/tests/integration/cli-e2e.test.ts +621 -0
  465. package/tests/integration/e2e.test.ts +6 -5
  466. package/tests/integration/entire-e2e.test.ts +314 -125
  467. package/tests/integration/persistence-e2e.test.ts +741 -0
  468. package/tests/integration/phase-e2e.test.ts +1143 -0
  469. package/tests/integration/pipeline-data-correctness.test.ts +794 -0
  470. package/tests/integration/session-bank.test.ts +20 -14
  471. package/tests/integration/sessionlog-e2e.test.ts +329 -0
  472. package/tests/integration/unified-pipeline-e2e.test.ts +634 -0
  473. package/tests/learning/analyzer.test.ts +1 -1
  474. package/tests/learning/energy-evaluator.test.ts +180 -0
  475. package/tests/learning/entire-trajectory-source.test.ts +25 -25
  476. package/tests/learning/healing-orchestrator.test.ts +269 -0
  477. package/tests/learning/instant-loop.test.ts +243 -0
  478. package/tests/learning/maintenance-scheduler.test.ts +191 -0
  479. package/tests/learning/meta-learner.test.ts +418 -0
  480. package/tests/learning/pipeline-memory-updates.test.ts +721 -0
  481. package/tests/learning/reflexion-generator.test.ts +411 -0
  482. package/tests/learning/trajectory-sources.test.ts +12 -4
  483. package/tests/learning/unified-pipeline-efficacy.test.ts +232 -0
  484. package/tests/learning/unified-pipeline.test.ts +322 -0
  485. package/tests/mcp/playbook-server.test.ts +6 -1
  486. package/tests/memory/candidate-retrieval.test.ts +167 -0
  487. package/tests/memory/causal-store.test.ts +276 -0
  488. package/tests/memory/coherence.test.ts +232 -0
  489. package/tests/memory/experience.test.ts +8 -3
  490. package/tests/memory/meta.test.ts +399 -0
  491. package/tests/memory/playbook.test.ts +307 -1
  492. package/tests/memory/provenance.test.ts +11 -2
  493. package/tests/memory/reasoning-bank.test.ts +239 -0
  494. package/tests/memory/reflexion.test.ts +166 -0
  495. package/tests/memory/skill-exporter.test.ts +6 -1
  496. package/tests/memory/system.test.ts +6 -1
  497. package/tests/memory/temporal-compressor.test.ts +318 -0
  498. package/tests/persistence/migrator.test.ts +1009 -0
  499. package/tests/persistence/sqlite-persistence.test.ts +635 -0
  500. package/tests/runtime/agent-manager.test.ts +6 -1
  501. package/tests/runtime/delegate.test.ts +6 -1
  502. package/tests/search/evaluator.test.ts +257 -0
  503. package/tests/search/moe-gate.test.ts +250 -0
  504. package/tests/search/refinement-loop.test.ts +11 -2
  505. package/tests/search/router.test.ts +81 -2
  506. package/tests/search/verification-runner.test.ts +357 -0
  507. package/tests/session-bank/fixtures/sessionlog-root-metadata.json +16 -0
  508. package/tests/session-bank/fixtures/sessionlog-session/full.jsonl +6 -0
  509. package/tests/session-bank/fixtures/sessionlog-session/metadata.json +55 -0
  510. package/tests/session-bank/git-reader.test.ts +13 -13
  511. package/tests/session-bank/parser.test.ts +135 -3
  512. package/tests/session-bank/session-bank.test.ts +1 -1
  513. package/tests/surfacing/skill-library.test.ts +6 -1
  514. package/tests/surfacing/skill-publisher.test.ts +24 -58
  515. package/tests/surfacing/sqlite-storage-adapter.test.ts +11 -23
  516. package/tests/utils/error-classifier.test.ts +149 -0
  517. package/tests/utils/partitioned-store.test.ts +230 -0
  518. package/tests/utils/trajectory-helpers.test.ts +163 -0
  519. package/tests/workspace/efficacy-toolkit.test.ts +404 -0
  520. package/tests/workspace/full-flow.test.ts +10 -4
  521. package/tests/workspace/runner.test.ts +10 -4
  522. package/tests/workspace/templates/playbook-efficacy.test.ts +377 -0
  523. package/docs/DESIGN-workspace-migration.md +0 -1079
  524. package/docs/PLAN-agentic-workspace-implementation.md +0 -717
  525. package/docs/PLAN-graph-migration.md +0 -299
  526. package/docs/PLAN-session-bank-implementation.md +0 -474
  527. package/src/learning/pipeline.ts +0 -323
  528. package/tests/learning/pipeline.test.ts +0 -176
@@ -0,0 +1,844 @@
1
+ /**
2
+ * UnifiedLearningPipeline — Three-speed learning orchestrator.
3
+ *
4
+ * Consolidates InstantLoop, LearningPipeline (batch), LoopCoordinator,
5
+ * MetaLearner, EffectivenessTracker, and KnowledgeExtractor into a single
6
+ * owner that manages the full learning lifecycle.
7
+ *
8
+ * Three processing speeds (inspired by ruvector SONA):
9
+ *
10
+ * 1. **Immediate** (InstantLoop, <200ms): Fires on every trajectory.
11
+ * Stores experience, bumps playbooks, extracts lightweight knowledge,
12
+ * causal edges, and reflexion episodes.
13
+ *
14
+ * 2. **Batch** (cold pipeline): Triggered by energy-threshold evaluation
15
+ * (not just count). Runs full analysis, playbook extraction, temporal
16
+ * compression, and experience clustering.
17
+ *
18
+ * 3. **Maintenance** (circadian-gated): Runs periodically or after N batches.
19
+ * Knowledge defrag, healing orchestrator, meta-strategy generation,
20
+ * effectiveness reporting.
21
+ *
22
+ * The pipeline owns all components and coordinates them. Atlas delegates
23
+ * learning to this pipeline rather than managing components directly.
24
+ */
25
+ // Immediate-phase components
26
+ import { InstantLoop } from './instant-loop.js';
27
+ // Batch-phase components
28
+ import { createAnalyzer, } from './analyzer.js';
29
+ import { createPlaybookExtractor, } from './playbook-extractor.js';
30
+ import { KnowledgeExtractor } from './knowledge-extractor.js';
31
+ import { TemporalCompressor } from '../memory/temporal-compressor.js';
32
+ import { ReasoningBank } from '../memory/reasoning-bank.js';
33
+ import { trajectoryAnalysisTemplate } from '../workspace/templates/trajectory-analysis.js';
34
+ import { playbookExtractionTemplate } from '../workspace/templates/playbook-extraction.js';
35
+ // Efficacy templates (used in maintenance tasks)
36
+ import { playbookDecayDetectionTemplate } from '../workspace/templates/playbook-decay-detection.js';
37
+ import { playbookEfficacyAuditTemplate } from '../workspace/templates/playbook-efficacy-audit.js';
38
+ import { playbookLifecycleReviewTemplate } from '../workspace/templates/playbook-lifecycle-review.js';
39
+ // Energy evaluator (batch trigger)
40
+ import { EnergyEvaluator, } from './energy-evaluator.js';
41
+ // Maintenance scheduler
42
+ import { MaintenanceScheduler, } from './maintenance-scheduler.js';
43
+ // Healing orchestrator
44
+ import { HealingOrchestrator, PlaybookDriftDetector, MemoryBloatDetector, } from './healing-orchestrator.js';
45
+ const DEFAULT_EFFICACY_CONFIG = {
46
+ lifecycleReviewFrequency: 3,
47
+ minPlaybooks: 1,
48
+ minAnnotations: 3,
49
+ };
50
+ const DEFAULT_UNIFIED_CONFIG = {
51
+ instant: {},
52
+ batch: {
53
+ learning: {},
54
+ energy: {},
55
+ },
56
+ maintenance: {},
57
+ metaLearner: {},
58
+ features: {},
59
+ efficacy: DEFAULT_EFFICACY_CONFIG,
60
+ maxInstantLatencyMs: 200,
61
+ };
62
+ // =========================================================================
63
+ // Unified Pipeline
64
+ // =========================================================================
65
+ /**
66
+ * UnifiedLearningPipeline — owns all learning components and orchestrates
67
+ * the three-speed processing loop.
68
+ */
69
+ export class UnifiedLearningPipeline {
70
+ // Configuration
71
+ config;
72
+ learningConfig;
73
+ // Immediate-phase components
74
+ instantLoop;
75
+ // Batch-phase components
76
+ analyzer;
77
+ playbookExtractor;
78
+ knowledgeExtractor;
79
+ temporalCompressor;
80
+ reasoningBank;
81
+ // Meta-learning and effectiveness
82
+ metaLearner = null;
83
+ effectivenessTracker = null;
84
+ // Orchestration
85
+ energyEvaluator;
86
+ maintenanceScheduler;
87
+ healingOrchestrator;
88
+ // State
89
+ memory;
90
+ taskRunner = null;
91
+ accumulated = [];
92
+ accumulatedAnalyses = [];
93
+ totalProcessed = 0;
94
+ batchCyclesRun = 0;
95
+ maintenanceCyclesRun = 0;
96
+ _onLatencyWarning = null;
97
+ lastDecayResult = null;
98
+ constructor(memory, config, persistence) {
99
+ this.config = {
100
+ ...DEFAULT_UNIFIED_CONFIG,
101
+ ...config,
102
+ instant: { ...DEFAULT_UNIFIED_CONFIG.instant, ...config?.instant },
103
+ batch: {
104
+ learning: { ...DEFAULT_UNIFIED_CONFIG.batch.learning, ...config?.batch?.learning },
105
+ energy: { ...DEFAULT_UNIFIED_CONFIG.batch.energy, ...config?.batch?.energy },
106
+ },
107
+ maintenance: { ...DEFAULT_UNIFIED_CONFIG.maintenance, ...config?.maintenance },
108
+ metaLearner: { ...DEFAULT_UNIFIED_CONFIG.metaLearner, ...config?.metaLearner },
109
+ features: { ...DEFAULT_UNIFIED_CONFIG.features, ...config?.features },
110
+ efficacy: { ...DEFAULT_EFFICACY_CONFIG, ...config?.efficacy },
111
+ };
112
+ this.memory = memory;
113
+ // Resolve learning config with defaults
114
+ const lc = this.config.batch.learning;
115
+ this.learningConfig = {
116
+ creditStrategy: lc.creditStrategy ?? 'simple',
117
+ patternExtractor: lc.patternExtractor ?? 'llm',
118
+ minTrajectories: lc.minTrajectories ?? 10,
119
+ minHoursSinceLast: lc.minHoursSinceLast,
120
+ minSuccessRate: lc.minSuccessRate,
121
+ deduplicationThreshold: lc.deduplicationThreshold ?? 0.9,
122
+ maxExperiences: lc.maxExperiences ?? 1000,
123
+ };
124
+ // Immediate phase
125
+ this.instantLoop = new InstantLoop(memory, {
126
+ ...this.config.instant,
127
+ enableReflexion: this.config.features.reflexion ?? true,
128
+ enableCausalExtraction: this.config.features.causalExtraction ?? true,
129
+ });
130
+ // Batch phase
131
+ this.analyzer = createAnalyzer(this.learningConfig.creditStrategy);
132
+ this.playbookExtractor = createPlaybookExtractor({
133
+ minTrajectories: this.learningConfig.minTrajectories,
134
+ mergeThreshold: this.learningConfig.deduplicationThreshold,
135
+ minSuccessRate: this.learningConfig.minSuccessRate ?? 0.6,
136
+ });
137
+ this.knowledgeExtractor = (this.config.features.knowledgeExtraction ?? true)
138
+ ? new KnowledgeExtractor()
139
+ : null;
140
+ this.temporalCompressor = (this.config.features.temporalCompression ?? true)
141
+ ? new TemporalCompressor(undefined, persistence)
142
+ : null;
143
+ this.reasoningBank = (this.config.features.reasoningBank ?? true)
144
+ ? new ReasoningBank(undefined, persistence)
145
+ : null;
146
+ // Orchestration
147
+ this.energyEvaluator = new EnergyEvaluator({
148
+ countThreshold: this.learningConfig.minTrajectories,
149
+ ...this.config.batch.energy,
150
+ });
151
+ this.maintenanceScheduler = new MaintenanceScheduler(this.config.maintenance);
152
+ this.healingOrchestrator = new HealingOrchestrator();
153
+ // Register built-in healing detectors if healing feature is enabled
154
+ if (this.config.features.healing ?? true) {
155
+ this.healingOrchestrator.addDetector(new PlaybookDriftDetector());
156
+ this.healingOrchestrator.addDetector(new MemoryBloatDetector(this.learningConfig.maxExperiences));
157
+ }
158
+ // Register built-in maintenance tasks
159
+ this.registerBuiltInMaintenanceTasks();
160
+ }
161
+ /**
162
+ * Load persisted state for internal components.
163
+ * Call after persistence is initialized.
164
+ */
165
+ loadPersistedState() {
166
+ this.temporalCompressor?.loadPersistedState();
167
+ this.reasoningBank?.loadPersistedState();
168
+ }
169
+ /**
170
+ * Initialize components that require async setup.
171
+ */
172
+ async init() {
173
+ // Seed known domains from existing playbooks for energy evaluator
174
+ const allPlaybooks = await this.memory.playbooks.getAll();
175
+ const domains = new Set();
176
+ for (const pb of allPlaybooks) {
177
+ for (const d of pb.applicability.domains) {
178
+ domains.add(d);
179
+ }
180
+ }
181
+ this.energyEvaluator.seedKnownDomains([...domains]);
182
+ // Initialize meta-learner if enabled and meta memory available
183
+ if ((this.config.features.metaLearning ?? true) && this.memory.meta) {
184
+ const { createMetaLearner: createML } = await import('./meta-learner.js');
185
+ this.metaLearner = createML(this.memory.meta, this.config.metaLearner);
186
+ }
187
+ // Initialize effectiveness tracker if enabled
188
+ if (this.config.features.effectivenessTracking ?? true) {
189
+ // Effectiveness tracker is available through memory system
190
+ this.effectivenessTracker = this.memory.effectiveness;
191
+ await this.effectivenessTracker.init();
192
+ }
193
+ }
194
+ /**
195
+ * Set the agentic task runner for workspace-based analysis.
196
+ */
197
+ setTaskRunner(runner) {
198
+ this.taskRunner = runner;
199
+ }
200
+ // =========================================================================
201
+ // IMMEDIATE PHASE
202
+ // =========================================================================
203
+ /**
204
+ * Process a single trajectory through the full pipeline.
205
+ *
206
+ * 1. Runs the instant loop (immediate phase)
207
+ * 2. Evaluates energy to decide on batch trigger
208
+ * 3. If batch triggered, runs batch + checks maintenance
209
+ *
210
+ * This is the primary entry point for trajectory processing.
211
+ */
212
+ async processTrajectory(trajectory, signals) {
213
+ // 1. Immediate phase — InstantLoop
214
+ const instantResult = await this.instantLoop.process(trajectory);
215
+ this.totalProcessed++;
216
+ // Warn if instant loop exceeded latency budget
217
+ if (instantResult.durationMs > this.config.maxInstantLatencyMs) {
218
+ this._onLatencyWarning?.(instantResult.durationMs);
219
+ }
220
+ // 2. Accumulate for batch
221
+ let analysis;
222
+ if (this.taskRunner) {
223
+ analysis = await this.analyzeWithTemplate(trajectory);
224
+ }
225
+ else {
226
+ analysis = await this.analyzer.analyze(trajectory);
227
+ }
228
+ this.accumulated.push(trajectory);
229
+ this.accumulatedAnalyses.push(analysis);
230
+ // 3. Energy evaluation
231
+ const energyEval = this.energyEvaluator.evaluate(trajectory, instantResult, signals);
232
+ const result = {
233
+ instantLoop: instantResult,
234
+ energyEval,
235
+ batchTriggered: false,
236
+ maintenanceTriggered: false,
237
+ };
238
+ // 4. Batch trigger
239
+ if (energyEval.shouldTriggerBatch) {
240
+ const batchResult = await this.runBatch(energyEval.reasons);
241
+ result.batchTriggered = true;
242
+ result.batchResult = batchResult;
243
+ // 5. Check maintenance after batch
244
+ this.maintenanceScheduler.onBatchComplete();
245
+ if (this.maintenanceScheduler.shouldRunMaintenance()) {
246
+ const maintenanceResult = await this.runMaintenance();
247
+ result.maintenanceTriggered = true;
248
+ result.maintenanceResult = maintenanceResult;
249
+ }
250
+ }
251
+ return result;
252
+ }
253
+ // =========================================================================
254
+ // BATCH PHASE
255
+ // =========================================================================
256
+ /**
257
+ * Run batch learning on accumulated trajectories.
258
+ * Can be called manually or triggered by energy evaluation.
259
+ */
260
+ async runBatch(triggerReasons) {
261
+ if (this.accumulated.length === 0) {
262
+ return this.emptyBatchResult(triggerReasons ?? []);
263
+ }
264
+ this.maintenanceScheduler.onBatchStart();
265
+ try {
266
+ // Extract playbooks
267
+ let playbooksAdded = 0;
268
+ const existingPlaybooks = await this.memory.playbooks.getAll();
269
+ const playbookExtraction = await this.extractPlaybooks(existingPlaybooks);
270
+ for (const playbook of playbookExtraction.new) {
271
+ const exists = await this.memory.playbooks.exists(playbook.name, this.learningConfig.deduplicationThreshold);
272
+ if (!exists) {
273
+ await this.memory.playbooks.add(playbook);
274
+ playbooksAdded++;
275
+ }
276
+ }
277
+ // Apply updates to existing playbooks
278
+ for (const update of playbookExtraction.updates) {
279
+ if (update.refinement) {
280
+ await this.memory.playbooks.addRefinement(update.id, update.refinement.context, update.refinement.addition, update.refinement.source);
281
+ }
282
+ if (update.newTrigger) {
283
+ const playbook = await this.memory.playbooks.get(update.id);
284
+ if (playbook && !playbook.applicability.triggers.includes(update.newTrigger)) {
285
+ playbook.applicability.triggers.push(update.newTrigger);
286
+ await this.memory.playbooks.add(playbook);
287
+ }
288
+ }
289
+ if (update.newAntiPattern) {
290
+ const playbook = await this.memory.playbooks.get(update.id);
291
+ if (playbook && !playbook.applicability.antiPatterns.includes(update.newAntiPattern)) {
292
+ playbook.applicability.antiPatterns.push(update.newAntiPattern);
293
+ await this.memory.playbooks.add(playbook);
294
+ }
295
+ }
296
+ }
297
+ // Knowledge extraction (batch-level, richer than instant-loop)
298
+ let knowledgeExtracted = 0;
299
+ if (this.knowledgeExtractor && this.memory.knowledgeBank) {
300
+ const existingEntities = await this.memory.knowledgeBank.listEntities();
301
+ const context = { existingEntities };
302
+ for (let i = 0; i < this.accumulated.length; i++) {
303
+ const extracted = this.knowledgeExtractor.extract(this.accumulated[i], this.accumulatedAnalyses[i], context);
304
+ for (const obs of extracted.observations) {
305
+ try {
306
+ await this.memory.knowledgeBank.addObservation(obs);
307
+ knowledgeExtracted++;
308
+ }
309
+ catch {
310
+ // Non-critical
311
+ }
312
+ }
313
+ }
314
+ }
315
+ // Temporal compression
316
+ let compressionEvicted = 0;
317
+ let compressionPromoted = 0;
318
+ let compressionDemoted = 0;
319
+ if (this.temporalCompressor) {
320
+ const allExperiences = await this.memory.experiences.getAll();
321
+ const compressionResult = await this.temporalCompressor.compress(allExperiences);
322
+ for (const [id, updates] of compressionResult.updates) {
323
+ await this.memory.experiences.update(id, updates);
324
+ }
325
+ for (const id of compressionResult.evicted) {
326
+ await this.memory.experiences.delete(id);
327
+ }
328
+ compressionEvicted = compressionResult.evicted.length;
329
+ compressionPromoted = compressionResult.promoted.length;
330
+ compressionDemoted = compressionResult.demoted.length;
331
+ }
332
+ // Re-cluster experiences
333
+ const currentExperiences = await this.memory.experiences.getAll();
334
+ if (this.reasoningBank) {
335
+ this.reasoningBank.buildClusters(currentExperiences);
336
+ }
337
+ // Prune experiences
338
+ const pruned = await this.memory.experiences.prune({
339
+ maxCount: this.learningConfig.maxExperiences,
340
+ });
341
+ // Calculate success rate
342
+ const successCount = this.accumulatedAnalyses.filter(a => a.success).length;
343
+ const successRate = successCount / this.accumulated.length;
344
+ // Meta-learning: generate strategies periodically
345
+ if (this.metaLearner) {
346
+ try {
347
+ await this.metaLearner.learn();
348
+ }
349
+ catch {
350
+ // Non-critical
351
+ }
352
+ }
353
+ const trajectoriesProcessed = this.accumulated.length;
354
+ // Clear accumulated and reset energy evaluator
355
+ this.accumulated = [];
356
+ this.accumulatedAnalyses = [];
357
+ this.energyEvaluator.resetAfterBatch();
358
+ this.batchCyclesRun++;
359
+ return {
360
+ trajectoriesProcessed,
361
+ playbooksExtracted: playbooksAdded,
362
+ experiencesPruned: pruned.totalPruned + compressionEvicted,
363
+ experiencesCompressed: {
364
+ promoted: compressionPromoted,
365
+ demoted: compressionDemoted,
366
+ evicted: compressionEvicted,
367
+ },
368
+ experiencesClustered: currentExperiences.length,
369
+ knowledgeExtracted,
370
+ successRate,
371
+ triggerReasons: triggerReasons ?? ['manual_override'],
372
+ };
373
+ }
374
+ finally {
375
+ this.maintenanceScheduler.onBatchEnd();
376
+ }
377
+ }
378
+ // =========================================================================
379
+ // MAINTENANCE PHASE
380
+ // =========================================================================
381
+ /**
382
+ * Run a maintenance cycle.
383
+ * Executes registered maintenance tasks (defrag, healing, etc.).
384
+ * Can be called manually regardless of mode.
385
+ */
386
+ async runMaintenance(options) {
387
+ const result = await this.maintenanceScheduler.runMaintenance(options);
388
+ if (result.ran) {
389
+ this.maintenanceCyclesRun++;
390
+ }
391
+ return result;
392
+ }
393
+ /**
394
+ * Register a custom maintenance task.
395
+ */
396
+ registerMaintenanceTask(task) {
397
+ this.maintenanceScheduler.registerTask(task);
398
+ }
399
+ /**
400
+ * Register a custom anomaly detector for the healing orchestrator.
401
+ */
402
+ addAnomalyDetector(detector) {
403
+ this.healingOrchestrator.addDetector(detector);
404
+ }
405
+ /**
406
+ * Register a custom repair strategy for the healing orchestrator.
407
+ */
408
+ addRepairStrategy(strategy) {
409
+ this.healingOrchestrator.addRepairStrategy(strategy);
410
+ }
411
+ // =========================================================================
412
+ // ACCESSORS
413
+ // =========================================================================
414
+ /**
415
+ * Get the meta-learner instance.
416
+ */
417
+ getMetaLearner() {
418
+ return this.metaLearner;
419
+ }
420
+ /**
421
+ * Get the effectiveness tracker.
422
+ */
423
+ getEffectivenessTracker() {
424
+ return this.effectivenessTracker;
425
+ }
426
+ /**
427
+ * Get the energy evaluator.
428
+ */
429
+ getEnergyEvaluator() {
430
+ return this.energyEvaluator;
431
+ }
432
+ /**
433
+ * Get the maintenance scheduler.
434
+ */
435
+ getMaintenanceScheduler() {
436
+ return this.maintenanceScheduler;
437
+ }
438
+ /**
439
+ * Get the healing orchestrator.
440
+ */
441
+ getHealingOrchestrator() {
442
+ return this.healingOrchestrator;
443
+ }
444
+ /**
445
+ * Get accumulated trajectory count.
446
+ */
447
+ getAccumulatedCount() {
448
+ return this.accumulated.length;
449
+ }
450
+ /**
451
+ * Get accumulated trajectories with analyses (read-only).
452
+ */
453
+ getAccumulated() {
454
+ return this.accumulated.map((trajectory, i) => ({
455
+ trajectory,
456
+ analysis: this.accumulatedAnalyses[i],
457
+ }));
458
+ }
459
+ /**
460
+ * Get pipeline statistics.
461
+ */
462
+ getStats() {
463
+ return {
464
+ totalProcessed: this.totalProcessed,
465
+ batchCyclesRun: this.batchCyclesRun,
466
+ maintenanceCyclesRun: this.maintenanceCyclesRun,
467
+ pendingForBatch: this.energyEvaluator.getPendingCount(),
468
+ batchesSinceLastMaintenance: this.maintenanceScheduler.getBatchesSinceLastMaintenance(),
469
+ maintenanceTasks: this.maintenanceScheduler.getRegisteredTasks().map(t => t.name),
470
+ anomalyDetectors: this.healingOrchestrator.getDetectors().map(d => d.name),
471
+ repairStrategies: this.healingOrchestrator.getRepairStrategies().map(s => s.name),
472
+ };
473
+ }
474
+ /**
475
+ * Register a callback for instant-loop latency warnings.
476
+ */
477
+ onLatencyWarning(callback) {
478
+ this._onLatencyWarning = callback;
479
+ }
480
+ /**
481
+ * Update batch learning configuration.
482
+ */
483
+ updateConfig(config) {
484
+ this.learningConfig = { ...this.learningConfig, ...config };
485
+ if (config.creditStrategy) {
486
+ this.analyzer.setStrategy(config.creditStrategy);
487
+ }
488
+ }
489
+ // =========================================================================
490
+ // PRIVATE
491
+ // =========================================================================
492
+ /**
493
+ * Register built-in maintenance tasks.
494
+ */
495
+ registerBuiltInMaintenanceTasks() {
496
+ // Healing cycle
497
+ this.maintenanceScheduler.registerTask({
498
+ name: 'healing-cycle',
499
+ priority: 100,
500
+ execute: async () => {
501
+ const start = Date.now();
502
+ const context = await this.buildHealthContext();
503
+ const result = await this.healingOrchestrator.runCycle(context);
504
+ return {
505
+ taskName: 'healing-cycle',
506
+ success: true,
507
+ durationMs: Date.now() - start,
508
+ details: {
509
+ anomaliesDetected: result.anomaliesDetected.length,
510
+ repairsAttempted: result.repairs.length,
511
+ repairsSucceeded: result.repairs.filter(r => r.success).length,
512
+ },
513
+ };
514
+ },
515
+ });
516
+ // Knowledge defrag (if knowledge bank is available)
517
+ if (this.memory.knowledgeBank) {
518
+ this.maintenanceScheduler.registerTask({
519
+ name: 'knowledge-defrag',
520
+ priority: 80,
521
+ execute: async () => {
522
+ const start = Date.now();
523
+ const kb = this.memory.knowledgeBank;
524
+ const shouldDefrag = await kb.shouldDefragment();
525
+ if (!shouldDefrag) {
526
+ return {
527
+ taskName: 'knowledge-defrag',
528
+ success: true,
529
+ durationMs: Date.now() - start,
530
+ details: { skipped: true, reason: 'not needed' },
531
+ };
532
+ }
533
+ const result = await kb.defragment();
534
+ return {
535
+ taskName: 'knowledge-defrag',
536
+ success: true,
537
+ durationMs: Date.now() - start,
538
+ details: result,
539
+ };
540
+ },
541
+ });
542
+ }
543
+ // Meta-strategy generation
544
+ if (this.config.features.metaLearning ?? true) {
545
+ this.maintenanceScheduler.registerTask({
546
+ name: 'meta-strategy-generation',
547
+ priority: 60,
548
+ execute: async () => {
549
+ const start = Date.now();
550
+ if (!this.metaLearner) {
551
+ return {
552
+ taskName: 'meta-strategy-generation',
553
+ success: true,
554
+ durationMs: Date.now() - start,
555
+ details: { skipped: true, reason: 'meta-learner not initialized' },
556
+ };
557
+ }
558
+ const strategies = await this.metaLearner.learn();
559
+ return {
560
+ taskName: 'meta-strategy-generation',
561
+ success: true,
562
+ durationMs: Date.now() - start,
563
+ details: { strategiesGenerated: strategies.length },
564
+ };
565
+ },
566
+ });
567
+ }
568
+ // Efficacy maintenance tasks
569
+ this.registerEfficacyMaintenanceTasks();
570
+ }
571
+ /**
572
+ * Register efficacy maintenance tasks (decay detection, audit, lifecycle review).
573
+ * All tasks are log-only — results are returned in details but no automatic mutations.
574
+ */
575
+ registerEfficacyMaintenanceTasks() {
576
+ if (!(this.config.features.efficacy ?? true))
577
+ return;
578
+ const efficacyCfg = this.config.efficacy;
579
+ // 1. Playbook Decay Detection (priority 70) — runs every maintenance cycle
580
+ this.maintenanceScheduler.registerTask({
581
+ name: 'playbook-decay-detection',
582
+ priority: 70,
583
+ execute: async () => {
584
+ const start = Date.now();
585
+ this.lastDecayResult = null;
586
+ const { annotations, playbooks, playbookEffectiveness, unguidedSuccessRate } = await this.getEfficacyData();
587
+ if (playbooks.length < efficacyCfg.minPlaybooks || annotations.length < efficacyCfg.minAnnotations) {
588
+ return {
589
+ taskName: 'playbook-decay-detection',
590
+ success: true,
591
+ durationMs: Date.now() - start,
592
+ details: { skipped: true, reason: 'insufficient data' },
593
+ };
594
+ }
595
+ const result = await playbookDecayDetectionTemplate.heuristicFallback({
596
+ playbooks,
597
+ annotations,
598
+ playbookEffectiveness,
599
+ unguidedSuccessRate,
600
+ });
601
+ this.lastDecayResult = result;
602
+ return {
603
+ taskName: 'playbook-decay-detection',
604
+ success: true,
605
+ durationMs: Date.now() - start,
606
+ details: {
607
+ decayingCount: result.decaying.length,
608
+ atRiskCount: result.atRisk.length,
609
+ healthyCount: result.healthy.length,
610
+ decaying: result.decaying,
611
+ atRisk: result.atRisk,
612
+ portfolioAssessment: result.portfolioAssessment,
613
+ },
614
+ };
615
+ },
616
+ });
617
+ // 2. Playbook Efficacy Audit (priority 65) — audits flagged playbooks from decay detection
618
+ this.maintenanceScheduler.registerTask({
619
+ name: 'playbook-efficacy-audit',
620
+ priority: 65,
621
+ execute: async () => {
622
+ const start = Date.now();
623
+ if (!this.lastDecayResult) {
624
+ return {
625
+ taskName: 'playbook-efficacy-audit',
626
+ success: true,
627
+ durationMs: Date.now() - start,
628
+ details: { skipped: true, reason: 'no decay detection results' },
629
+ };
630
+ }
631
+ const flagged = [
632
+ ...this.lastDecayResult.decaying,
633
+ ...this.lastDecayResult.atRisk,
634
+ ];
635
+ if (flagged.length === 0) {
636
+ return {
637
+ taskName: 'playbook-efficacy-audit',
638
+ success: true,
639
+ durationMs: Date.now() - start,
640
+ details: { skipped: true, reason: 'no flagged playbooks' },
641
+ };
642
+ }
643
+ const { annotations, playbooks, playbookEffectiveness, unguidedSuccessRate } = await this.getEfficacyData();
644
+ const playbookMap = new Map(playbooks.map(p => [p.id, p]));
645
+ const effectivenessMap = new Map(playbookEffectiveness.map(e => [e.playbookId, e]));
646
+ const trajectoryDomainMap = this.buildTrajectoryDomainMap(annotations);
647
+ const audits = [];
648
+ for (const signal of flagged) {
649
+ const playbook = playbookMap.get(signal.playbookId);
650
+ if (!playbook)
651
+ continue;
652
+ const auditResult = await playbookEfficacyAuditTemplate.heuristicFallback({
653
+ playbook,
654
+ annotations,
655
+ playbookEffectiveness: effectivenessMap.get(signal.playbookId),
656
+ unguidedSuccessRate,
657
+ trajectoryDomainMap,
658
+ });
659
+ audits.push({
660
+ playbookId: signal.playbookId,
661
+ health: auditResult.assessment.health,
662
+ recommendations: auditResult.assessment.recommendations,
663
+ summary: auditResult.assessment.summary,
664
+ });
665
+ }
666
+ return {
667
+ taskName: 'playbook-efficacy-audit',
668
+ success: true,
669
+ durationMs: Date.now() - start,
670
+ details: {
671
+ auditsPerformed: audits.length,
672
+ audits,
673
+ },
674
+ };
675
+ },
676
+ });
677
+ // 3. Playbook Lifecycle Review (priority 50) — runs every Nth maintenance cycle
678
+ this.maintenanceScheduler.registerTask({
679
+ name: 'playbook-lifecycle-review',
680
+ priority: 50,
681
+ execute: async () => {
682
+ const start = Date.now();
683
+ // Only run every Nth maintenance cycle
684
+ if (this.maintenanceCyclesRun % efficacyCfg.lifecycleReviewFrequency !== 0) {
685
+ return {
686
+ taskName: 'playbook-lifecycle-review',
687
+ success: true,
688
+ durationMs: Date.now() - start,
689
+ details: {
690
+ skipped: true,
691
+ reason: `runs every ${efficacyCfg.lifecycleReviewFrequency} maintenance cycles`,
692
+ },
693
+ };
694
+ }
695
+ const { annotations, playbooks, playbookEffectiveness, unguidedSuccessRate } = await this.getEfficacyData();
696
+ if (playbooks.length < efficacyCfg.minPlaybooks || annotations.length < efficacyCfg.minAnnotations) {
697
+ return {
698
+ taskName: 'playbook-lifecycle-review',
699
+ success: true,
700
+ durationMs: Date.now() - start,
701
+ details: { skipped: true, reason: 'insufficient data' },
702
+ };
703
+ }
704
+ const trajectoryDomainMap = this.buildTrajectoryDomainMap(annotations);
705
+ const result = await playbookLifecycleReviewTemplate.heuristicFallback({
706
+ playbooks,
707
+ annotations,
708
+ playbookEffectiveness,
709
+ unguidedSuccessRate,
710
+ trajectoryDomainMap,
711
+ });
712
+ return {
713
+ taskName: 'playbook-lifecycle-review',
714
+ success: true,
715
+ durationMs: Date.now() - start,
716
+ details: {
717
+ totalPlaybooks: result.snapshot.totalPlaybooks,
718
+ recommendationsCount: result.recommendations.length,
719
+ recommendations: result.recommendations,
720
+ insights: result.insights,
721
+ actionPlan: result.actionPlan,
722
+ snapshot: {
723
+ avgConfidence: result.snapshot.avgConfidence,
724
+ avgSuccessRate: result.snapshot.avgSuccessRate,
725
+ confidenceBands: result.snapshot.confidenceBands,
726
+ decayingCount: result.snapshot.decaying.length,
727
+ staleCount: result.snapshot.stale.length,
728
+ },
729
+ },
730
+ };
731
+ },
732
+ });
733
+ }
734
+ /**
735
+ * Fetch shared efficacy data used by all three efficacy maintenance tasks.
736
+ */
737
+ async getEfficacyData() {
738
+ const playbooks = await this.memory.playbooks.getAll();
739
+ let annotations = [];
740
+ let playbookEffectiveness = [];
741
+ let unguidedSuccessRate = 0;
742
+ if (this.effectivenessTracker) {
743
+ annotations = await this.effectivenessTracker.getAll();
744
+ const metrics = await this.effectivenessTracker.computeMetrics();
745
+ playbookEffectiveness = metrics.playbookEffectiveness;
746
+ unguidedSuccessRate = metrics.unguidedSuccessRate;
747
+ }
748
+ return { annotations, playbooks, playbookEffectiveness, unguidedSuccessRate };
749
+ }
750
+ /**
751
+ * Build a trajectoryId→domain map from annotations.
752
+ * Uses accumulated trajectories when available, otherwise infers from task annotations.
753
+ */
754
+ buildTrajectoryDomainMap(_annotations) {
755
+ const domainMap = new Map();
756
+ // Map from accumulated trajectories (has task.domain directly).
757
+ // Annotations don't carry domain, so historical trajectories will
758
+ // fall through to the toolkit's 'unknown' default — acceptable for log-only mode.
759
+ for (const t of this.accumulated) {
760
+ domainMap.set(t.id, t.task.domain);
761
+ }
762
+ return domainMap;
763
+ }
764
+ /**
765
+ * Build health context for the healing orchestrator.
766
+ */
767
+ async buildHealthContext() {
768
+ const [experienceCount, playbookCount] = await Promise.all([
769
+ this.memory.experiences.count(),
770
+ this.memory.playbooks.count(),
771
+ ]);
772
+ // Compute recent success rate from accumulated analyses
773
+ const recentAnalyses = this.accumulatedAnalyses.length > 0
774
+ ? this.accumulatedAnalyses
775
+ : [];
776
+ const recentSuccessRate = recentAnalyses.length > 0
777
+ ? recentAnalyses.filter(a => a.success).length / recentAnalyses.length
778
+ : 1.0;
779
+ return {
780
+ trajectoriesProcessed: this.totalProcessed,
781
+ experienceCount,
782
+ playbookCount,
783
+ recentSuccessRate,
784
+ batchesSinceLastMaintenance: this.maintenanceScheduler.getBatchesSinceLastMaintenance(),
785
+ metrics: {},
786
+ };
787
+ }
788
+ /**
789
+ * Analyze a trajectory via workspace template or heuristic fallback.
790
+ */
791
+ async analyzeWithTemplate(trajectory) {
792
+ try {
793
+ const result = await this.taskRunner.run(trajectoryAnalysisTemplate, {
794
+ trajectory,
795
+ creditStrategy: this.learningConfig.creditStrategy,
796
+ });
797
+ return result.output;
798
+ }
799
+ catch {
800
+ return this.analyzer.analyze(trajectory);
801
+ }
802
+ }
803
+ /**
804
+ * Extract playbooks via workspace template or heuristic fallback.
805
+ */
806
+ async extractPlaybooks(existingPlaybooks) {
807
+ if (this.taskRunner) {
808
+ try {
809
+ const result = await this.taskRunner.run(playbookExtractionTemplate, {
810
+ trajectories: this.accumulated,
811
+ analyses: this.accumulatedAnalyses,
812
+ existingPlaybooks,
813
+ });
814
+ return result.output;
815
+ }
816
+ catch {
817
+ // Fall through to heuristic
818
+ }
819
+ }
820
+ return this.playbookExtractor.extract(this.accumulated, this.accumulatedAnalyses, existingPlaybooks);
821
+ }
822
+ /**
823
+ * Empty batch result for when there's nothing to process.
824
+ */
825
+ emptyBatchResult(triggerReasons) {
826
+ return {
827
+ trajectoriesProcessed: 0,
828
+ playbooksExtracted: 0,
829
+ experiencesPruned: 0,
830
+ experiencesCompressed: { promoted: 0, demoted: 0, evicted: 0 },
831
+ experiencesClustered: 0,
832
+ knowledgeExtracted: 0,
833
+ successRate: 0,
834
+ triggerReasons,
835
+ };
836
+ }
837
+ }
838
+ /**
839
+ * Create a UnifiedLearningPipeline.
840
+ */
841
+ export function createUnifiedPipeline(memory, config, persistence) {
842
+ return new UnifiedLearningPipeline(memory, config, persistence);
843
+ }
844
+ //# sourceMappingURL=unified-pipeline.js.map