pulseed 0.4.0 → 0.4.2

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 (335) hide show
  1. package/dist/base/state/state-manager-goal-write.d.ts +22 -0
  2. package/dist/base/state/state-manager-goal-write.d.ts.map +1 -0
  3. package/dist/base/state/state-manager-goal-write.js +74 -0
  4. package/dist/base/state/state-manager-goal-write.js.map +1 -0
  5. package/dist/base/state/state-manager-wal.d.ts +11 -0
  6. package/dist/base/state/state-manager-wal.d.ts.map +1 -0
  7. package/dist/base/state/state-manager-wal.js +89 -0
  8. package/dist/base/state/state-manager-wal.js.map +1 -0
  9. package/dist/base/state/state-manager.d.ts +1 -4
  10. package/dist/base/state/state-manager.d.ts.map +1 -1
  11. package/dist/base/state/state-manager.js +18 -127
  12. package/dist/base/state/state-manager.js.map +1 -1
  13. package/dist/interface/chat/chat-runner.d.ts +1 -1
  14. package/dist/interface/chat/event-subscriber.d.ts +4 -0
  15. package/dist/interface/chat/event-subscriber.d.ts.map +1 -1
  16. package/dist/interface/chat/event-subscriber.js +49 -2
  17. package/dist/interface/chat/event-subscriber.js.map +1 -1
  18. package/dist/interface/chat/tend-command.d.ts +1 -1
  19. package/dist/interface/cli/cli-command-registry.js +1 -1
  20. package/dist/interface/cli/cli-command-registry.js.map +1 -1
  21. package/dist/interface/cli/commands/chat.js +2 -2
  22. package/dist/interface/cli/commands/daemon.d.ts.map +1 -1
  23. package/dist/interface/cli/commands/daemon.js +87 -44
  24. package/dist/interface/cli/commands/daemon.js.map +1 -1
  25. package/dist/interface/cli/commands/schedule.js +2 -2
  26. package/dist/interface/cli/commands/setup/steps-runtime.js +1 -1
  27. package/dist/interface/cli/ensure-api-key.d.ts +4 -1
  28. package/dist/interface/cli/ensure-api-key.d.ts.map +1 -1
  29. package/dist/interface/cli/ensure-api-key.js +52 -15
  30. package/dist/interface/cli/ensure-api-key.js.map +1 -1
  31. package/dist/interface/tui/app.d.ts +1 -1
  32. package/dist/interface/tui/chat/scroll.d.ts +14 -0
  33. package/dist/interface/tui/chat/scroll.d.ts.map +1 -0
  34. package/dist/interface/tui/chat/scroll.js +46 -0
  35. package/dist/interface/tui/chat/scroll.js.map +1 -0
  36. package/dist/interface/tui/chat/suggestions.d.ts +8 -0
  37. package/dist/interface/tui/chat/suggestions.d.ts.map +1 -0
  38. package/dist/interface/tui/chat/suggestions.js +112 -0
  39. package/dist/interface/tui/chat/suggestions.js.map +1 -0
  40. package/dist/interface/tui/chat/types.d.ts +31 -0
  41. package/dist/interface/tui/chat/types.d.ts.map +1 -0
  42. package/dist/interface/tui/chat/types.js +2 -0
  43. package/dist/interface/tui/chat/types.js.map +1 -0
  44. package/dist/interface/tui/chat/viewport.d.ts +3 -0
  45. package/dist/interface/tui/chat/viewport.d.ts.map +1 -0
  46. package/dist/interface/tui/chat/viewport.js +78 -0
  47. package/dist/interface/tui/chat/viewport.js.map +1 -0
  48. package/dist/interface/tui/chat.d.ts +5 -49
  49. package/dist/interface/tui/chat.d.ts.map +1 -1
  50. package/dist/interface/tui/chat.js +7 -236
  51. package/dist/interface/tui/chat.js.map +1 -1
  52. package/dist/interface/tui/entry.js +3 -3
  53. package/dist/interface/tui/use-loop.d.ts +1 -1
  54. package/dist/orchestrator/execution/task/task-lifecycle.d.ts +3 -0
  55. package/dist/orchestrator/execution/task/task-lifecycle.d.ts.map +1 -1
  56. package/dist/orchestrator/execution/task/task-lifecycle.js +3 -0
  57. package/dist/orchestrator/execution/task/task-lifecycle.js.map +1 -1
  58. package/dist/orchestrator/execution/task/task-verifier-rules.d.ts.map +1 -1
  59. package/dist/orchestrator/execution/task/task-verifier-rules.js +34 -2
  60. package/dist/orchestrator/execution/task/task-verifier-rules.js.map +1 -1
  61. package/dist/orchestrator/execution/task/task-verifier-types.d.ts +2 -0
  62. package/dist/orchestrator/execution/task/task-verifier-types.d.ts.map +1 -1
  63. package/dist/orchestrator/loop/checkpoint-manager-loop.d.ts +1 -1
  64. package/dist/orchestrator/loop/checkpoint-manager-loop.d.ts.map +1 -1
  65. package/dist/orchestrator/loop/core-loop/capability.d.ts +22 -0
  66. package/dist/orchestrator/loop/core-loop/capability.d.ts.map +1 -0
  67. package/dist/orchestrator/loop/core-loop/capability.js +151 -0
  68. package/dist/orchestrator/loop/core-loop/capability.js.map +1 -0
  69. package/dist/orchestrator/loop/core-loop/contracts.d.ts +245 -0
  70. package/dist/orchestrator/loop/core-loop/contracts.d.ts.map +1 -0
  71. package/dist/orchestrator/loop/core-loop/contracts.js +40 -0
  72. package/dist/orchestrator/loop/core-loop/contracts.js.map +1 -0
  73. package/dist/orchestrator/loop/core-loop/control.d.ts +27 -0
  74. package/dist/orchestrator/loop/core-loop/control.d.ts.map +1 -0
  75. package/dist/orchestrator/loop/core-loop/control.js +72 -0
  76. package/dist/orchestrator/loop/core-loop/control.js.map +1 -0
  77. package/dist/orchestrator/loop/core-loop/learning.d.ts +31 -0
  78. package/dist/orchestrator/loop/core-loop/learning.d.ts.map +1 -0
  79. package/dist/orchestrator/loop/core-loop/learning.js +92 -0
  80. package/dist/orchestrator/loop/core-loop/learning.js.map +1 -0
  81. package/dist/orchestrator/loop/core-loop/preparation.d.ts +63 -0
  82. package/dist/orchestrator/loop/core-loop/preparation.d.ts.map +1 -0
  83. package/dist/orchestrator/loop/core-loop/preparation.js +362 -0
  84. package/dist/orchestrator/loop/core-loop/preparation.js.map +1 -0
  85. package/dist/orchestrator/loop/core-loop/task-cycle.d.ts +29 -0
  86. package/dist/orchestrator/loop/core-loop/task-cycle.d.ts.map +1 -0
  87. package/dist/orchestrator/loop/core-loop/task-cycle.js +674 -0
  88. package/dist/orchestrator/loop/core-loop/task-cycle.js.map +1 -0
  89. package/dist/orchestrator/loop/core-loop-capability.d.ts +1 -24
  90. package/dist/orchestrator/loop/core-loop-capability.d.ts.map +1 -1
  91. package/dist/orchestrator/loop/core-loop-capability.js +1 -153
  92. package/dist/orchestrator/loop/core-loop-capability.js.map +1 -1
  93. package/dist/orchestrator/loop/core-loop-learning.d.ts +1 -34
  94. package/dist/orchestrator/loop/core-loop-learning.d.ts.map +1 -1
  95. package/dist/orchestrator/loop/core-loop-learning.js +1 -95
  96. package/dist/orchestrator/loop/core-loop-learning.js.map +1 -1
  97. package/dist/orchestrator/loop/core-loop-phases-b.d.ts +1 -31
  98. package/dist/orchestrator/loop/core-loop-phases-b.d.ts.map +1 -1
  99. package/dist/orchestrator/loop/core-loop-phases-b.js +1 -669
  100. package/dist/orchestrator/loop/core-loop-phases-b.js.map +1 -1
  101. package/dist/orchestrator/loop/core-loop-phases-c.d.ts +1 -26
  102. package/dist/orchestrator/loop/core-loop-phases-c.d.ts.map +1 -1
  103. package/dist/orchestrator/loop/core-loop-phases-c.js +1 -71
  104. package/dist/orchestrator/loop/core-loop-phases-c.js.map +1 -1
  105. package/dist/orchestrator/loop/core-loop-phases.d.ts +1 -68
  106. package/dist/orchestrator/loop/core-loop-phases.d.ts.map +1 -1
  107. package/dist/orchestrator/loop/core-loop-phases.js +1 -367
  108. package/dist/orchestrator/loop/core-loop-phases.js.map +1 -1
  109. package/dist/orchestrator/loop/core-loop-types.d.ts +1 -244
  110. package/dist/orchestrator/loop/core-loop-types.d.ts.map +1 -1
  111. package/dist/orchestrator/loop/core-loop-types.js +1 -39
  112. package/dist/orchestrator/loop/core-loop-types.js.map +1 -1
  113. package/dist/orchestrator/loop/core-loop.d.ts +3 -3
  114. package/dist/orchestrator/loop/core-loop.d.ts.map +1 -1
  115. package/dist/orchestrator/loop/core-loop.js +6 -6
  116. package/dist/orchestrator/loop/core-loop.js.map +1 -1
  117. package/dist/orchestrator/loop/loop-report-helper.d.ts +1 -1
  118. package/dist/orchestrator/loop/loop-report-helper.d.ts.map +1 -1
  119. package/dist/orchestrator/loop/parallel-dispatch.d.ts +2 -2
  120. package/dist/orchestrator/loop/parallel-dispatch.d.ts.map +1 -1
  121. package/dist/orchestrator/loop/post-loop-hooks.d.ts +1 -1
  122. package/dist/orchestrator/loop/post-loop-hooks.d.ts.map +1 -1
  123. package/dist/orchestrator/loop/tree-loop-runner.d.ts +1 -1
  124. package/dist/orchestrator/loop/tree-loop-runner.d.ts.map +1 -1
  125. package/dist/orchestrator/loop/tree-loop-runner.js +1 -1
  126. package/dist/orchestrator/loop/tree-loop-runner.js.map +1 -1
  127. package/dist/platform/dream/dream-schedule-suggestions.d.ts +1 -1
  128. package/dist/platform/drive/drive-system.d.ts +8 -0
  129. package/dist/platform/drive/drive-system.d.ts.map +1 -1
  130. package/dist/platform/drive/drive-system.js +39 -22
  131. package/dist/platform/drive/drive-system.js.map +1 -1
  132. package/dist/platform/observation/engine/observe-context.d.ts +4 -0
  133. package/dist/platform/observation/engine/observe-context.d.ts.map +1 -0
  134. package/dist/platform/observation/engine/observe-context.js +26 -0
  135. package/dist/platform/observation/engine/observe-context.js.map +1 -0
  136. package/dist/platform/observation/engine/observe-datasource-stage.d.ts +33 -0
  137. package/dist/platform/observation/engine/observe-datasource-stage.d.ts.map +1 -0
  138. package/dist/platform/observation/engine/observe-datasource-stage.js +66 -0
  139. package/dist/platform/observation/engine/observe-datasource-stage.js.map +1 -0
  140. package/dist/platform/observation/engine/observe-llm-stage.d.ts +25 -0
  141. package/dist/platform/observation/engine/observe-llm-stage.d.ts.map +1 -0
  142. package/dist/platform/observation/engine/observe-llm-stage.js +79 -0
  143. package/dist/platform/observation/engine/observe-llm-stage.js.map +1 -0
  144. package/dist/platform/observation/engine/observe-precheck.d.ts +21 -0
  145. package/dist/platform/observation/engine/observe-precheck.d.ts.map +1 -0
  146. package/dist/platform/observation/engine/observe-precheck.js +51 -0
  147. package/dist/platform/observation/engine/observe-precheck.js.map +1 -0
  148. package/dist/platform/observation/engine/observe-self-report.d.ts +18 -0
  149. package/dist/platform/observation/engine/observe-self-report.d.ts.map +1 -0
  150. package/dist/platform/observation/engine/observe-self-report.js +26 -0
  151. package/dist/platform/observation/engine/observe-self-report.js.map +1 -0
  152. package/dist/platform/observation/engine/observe-tool-stage.d.ts +21 -0
  153. package/dist/platform/observation/engine/observe-tool-stage.d.ts.map +1 -0
  154. package/dist/platform/observation/engine/observe-tool-stage.js +49 -0
  155. package/dist/platform/observation/engine/observe-tool-stage.js.map +1 -0
  156. package/dist/platform/observation/observation-engine.d.ts.map +1 -1
  157. package/dist/platform/observation/observation-engine.js +67 -246
  158. package/dist/platform/observation/observation-engine.js.map +1 -1
  159. package/dist/prompt/context-assembler.d.ts +61 -13
  160. package/dist/prompt/context-assembler.d.ts.map +1 -1
  161. package/dist/prompt/context-assembler.js +18 -3
  162. package/dist/prompt/context-assembler.js.map +1 -1
  163. package/dist/runtime/approval-broker.d.ts.map +1 -1
  164. package/dist/runtime/approval-broker.js +1 -0
  165. package/dist/runtime/approval-broker.js.map +1 -1
  166. package/dist/runtime/command-dispatcher.d.ts +35 -0
  167. package/dist/runtime/command-dispatcher.d.ts.map +1 -0
  168. package/dist/runtime/command-dispatcher.js +145 -0
  169. package/dist/runtime/command-dispatcher.js.map +1 -0
  170. package/dist/runtime/daemon/client.d.ts +67 -0
  171. package/dist/runtime/daemon/client.d.ts.map +1 -0
  172. package/dist/runtime/daemon/client.js +330 -0
  173. package/dist/runtime/daemon/client.js.map +1 -0
  174. package/dist/runtime/daemon/health.d.ts +31 -0
  175. package/dist/runtime/daemon/health.d.ts.map +1 -0
  176. package/dist/runtime/daemon/health.js +113 -0
  177. package/dist/runtime/daemon/health.js.map +1 -0
  178. package/dist/runtime/daemon/index.d.ts +9 -0
  179. package/dist/runtime/daemon/index.d.ts.map +1 -0
  180. package/dist/runtime/daemon/index.js +8 -0
  181. package/dist/runtime/daemon/index.js.map +1 -0
  182. package/dist/runtime/daemon/maintenance.d.ts +47 -0
  183. package/dist/runtime/daemon/maintenance.d.ts.map +1 -0
  184. package/dist/runtime/daemon/maintenance.js +230 -0
  185. package/dist/runtime/daemon/maintenance.js.map +1 -0
  186. package/dist/runtime/daemon/persistence.d.ts +20 -0
  187. package/dist/runtime/daemon/persistence.d.ts.map +1 -0
  188. package/dist/runtime/daemon/persistence.js +112 -0
  189. package/dist/runtime/daemon/persistence.js.map +1 -0
  190. package/dist/runtime/daemon/runner-lifecycle.d.ts +29 -0
  191. package/dist/runtime/daemon/runner-lifecycle.d.ts.map +1 -0
  192. package/dist/runtime/daemon/runner-lifecycle.js +56 -0
  193. package/dist/runtime/daemon/runner-lifecycle.js.map +1 -0
  194. package/dist/runtime/daemon/runner.d.ts +229 -0
  195. package/dist/runtime/daemon/runner.d.ts.map +1 -0
  196. package/dist/runtime/daemon/runner.js +875 -0
  197. package/dist/runtime/daemon/runner.js.map +1 -0
  198. package/dist/runtime/daemon/runtime-ownership.d.ts +30 -0
  199. package/dist/runtime/daemon/runtime-ownership.d.ts.map +1 -0
  200. package/dist/runtime/daemon/runtime-ownership.js +132 -0
  201. package/dist/runtime/daemon/runtime-ownership.js.map +1 -0
  202. package/dist/runtime/daemon/signals.d.ts +17 -0
  203. package/dist/runtime/daemon/signals.d.ts.map +1 -0
  204. package/dist/runtime/daemon/signals.js +31 -0
  205. package/dist/runtime/daemon/signals.js.map +1 -0
  206. package/dist/runtime/daemon/types.d.ts +8 -0
  207. package/dist/runtime/daemon/types.d.ts.map +1 -0
  208. package/dist/runtime/daemon/types.js +2 -0
  209. package/dist/runtime/daemon/types.js.map +1 -0
  210. package/dist/runtime/daemon-client.d.ts +1 -55
  211. package/dist/runtime/daemon-client.d.ts.map +1 -1
  212. package/dist/runtime/daemon-client.js +1 -297
  213. package/dist/runtime/daemon-client.js.map +1 -1
  214. package/dist/runtime/daemon-health.d.ts +1 -30
  215. package/dist/runtime/daemon-health.d.ts.map +1 -1
  216. package/dist/runtime/daemon-health.js +1 -112
  217. package/dist/runtime/daemon-health.js.map +1 -1
  218. package/dist/runtime/daemon-runner-lifecycle.d.ts +2 -0
  219. package/dist/runtime/daemon-runner-lifecycle.d.ts.map +1 -0
  220. package/dist/runtime/daemon-runner-lifecycle.js +2 -0
  221. package/dist/runtime/daemon-runner-lifecycle.js.map +1 -0
  222. package/dist/runtime/daemon-runner.d.ts +1 -231
  223. package/dist/runtime/daemon-runner.d.ts.map +1 -1
  224. package/dist/runtime/daemon-runner.js +1 -1042
  225. package/dist/runtime/daemon-runner.js.map +1 -1
  226. package/dist/runtime/daemon-runtime-ownership.d.ts +2 -0
  227. package/dist/runtime/daemon-runtime-ownership.d.ts.map +1 -0
  228. package/dist/runtime/daemon-runtime-ownership.js +2 -0
  229. package/dist/runtime/daemon-runtime-ownership.js.map +1 -0
  230. package/dist/runtime/daemon-signals.d.ts +1 -16
  231. package/dist/runtime/daemon-signals.d.ts.map +1 -1
  232. package/dist/runtime/daemon-signals.js +1 -30
  233. package/dist/runtime/daemon-signals.js.map +1 -1
  234. package/dist/runtime/event/dispatcher.d.ts +34 -0
  235. package/dist/runtime/event/dispatcher.d.ts.map +1 -0
  236. package/dist/runtime/event/dispatcher.js +124 -0
  237. package/dist/runtime/event/dispatcher.js.map +1 -0
  238. package/dist/runtime/event/index.d.ts +5 -0
  239. package/dist/runtime/event/index.d.ts.map +1 -0
  240. package/dist/runtime/event/index.js +5 -0
  241. package/dist/runtime/event/index.js.map +1 -0
  242. package/dist/runtime/event/server-snapshot-reader.d.ts +31 -0
  243. package/dist/runtime/event/server-snapshot-reader.d.ts.map +1 -0
  244. package/dist/runtime/event/server-snapshot-reader.js +94 -0
  245. package/dist/runtime/event/server-snapshot-reader.js.map +1 -0
  246. package/dist/runtime/event/server-sse.d.ts +25 -0
  247. package/dist/runtime/event/server-sse.d.ts.map +1 -0
  248. package/dist/runtime/event/server-sse.js +149 -0
  249. package/dist/runtime/event/server-sse.js.map +1 -0
  250. package/dist/runtime/event/server.d.ts +114 -0
  251. package/dist/runtime/event/server.d.ts.map +1 -0
  252. package/dist/runtime/event/server.js +651 -0
  253. package/dist/runtime/event/server.js.map +1 -0
  254. package/dist/runtime/event-dispatcher.d.ts +2 -0
  255. package/dist/runtime/event-dispatcher.d.ts.map +1 -0
  256. package/dist/runtime/event-dispatcher.js +2 -0
  257. package/dist/runtime/event-dispatcher.js.map +1 -0
  258. package/dist/runtime/event-server-snapshot-reader.d.ts +2 -0
  259. package/dist/runtime/event-server-snapshot-reader.d.ts.map +1 -0
  260. package/dist/runtime/event-server-snapshot-reader.js +2 -0
  261. package/dist/runtime/event-server-snapshot-reader.js.map +1 -0
  262. package/dist/runtime/event-server-sse.d.ts +2 -0
  263. package/dist/runtime/event-server-sse.d.ts.map +1 -0
  264. package/dist/runtime/event-server-sse.js +2 -0
  265. package/dist/runtime/event-server-sse.js.map +1 -0
  266. package/dist/runtime/event-server.d.ts +1 -91
  267. package/dist/runtime/event-server.d.ts.map +1 -1
  268. package/dist/runtime/event-server.js +1 -698
  269. package/dist/runtime/event-server.js.map +1 -1
  270. package/dist/runtime/executor/loop-supervisor.d.ts +9 -5
  271. package/dist/runtime/executor/loop-supervisor.d.ts.map +1 -1
  272. package/dist/runtime/executor/loop-supervisor.js +59 -76
  273. package/dist/runtime/executor/loop-supervisor.js.map +1 -1
  274. package/dist/runtime/gateway/http-channel-adapter.d.ts +1 -1
  275. package/dist/runtime/plugin-loader.d.ts +1 -1
  276. package/dist/runtime/queue/index.d.ts +0 -4
  277. package/dist/runtime/queue/index.d.ts.map +1 -1
  278. package/dist/runtime/queue/index.js +0 -2
  279. package/dist/runtime/queue/index.js.map +1 -1
  280. package/dist/runtime/queue/journal-backed-queue.d.ts.map +1 -1
  281. package/dist/runtime/queue/journal-backed-queue.js +2 -0
  282. package/dist/runtime/queue/journal-backed-queue.js.map +1 -1
  283. package/dist/runtime/schedule/engine-layers.d.ts +44 -0
  284. package/dist/runtime/schedule/engine-layers.d.ts.map +1 -0
  285. package/dist/runtime/schedule/engine-layers.js +433 -0
  286. package/dist/runtime/schedule/engine-layers.js.map +1 -0
  287. package/dist/runtime/schedule/engine.d.ts +82 -0
  288. package/dist/runtime/schedule/engine.d.ts.map +1 -0
  289. package/dist/runtime/schedule/engine.js +480 -0
  290. package/dist/runtime/schedule/engine.js.map +1 -0
  291. package/dist/runtime/schedule/index.d.ts +5 -0
  292. package/dist/runtime/schedule/index.d.ts.map +1 -0
  293. package/dist/runtime/schedule/index.js +5 -0
  294. package/dist/runtime/schedule/index.js.map +1 -0
  295. package/dist/runtime/schedule/presets.d.ts +536 -0
  296. package/dist/runtime/schedule/presets.d.ts.map +1 -0
  297. package/dist/runtime/schedule/presets.js +166 -0
  298. package/dist/runtime/schedule/presets.js.map +1 -0
  299. package/dist/runtime/schedule/source.d.ts +65 -0
  300. package/dist/runtime/schedule/source.d.ts.map +1 -0
  301. package/dist/runtime/schedule/source.js +16 -0
  302. package/dist/runtime/schedule/source.js.map +1 -0
  303. package/dist/runtime/schedule-engine-layers.d.ts +1 -43
  304. package/dist/runtime/schedule-engine-layers.d.ts.map +1 -1
  305. package/dist/runtime/schedule-engine-layers.js +1 -432
  306. package/dist/runtime/schedule-engine-layers.js.map +1 -1
  307. package/dist/runtime/schedule-engine.d.ts +1 -81
  308. package/dist/runtime/schedule-engine.d.ts.map +1 -1
  309. package/dist/runtime/schedule-engine.js +1 -479
  310. package/dist/runtime/schedule-engine.js.map +1 -1
  311. package/dist/runtime/schedule-presets.d.ts +1 -535
  312. package/dist/runtime/schedule-presets.d.ts.map +1 -1
  313. package/dist/runtime/schedule-presets.js +1 -165
  314. package/dist/runtime/schedule-presets.js.map +1 -1
  315. package/dist/runtime/schedule-source.d.ts +1 -64
  316. package/dist/runtime/schedule-source.d.ts.map +1 -1
  317. package/dist/runtime/schedule-source.js +1 -15
  318. package/dist/runtime/schedule-source.js.map +1 -1
  319. package/dist/runtime/types/daemon.d.ts.map +1 -1
  320. package/dist/runtime/types/daemon.js +2 -1
  321. package/dist/runtime/types/daemon.js.map +1 -1
  322. package/dist/runtime/watchdog.d.ts +44 -0
  323. package/dist/runtime/watchdog.d.ts.map +1 -0
  324. package/dist/runtime/watchdog.js +185 -0
  325. package/dist/runtime/watchdog.js.map +1 -0
  326. package/dist/tools/builtin/index.d.ts +1 -1
  327. package/dist/tools/schedule/CreateScheduleTool/CreateScheduleTool.d.ts +1 -1
  328. package/dist/tools/schedule/CreateScheduleTool/CreateScheduleTool.js +1 -1
  329. package/dist/tools/schedule/GetScheduleTool/GetScheduleTool.d.ts +1 -1
  330. package/dist/tools/schedule/ListSchedulesTool/ListSchedulesTool.d.ts +1 -1
  331. package/dist/tools/schedule/PauseScheduleTool/PauseScheduleTool.d.ts +1 -1
  332. package/dist/tools/schedule/RemoveScheduleTool/RemoveScheduleTool.d.ts +1 -1
  333. package/dist/tools/schedule/ResumeScheduleTool/ResumeScheduleTool.d.ts +1 -1
  334. package/dist/tools/schedule/UpdateScheduleTool/UpdateScheduleTool.d.ts +1 -1
  335. package/package.json +1 -1
@@ -1,670 +1,2 @@
1
- /**
2
- * core-loop-phases-b.ts
3
- *
4
- * Phases 5–7 of CoreLoop.runOneIteration() as standalone functions.
5
- * Phases 1–4 are in core-loop-phases.ts.
6
- */
7
- import { randomUUID } from "node:crypto";
8
- import * as path from "node:path";
9
- import { KnowledgeGraph } from "../../platform/knowledge/knowledge-graph.js";
10
- import { loadDreamActivationState, mergeUniqueKnowledgeEntries } from "../../platform/dream/dream-activation.js";
11
- import { buildDriveContext, } from "./core-loop-types.js";
12
- import { getMilestones, evaluatePace, } from "../goal/milestone-evaluator.js";
13
- import { gatherStallEvidence } from "./stall-evidence.js";
14
- import { verifyWithTools } from "./verification-layer1.js";
15
- import { buildLoopToolContext } from "./core-loop-phases.js";
16
- import { expandKnowledgeEntriesWithGraph, mergeWorkingMemorySelections, } from "../execution/context/context-builder.js";
17
- // ─── Phase 5 ───
18
- /** Completion check + milestone deadline check.
19
- * Sets result.error on fatal failure, sets result.completionJudgment. */
20
- export async function checkCompletionAndMilestones(ctx, goalId, goal, result, startTime) {
21
- // R1-1: record pre-task judgment (do NOT early-return here)
22
- try {
23
- const judgment = goal.children_ids.length > 0
24
- ? await ctx.deps.satisficingJudge.judgeTreeCompletion(goalId)
25
- : ctx.deps.satisficingJudge.isGoalComplete(goal);
26
- result.completionJudgment = judgment;
27
- // Wire satisficing callback to MemoryLifecycleManager
28
- // SatisficingJudge fires (goalId, satisfiedDimensions[]) but MLM expects per-dimension calls
29
- if (ctx.deps.memoryLifecycleManager) {
30
- const blockingSet = new Set(judgment.blocking_dimensions);
31
- for (const dim of goal.dimensions) {
32
- const isSatisfied = !blockingSet.has(dim.name);
33
- ctx.deps.memoryLifecycleManager.onSatisficingJudgment(goalId, dim.name, isSatisfied);
34
- }
35
- }
36
- }
37
- catch (err) {
38
- result.error = `Completion check failed: ${err instanceof Error ? err.message : String(err)}`;
39
- ctx.logger?.error(`CoreLoop: ${result.error}`, { goalId });
40
- result.elapsedMs = Date.now() - startTime;
41
- return;
42
- }
43
- // Milestone deadline check
44
- try {
45
- const allGoals = [goal];
46
- for (const childId of goal.children_ids) {
47
- const child = await ctx.deps.stateManager.loadGoal(childId);
48
- if (child)
49
- allGoals.push(child);
50
- }
51
- const milestones = getMilestones(allGoals);
52
- if (milestones.length > 0) {
53
- const milestoneAlerts = [];
54
- for (const milestone of milestones) {
55
- const currentAchievement = milestone.pace_snapshot?.achievement_ratio ??
56
- (typeof milestone.dimensions[0]?.current_value === "number"
57
- ? Math.min(milestone.dimensions[0].current_value / 100, 1)
58
- : 0);
59
- const snapshot = evaluatePace(milestone, currentAchievement);
60
- await ctx.deps.stateManager.savePaceSnapshot(milestone.id, snapshot);
61
- if (snapshot.status === "at_risk" || snapshot.status === "behind") {
62
- milestoneAlerts.push({
63
- goalId: milestone.id,
64
- status: snapshot.status,
65
- pace_ratio: snapshot.pace_ratio,
66
- });
67
- }
68
- else {
69
- if (ctx.deps.learningPipeline) {
70
- try {
71
- await ctx.deps.learningPipeline.onMilestoneReached(goalId, `Milestone ${milestone.title}: pace ${snapshot.status}`);
72
- }
73
- catch {
74
- // non-fatal
75
- }
76
- }
77
- }
78
- }
79
- if (milestoneAlerts.length > 0) {
80
- result.milestoneAlerts = milestoneAlerts;
81
- }
82
- }
83
- }
84
- catch {
85
- // Milestone check failure is non-fatal
86
- }
87
- }
88
- // ─── Phase 6 ───
89
- /** Stall detection per-dimension and globally, plus portfolio rebalance. */
90
- export async function detectStallsAndRebalance(ctx, goalId, goal, result) {
91
- try {
92
- const gapHistory = await ctx.deps.stateManager.loadGapHistory(goalId);
93
- // Gather tool-based workspace evidence for stall detection (Phase 6)
94
- if (ctx.toolExecutor) {
95
- try {
96
- const toolContext = {
97
- cwd: process.cwd(),
98
- goalId,
99
- trustBalance: 0,
100
- preApproved: true,
101
- approvalFn: async () => false,
102
- };
103
- const evidence = await gatherStallEvidence(ctx.toolExecutor, toolContext);
104
- result.toolStallEvidence = evidence;
105
- if (!evidence.hasWorkspaceChanges) {
106
- ctx.logger?.info("CoreLoop: stall evidence — no workspace changes detected", { goalId, toolErrors: evidence.toolErrors });
107
- }
108
- }
109
- catch {
110
- // Non-fatal: evidence gathering failure does not block stall detection
111
- }
112
- }
113
- // Gap 3: isSuppressed wiring — suppression is per-dimension only.
114
- // Collect suppressed dimensions from all active WaitStrategies; skip those dims in stall loop.
115
- const suppressedDimensions = new Set();
116
- if (ctx.deps.portfolioManager) {
117
- try {
118
- const portfolio = await ctx.deps.strategyManager.getPortfolio(goalId);
119
- if (portfolio) {
120
- for (const s of portfolio.strategies) {
121
- if (s.state !== "active" || !ctx.deps.portfolioManager.isWaitStrategy(s))
122
- continue;
123
- const ws = s;
124
- const waitUntil = typeof ws["wait_until"] === "string" ? ws["wait_until"] : null;
125
- if (!ctx.deps.stallDetector.isSuppressed(waitUntil))
126
- continue;
127
- // Suppress only the primary_dimension of this WaitStrategy
128
- const primaryDim = typeof ws["primary_dimension"] === "string" ? ws["primary_dimension"] : null;
129
- if (primaryDim) {
130
- suppressedDimensions.add(primaryDim);
131
- ctx.logger?.info("CoreLoop: stall detection suppressed for dimension by active WaitStrategy", {
132
- goalId,
133
- dimension: primaryDim,
134
- waitUntil,
135
- });
136
- result.waitSuppressed = true;
137
- }
138
- }
139
- }
140
- }
141
- catch {
142
- // Non-fatal: suppression check failure does not block stall detection
143
- }
144
- }
145
- // Per-dimension stall check (skip dimensions suppressed by active WaitStrategies)
146
- for (const dim of goal.dimensions) {
147
- if (suppressedDimensions.has(dim.name))
148
- continue;
149
- const dimGapHistory = gapHistory
150
- .filter((entry) => entry.gap_vector.some((g) => g.dimension_name === dim.name))
151
- .map((entry) => {
152
- const g = entry.gap_vector.find((g) => g.dimension_name === dim.name);
153
- return { normalized_gap: g?.normalized_weighted_gap ?? 1 };
154
- });
155
- const stallReport = ctx.deps.stallDetector.checkDimensionStall(goalId, dim.name, dimGapHistory);
156
- if (stallReport) {
157
- result.stallDetected = true;
158
- result.stallReport = stallReport;
159
- // Predicted stalls are advisory — log but don't pivot/escalate
160
- if (stallReport.stall_type === "predicted_plateau" ||
161
- stallReport.stall_type === "predicted_regression") {
162
- ctx.logger?.info(`CoreLoop: early warning ${stallReport.stall_type} — monitoring, no pivot`, { goalId });
163
- continue;
164
- }
165
- const escalationLevel = await ctx.deps.stallDetector.getEscalationLevel(goalId, dim.name);
166
- await applyStallAction(ctx, goalId, goal, dimGapHistory, stallReport, escalationLevel, dim.name, result, "");
167
- break;
168
- }
169
- }
170
- // Global stall check
171
- if (!result.stallDetected) {
172
- await checkGlobalStall(ctx, goalId, goal, result, gapHistory);
173
- }
174
- // Portfolio: check rebalance after stall detection
175
- if (ctx.deps.portfolioManager) {
176
- await rebalancePortfolio(ctx, goalId, goal, result);
177
- }
178
- }
179
- catch (err) {
180
- ctx.logger?.warn("CoreLoop: stall detection failed (non-fatal)", { error: err instanceof Error ? err.message : String(err) });
181
- }
182
- }
183
- // ─── Shared stall-action helper ───
184
- /** Apply REFINE/PIVOT/ESCALATE logic for a detected stall (per-dimension or global).
185
- * @param dimHistory Gap history slice used for analysis (single-dim or first-dim for global).
186
- * @param stallReport The detected StallReport.
187
- * @param escalationLevel Current escalation level for the stall dimension.
188
- * @param incrementDimName Dimension name passed to incrementEscalation after handling.
189
- * @param logPrefix Short prefix for log messages, e.g. "" or "global ".
190
- */
191
- async function applyStallAction(ctx, goalId, goal, dimHistory, stallReport, escalationLevel, incrementDimName, result, logPrefix) {
192
- if (ctx.deps.learningPipeline) {
193
- try {
194
- await ctx.deps.learningPipeline.onStallDetected(goalId, stallReport);
195
- }
196
- catch {
197
- // non-fatal
198
- }
199
- }
200
- const activeStrategyForRecord = await Promise.resolve(ctx.deps.strategyManager.getActiveStrategy(goalId)).catch(() => null);
201
- const strategyIdForRecord = activeStrategyForRecord?.id ?? "unknown";
202
- // M14-S2: analyze stall cause to determine REFINE/PIVOT/ESCALATE
203
- // Falls back to PIVOT behavior when analyzeStallCause is unavailable
204
- const analysis = ctx.deps.stallDetector.analyzeStallCause?.(dimHistory);
205
- result.stallAnalysis = analysis;
206
- if (analysis?.recommended_action === "refine") {
207
- // REFINE: keep current strategy, just log and continue
208
- ctx.logger?.info(`CoreLoop: ${logPrefix}stall REFINE — parameter_issue detected, keeping strategy`, {
209
- goalId,
210
- evidence: analysis.evidence,
211
- });
212
- }
213
- else if (stallReport.suggested_cause === "information_deficit" && ctx.deps.goalRefiner) {
214
- // Observation-failure stall: re-refine the leaf to get better dimensions
215
- ctx.logger?.info(`CoreLoop: ${logPrefix}observation-failure stall — calling reRefineLeaf`, { goalId });
216
- try {
217
- await ctx.deps.goalRefiner.reRefineLeaf(goalId, stallReport.suggested_cause);
218
- }
219
- catch (reRefineErr) {
220
- ctx.logger?.warn(`CoreLoop: ${logPrefix}reRefineLeaf failed (non-fatal)`, {
221
- goalId,
222
- err: reRefineErr instanceof Error ? reRefineErr.message : String(reRefineErr),
223
- });
224
- }
225
- }
226
- else if (analysis?.recommended_action === "escalate") {
227
- // ESCALATE: set escalation level to max to trigger loop exit
228
- ctx.logger?.warn(`CoreLoop: ${logPrefix}stall ESCALATE — goal_unreachable detected`, {
229
- goalId,
230
- evidence: analysis.evidence,
231
- });
232
- await ctx.deps.strategyManager.onStallDetected(goalId, 3, goal.origin ?? "general");
233
- result.pivotOccurred = true;
234
- }
235
- else {
236
- // PIVOT: switch strategy, but check pivot count limit first
237
- const portfolio = await ctx.deps.strategyManager.getPortfolio(goalId);
238
- const activeStrategy = portfolio?.strategies.find((s) => s.state === "active");
239
- const pivotCount = activeStrategy?.pivot_count ?? 0;
240
- const maxPivotCount = activeStrategy?.max_pivot_count ?? 2;
241
- if (pivotCount >= maxPivotCount) {
242
- // Auto-escalate when pivot limit reached
243
- ctx.logger?.warn(`CoreLoop: ${logPrefix}stall auto-ESCALATE — pivot_count limit reached`, {
244
- goalId,
245
- pivotCount,
246
- maxPivotCount,
247
- });
248
- await ctx.deps.strategyManager.onStallDetected(goalId, 3, goal.origin ?? "general");
249
- result.pivotOccurred = true;
250
- }
251
- else {
252
- const newStrategy = await ctx.deps.strategyManager.onStallDetected(goalId, escalationLevel + 1, goal.origin ?? "general");
253
- if (newStrategy) {
254
- result.pivotOccurred = true;
255
- if (activeStrategy?.id) {
256
- try {
257
- await ctx.deps.strategyManager.incrementPivotCount(goalId, activeStrategy.id);
258
- }
259
- catch {
260
- // non-fatal
261
- }
262
- }
263
- }
264
- }
265
- }
266
- // M14-S3: Record decision (non-fatal)
267
- if (ctx.deps.knowledgeManager) {
268
- try {
269
- const latestGap = dimHistory[dimHistory.length - 1]?.normalized_gap ?? 1;
270
- await ctx.deps.knowledgeManager.recordDecision({
271
- id: randomUUID(),
272
- goal_id: goalId,
273
- goal_type: goal.origin ?? "general",
274
- strategy_id: strategyIdForRecord,
275
- hypothesis: activeStrategyForRecord?.hypothesis,
276
- decision: analysis?.recommended_action ?? "pivot",
277
- context: {
278
- gap_value: latestGap,
279
- stall_count: stallReport.escalation_level,
280
- cycle_count: dimHistory.length,
281
- trust_score: 0,
282
- },
283
- outcome: "pending",
284
- timestamp: new Date().toISOString(),
285
- what_worked: [],
286
- what_failed: [],
287
- suggested_next: [],
288
- });
289
- }
290
- catch {
291
- // non-fatal: never block the loop for decision recording
292
- }
293
- }
294
- if (incrementDimName) {
295
- await ctx.deps.stallDetector.incrementEscalation(goalId, incrementDimName);
296
- }
297
- }
298
- /** Global stall detection: check all dimensions together, handle REFINE/PIVOT/ESCALATE. */
299
- async function checkGlobalStall(ctx, goalId, goal, result, gapHistory) {
300
- const allDimGaps = new Map();
301
- for (const dim of goal.dimensions) {
302
- const dimGapHistory = gapHistory
303
- .filter((entry) => entry.gap_vector.some((g) => g.dimension_name === dim.name))
304
- .map((entry) => {
305
- const g = entry.gap_vector.find((g) => g.dimension_name === dim.name);
306
- return { normalized_gap: g?.normalized_weighted_gap ?? 1 };
307
- });
308
- allDimGaps.set(dim.name, dimGapHistory);
309
- }
310
- const globalStall = ctx.deps.stallDetector.checkGlobalStall(goalId, allDimGaps);
311
- if (!globalStall)
312
- return;
313
- result.stallDetected = true;
314
- result.stallReport = globalStall;
315
- const firstDimHistory = allDimGaps.values().next().value ?? [];
316
- const firstDimName = goal.dimensions[0]?.name ?? "";
317
- // Pass escalationLevel=1 so that escalationLevel+1=2, preserving the original global PIVOT level
318
- await applyStallAction(ctx, goalId, goal, firstDimHistory, globalStall, 1, firstDimName, result, "global ");
319
- }
320
- /** Portfolio rebalance: check for rebalance triggers and handle wait strategy expiry. */
321
- async function rebalancePortfolio(ctx, goalId, goal, result) {
322
- if (!ctx.deps.portfolioManager)
323
- return;
324
- try {
325
- const rebalanceTrigger = await ctx.deps.portfolioManager.shouldRebalance(goalId);
326
- if (rebalanceTrigger) {
327
- const rebalanceResult = await ctx.deps.portfolioManager.rebalance(goalId, rebalanceTrigger);
328
- if (rebalanceResult.new_generation_needed) {
329
- await ctx.deps.strategyManager.onStallDetected(goalId, 3, goal.origin ?? "general");
330
- }
331
- }
332
- }
333
- catch {
334
- // Portfolio rebalance errors are non-fatal
335
- }
336
- try {
337
- const portfolio = await ctx.deps.strategyManager.getPortfolio(goalId);
338
- if (portfolio) {
339
- for (const strategy of portfolio.strategies) {
340
- if (ctx.deps.portfolioManager.isWaitStrategy(strategy)) {
341
- // Gap 1: canAffordWait gate — if TimeHorizonEngine is available, check whether
342
- // the goal can afford the wait before processing WaitStrategy expiry.
343
- if (ctx.timeHorizonEngine) {
344
- try {
345
- const ws = strategy;
346
- const waitUntil = typeof ws["wait_until"] === "string" ? ws["wait_until"] : null;
347
- const startedAt = typeof ws["started_at"] === "string" ? ws["started_at"] : (goal.created_at ?? new Date().toISOString());
348
- // Remaining wait time (not total): use now as reference so nearly-expired waits pass
349
- const waitHours = waitUntil
350
- ? Math.max(0, (new Date(waitUntil).getTime() - Date.now()) / 3_600_000)
351
- : 0;
352
- const currentGap = result?.gapAggregate ?? 1;
353
- const initialGap = typeof ws["gap_snapshot_at_start"] === "number" ? ws["gap_snapshot_at_start"] : currentGap;
354
- // Compute an approximate velocity from gap progress and elapsed time.
355
- // Fallback to a small positive value (0.01/h) when elapsed is too short to measure.
356
- const elapsedHours = waitUntil
357
- ? Math.max(0, (Date.now() - new Date(startedAt).getTime()) / 3_600_000)
358
- : 0;
359
- const gapDelta = initialGap - currentGap;
360
- const velocity = elapsedHours > 0.001 && gapDelta > 0
361
- ? gapDelta / elapsedHours
362
- : 0.01; // conservative positive fallback; replace with real velocity when available
363
- const budget = ctx.timeHorizonEngine.getTimeBudget(goal.deadline ?? null, startedAt, currentGap, initialGap, velocity);
364
- if (!budget.canAffordWait(waitHours)) {
365
- ctx.logger?.info("CoreLoop: canAffordWait=false, skipping WaitStrategy processing", {
366
- goalId,
367
- strategyId: strategy.id,
368
- waitHours,
369
- });
370
- continue;
371
- }
372
- }
373
- catch {
374
- // Non-fatal: if canAffordWait check fails, proceed normally
375
- }
376
- }
377
- const waitTrigger = await ctx.deps.portfolioManager.handleWaitStrategyExpiry(goalId, strategy.id);
378
- if (waitTrigger) {
379
- await ctx.deps.portfolioManager.rebalance(goalId, waitTrigger);
380
- if (result) {
381
- result.waitExpired = true;
382
- result.waitStrategyId = strategy.id;
383
- }
384
- }
385
- }
386
- }
387
- }
388
- }
389
- catch {
390
- // WaitStrategy expiry errors are non-fatal
391
- }
392
- }
393
- // ─── Phase 6b ───
394
- /** Check dependency graph block.
395
- * Returns true if goal is blocked (result.error set, caller should return). */
396
- export function checkDependencyBlock(ctx, goalId, result) {
397
- if (ctx.deps.goalDependencyGraph) {
398
- try {
399
- if (ctx.deps.goalDependencyGraph.isBlocked(goalId)) {
400
- const blockingGoals = ctx.deps.goalDependencyGraph.getBlockingGoals(goalId);
401
- result.error = `Goal ${goalId} is blocked by prerequisites: ${blockingGoals.join(", ")}`;
402
- return true;
403
- }
404
- }
405
- catch {
406
- // Dependency graph errors are non-fatal
407
- }
408
- }
409
- return false;
410
- }
411
- /** Collect context, run task cycle, handle capability acquisition,
412
- * transfer detection, and post-task completion re-check.
413
- * Returns true on success, false if the caller should return result early.
414
- * `transferCheckCounter` is incremented via the callback to keep mutable state on CoreLoop. */
415
- export async function runTaskCycleWithContext(ctx, goalId, goal, gapVector, driveScores, highDissatisfactionDimensions, loopIndex, result, startTime, callbacks) {
416
- const { handleCapabilityAcquisition, incrementTransferCounter, tryGenerateReport } = callbacks;
417
- try {
418
- const taskStartTime = Date.now();
419
- const driveContext = buildDriveContext(goal);
420
- const adapter = ctx.deps.adapterRegistry.getAdapter(ctx.config.adapterType);
421
- const baseDir = typeof ctx.deps.stateManager.getBaseDir === "function"
422
- ? ctx.deps.stateManager.getBaseDir()
423
- : null;
424
- const dreamActivation = baseDir
425
- ? await loadDreamActivationState(baseDir).catch(() => null)
426
- : null;
427
- const activationFlags = dreamActivation?.flags;
428
- // Portfolio: select strategy for next task
429
- if (ctx.deps.portfolioManager) {
430
- try {
431
- const selectionResult = await ctx.deps.portfolioManager.selectNextStrategyForTask(goalId);
432
- if (selectionResult) {
433
- ctx.deps.taskLifecycle.setOnTaskComplete((strategyId) => {
434
- ctx.deps.portfolioManager?.recordTaskCompletion(strategyId);
435
- });
436
- }
437
- }
438
- catch {
439
- // Portfolio strategy selection is non-fatal
440
- }
441
- }
442
- // Collect knowledge context
443
- let knowledgeContext;
444
- if (ctx.deps.knowledgeManager) {
445
- try {
446
- const topDimension = driveScores[0]?.dimension_name ?? goal.dimensions[0]?.name;
447
- if (topDimension) {
448
- let entries = await ctx.deps.knowledgeManager.getRelevantKnowledge(goalId, topDimension);
449
- if (activationFlags?.semanticContext) {
450
- const semanticEntries = await ctx.deps.knowledgeManager.searchKnowledge(`${goal.title} ${goal.description} ${topDimension}`, 5).catch(() => []);
451
- entries = mergeUniqueKnowledgeEntries(entries, semanticEntries, 8);
452
- }
453
- let contradictionWarnings = [];
454
- if (activationFlags?.graphTraversal && entries.length > 0) {
455
- const graph = baseDir
456
- ? await KnowledgeGraph.create(path.join(baseDir, "knowledge", "graph.json")).catch(() => null)
457
- : null;
458
- if (graph) {
459
- const allEntries = await ctx.deps.knowledgeManager.loadKnowledge(goalId).catch(() => []);
460
- const expanded = expandKnowledgeEntriesWithGraph(entries, allEntries, graph);
461
- entries = mergeUniqueKnowledgeEntries(entries, expanded.relatedEntries, 10);
462
- contradictionWarnings = expanded.contradictionWarnings;
463
- }
464
- }
465
- if (entries.length > 0) {
466
- knowledgeContext = entries
467
- .map((e) => `Q: ${e.question}\nA: ${e.answer}`)
468
- .join("\n\n");
469
- if (contradictionWarnings.length > 0) {
470
- knowledgeContext += `\n\nContradiction warnings:\n${contradictionWarnings
471
- .map((warning) => `- ${warning}`)
472
- .join("\n")}`;
473
- }
474
- }
475
- }
476
- }
477
- catch {
478
- // Knowledge retrieval failure is non-fatal
479
- }
480
- }
481
- if (activationFlags?.crossGoalLessons && ctx.deps.memoryLifecycleManager) {
482
- try {
483
- const topDimension = driveScores[0]?.dimension_name ?? goal.dimensions[0]?.name ?? "";
484
- const lessons = await ctx.deps.memoryLifecycleManager.searchCrossGoalLessons(`${goal.title} ${goal.description} ${topDimension}`, 3);
485
- if (lessons.length > 0) {
486
- const lessonsBlock = [
487
- "Cross-goal lessons:",
488
- ...lessons.map((lesson, index) => `${index + 1}. ${lesson.lesson}`),
489
- ].join("\n");
490
- knowledgeContext = knowledgeContext ? `${knowledgeContext}\n\n${lessonsBlock}` : lessonsBlock;
491
- }
492
- }
493
- catch {
494
- // Non-fatal: proceed without cross-goal lessons.
495
- }
496
- }
497
- // Tier-aware memory selection: use highDissatisfactionDimensions and dynamic budget
498
- if (ctx.deps.memoryLifecycleManager) {
499
- try {
500
- const dimensions = goal.dimensions.map((d) => d.name);
501
- const maxDissatisfaction = driveScores.length > 0
502
- ? Math.max(...driveScores.map((s) => s.dissatisfaction))
503
- : 0;
504
- const satisfiedDimensions = goal.dimensions
505
- .filter((d) => !result.completionJudgment?.blocking_dimensions.includes(d.name))
506
- .map((d) => d.name);
507
- const tierAwareMemory = await ctx.deps.memoryLifecycleManager.selectForWorkingMemoryTierAware(goalId, dimensions, [], 10, [goalId], [], satisfiedDimensions, highDissatisfactionDimensions, maxDissatisfaction);
508
- if (activationFlags?.semanticWorkingMemory) {
509
- const topDimension = driveScores[0]?.dimension_name ?? goal.dimensions[0]?.name ?? "";
510
- const semanticMemory = await ctx.deps.memoryLifecycleManager.selectForWorkingMemorySemantic(goalId, `${goal.title} ${goal.description} ${topDimension}`, dimensions, [], 5, driveScores.map((score) => ({
511
- dimension: score.dimension_name,
512
- dissatisfaction: score.dissatisfaction,
513
- deadline: score.deadline,
514
- })));
515
- const mergedEntries = mergeWorkingMemorySelections(tierAwareMemory.shortTerm, semanticMemory.shortTerm, 5);
516
- if (mergedEntries.length > 0) {
517
- const memoryBlock = [
518
- "Working memory:",
519
- ...mergedEntries.map((entry, index) => `${index + 1}. [${entry.data_type}] ${JSON.stringify(entry.data)}`),
520
- ].join("\n");
521
- knowledgeContext = knowledgeContext ? `${knowledgeContext}\n\n${memoryBlock}` : memoryBlock;
522
- }
523
- }
524
- }
525
- catch {
526
- // Memory selection failure is non-fatal
527
- }
528
- }
529
- // Fetch existing tasks for dedup context
530
- let existingTasks;
531
- if (adapter.listExistingTasks) {
532
- try {
533
- existingTasks = await adapter.listExistingTasks();
534
- }
535
- catch {
536
- // Non-fatal: proceed without existing tasks context
537
- }
538
- }
539
- // Collect workspace context
540
- let workspaceContext;
541
- if (ctx.deps.contextProvider) {
542
- try {
543
- const topDimension = driveScores[0]?.dimension_name ?? goal.dimensions[0]?.name ?? "";
544
- workspaceContext = await ctx.deps.contextProvider(goalId, topDimension);
545
- }
546
- catch {
547
- // Non-fatal: proceed without workspace context
548
- }
549
- }
550
- ctx.logger?.debug("CoreLoop: running task cycle", { adapter: adapter.adapterType, goalId });
551
- ctx.deps.onProgress?.({
552
- iteration: loopIndex + 1,
553
- maxIterations: ctx.config.maxIterations,
554
- phase: "Executing task...",
555
- gap: result.gapAggregate,
556
- });
557
- const taskResult = await ctx.deps.taskLifecycle.runTaskCycle(goalId, gapVector, driveContext, adapter, knowledgeContext, existingTasks, workspaceContext);
558
- ctx.logger?.info("CoreLoop: task cycle result", { action: taskResult.action, taskId: taskResult.task.id });
559
- result.taskResult = taskResult;
560
- result.tokensUsed = (result.tokensUsed ?? 0) + (taskResult.tokensUsed ?? 0);
561
- ctx.deps.onProgress?.({
562
- iteration: loopIndex + 1,
563
- maxIterations: ctx.config.maxIterations,
564
- phase: "Verifying result...",
565
- gap: result.gapAggregate,
566
- taskDescription: taskResult.task.work_description
567
- ? taskResult.task.work_description.split("\n")[0]?.slice(0, 80)
568
- : undefined,
569
- });
570
- // Handle capability_acquiring
571
- if (taskResult.action === "capability_acquiring" && taskResult.acquisition_task) {
572
- const acquisitionOutcome = await handleCapabilityAcquisition(taskResult.acquisition_task, goalId, adapter);
573
- if (acquisitionOutcome?.replanRequired) {
574
- ctx.logger?.info("CoreLoop: capability acquisition requested replanning", {
575
- capabilityName: acquisitionOutcome.capabilityName,
576
- replanRequired: acquisitionOutcome.replanRequired,
577
- recommendationSource: acquisitionOutcome.recommendationSource,
578
- recommendedPlugin: acquisitionOutcome.recommendedPlugin,
579
- });
580
- ctx.deps.onProgress?.({
581
- iteration: loopIndex + 1,
582
- maxIterations: ctx.config.maxIterations,
583
- phase: "Generating task...",
584
- gap: result.gapAggregate,
585
- taskDescription: `Replanning after capability acquisition: ${acquisitionOutcome.capabilityName}`,
586
- });
587
- }
588
- }
589
- // Portfolio: record task completion
590
- if (ctx.deps.portfolioManager && taskResult.action === "completed" && taskResult.task.strategy_id) {
591
- try {
592
- ctx.deps.portfolioManager.recordTaskCompletion(taskResult.task.strategy_id);
593
- }
594
- catch {
595
- // Non-fatal
596
- }
597
- }
598
- // Phase 7: tool-based verification (Layer 1)
599
- if (ctx.toolExecutor && taskResult.task.success_criteria.length > 0) {
600
- try {
601
- const toolCtx = await buildLoopToolContext(ctx, goalId);
602
- const verificationResult = await verifyWithTools(taskResult.task.success_criteria, ctx.toolExecutor, toolCtx);
603
- if (!verificationResult.mechanicalPassed) {
604
- taskResult.verificationResult = { ...taskResult.verificationResult, verdict: "fail" };
605
- ctx.logger?.info("CoreLoop Phase 7: tool verification failed", {
606
- taskId: taskResult.task.id,
607
- details: verificationResult.details,
608
- });
609
- }
610
- result.toolVerification = verificationResult;
611
- // Feed execution results back to strategy for scoring
612
- if (typeof ctx.deps.strategyManager.recordExecutionFeedback === 'function') {
613
- const activeStrat = await ctx.deps.strategyManager.getActiveStrategy(goalId);
614
- if (activeStrat) {
615
- ctx.deps.strategyManager.recordExecutionFeedback({
616
- strategyId: activeStrat.hypothesis,
617
- taskId: taskResult.task?.id ?? 'unknown',
618
- success: taskResult.action === 'completed',
619
- verificationPassed: verificationResult.mechanicalPassed,
620
- duration_ms: Date.now() - taskStartTime,
621
- timestamp: Date.now(),
622
- });
623
- }
624
- }
625
- }
626
- catch (err) {
627
- ctx.logger?.warn("CoreLoop Phase 7: tool verification threw (non-fatal)", {
628
- error: err instanceof Error ? err.message : String(err),
629
- });
630
- }
631
- }
632
- // Re-check completion after task execution
633
- const updatedGoal = await ctx.deps.stateManager.loadGoal(goalId);
634
- if (updatedGoal) {
635
- const postTaskJudgment = updatedGoal.children_ids.length > 0
636
- ? await ctx.deps.satisficingJudge.judgeTreeCompletion(updatedGoal.id)
637
- : ctx.deps.satisficingJudge.isGoalComplete(updatedGoal);
638
- result.completionJudgment = postTaskJudgment;
639
- }
640
- }
641
- catch (err) {
642
- result.error = `Task cycle failed: ${err instanceof Error ? err.message : String(err)}`;
643
- ctx.logger?.error(`CoreLoop: ${result.error}`, { goalId });
644
- result.elapsedMs = Date.now() - startTime;
645
- tryGenerateReport(goalId, loopIndex, result, goal);
646
- return false;
647
- }
648
- // Track curiosity goal loop count
649
- if (ctx.deps.curiosityEngine) {
650
- const currentGoal = await ctx.deps.stateManager.loadGoal(goalId);
651
- if (currentGoal?.origin === "curiosity") {
652
- ctx.deps.curiosityEngine.incrementLoopCount(goalId);
653
- }
654
- }
655
- // Transfer Detection (every 5 iterations, suggestion-only)
656
- const transferCount = incrementTransferCounter();
657
- if (ctx.deps.knowledgeTransfer && transferCount % 5 === 0) {
658
- try {
659
- const candidates = await ctx.deps.knowledgeTransfer.detectTransferOpportunities(goalId);
660
- if (candidates.length > 0) {
661
- result.transfer_candidates = candidates;
662
- }
663
- }
664
- catch {
665
- // non-fatal
666
- }
667
- }
668
- return true;
669
- }
1
+ export * from "./core-loop/task-cycle.js";
670
2
  //# sourceMappingURL=core-loop-phases-b.js.map