@caupulican/pi-adaptative 0.94.1 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (324) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +32 -13
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +7 -4
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +173 -293
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +247 -392
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.d.ts +52 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.d.ts.map +1 -0
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.js +118 -0
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.js.map +1 -0
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/launch-profile.ts +169 -0
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +1 -1
  14. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +1 -1
  15. package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +13 -7
  16. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +11 -11
  17. package/dist/core/agent-session.d.ts +11 -41
  18. package/dist/core/agent-session.d.ts.map +1 -1
  19. package/dist/core/agent-session.js +93 -160
  20. package/dist/core/agent-session.js.map +1 -1
  21. package/dist/core/autonomy/envelope-enforcement.d.ts +6 -1
  22. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  23. package/dist/core/autonomy/envelope-enforcement.js +26 -25
  24. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  25. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -1
  26. package/dist/core/autonomy/lane-private-paths.js +2 -1
  27. package/dist/core/autonomy/lane-private-paths.js.map +1 -1
  28. package/dist/core/autonomy/lane-tool-surface.d.ts +8 -8
  29. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  30. package/dist/core/autonomy/lane-tool-surface.js +45 -30
  31. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  32. package/dist/core/autonomy/worker-session-private-scope.d.ts +12 -0
  33. package/dist/core/autonomy/worker-session-private-scope.d.ts.map +1 -0
  34. package/dist/core/autonomy/worker-session-private-scope.js +42 -0
  35. package/dist/core/autonomy/worker-session-private-scope.js.map +1 -0
  36. package/dist/core/autonomy/worker-tool-adapter-registry.d.ts +65 -0
  37. package/dist/core/autonomy/worker-tool-adapter-registry.d.ts.map +1 -0
  38. package/dist/core/autonomy/worker-tool-adapter-registry.js +145 -0
  39. package/dist/core/autonomy/worker-tool-adapter-registry.js.map +1 -0
  40. package/dist/core/background-lane-controller.d.ts +1 -1
  41. package/dist/core/background-lane-controller.d.ts.map +1 -1
  42. package/dist/core/background-lane-controller.js +1 -1
  43. package/dist/core/background-lane-controller.js.map +1 -1
  44. package/dist/core/background-tool-task-controller.d.ts +8 -2
  45. package/dist/core/background-tool-task-controller.d.ts.map +1 -1
  46. package/dist/core/background-tool-task-controller.js +10 -2
  47. package/dist/core/background-tool-task-controller.js.map +1 -1
  48. package/dist/core/cost-guard-controller.d.ts +37 -0
  49. package/dist/core/cost-guard-controller.d.ts.map +1 -0
  50. package/dist/core/cost-guard-controller.js +71 -0
  51. package/dist/core/cost-guard-controller.js.map +1 -0
  52. package/dist/core/cost-guard.d.ts +9 -4
  53. package/dist/core/cost-guard.d.ts.map +1 -1
  54. package/dist/core/cost-guard.js +7 -3
  55. package/dist/core/cost-guard.js.map +1 -1
  56. package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
  57. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  58. package/dist/core/delegation/worker-attempt-executor.js +0 -1
  59. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  60. package/dist/core/delegation/worker-authority-resolver.d.ts +16 -3
  61. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  62. package/dist/core/delegation/worker-authority-resolver.js +114 -55
  63. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  64. package/dist/core/delegation/worker-claim.d.ts +1 -2
  65. package/dist/core/delegation/worker-claim.d.ts.map +1 -1
  66. package/dist/core/delegation/worker-claim.js.map +1 -1
  67. package/dist/core/delegation/worker-delegation-controller.d.ts +19 -6
  68. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  69. package/dist/core/delegation/worker-delegation-controller.js +125 -40
  70. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  71. package/dist/core/delegation/worker-delegation-request.d.ts +3 -3
  72. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  73. package/dist/core/delegation/worker-delegation-request.js +13 -19
  74. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  75. package/dist/core/delegation/worker-execution-policy.d.ts +3 -2
  76. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  77. package/dist/core/delegation/worker-execution-policy.js +54 -39
  78. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  79. package/dist/core/delegation/worker-fleet-limits.d.ts +3 -3
  80. package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -1
  81. package/dist/core/delegation/worker-fleet-limits.js +7 -7
  82. package/dist/core/delegation/worker-fleet-limits.js.map +1 -1
  83. package/dist/core/delegation/worker-machine-scope.d.ts +12 -0
  84. package/dist/core/delegation/worker-machine-scope.d.ts.map +1 -0
  85. package/dist/core/delegation/worker-machine-scope.js +38 -0
  86. package/dist/core/delegation/worker-machine-scope.js.map +1 -0
  87. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  88. package/dist/core/delegation/worker-recovery-coordinator.js +6 -1
  89. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  90. package/dist/core/delegation/worker-runner.d.ts +5 -7
  91. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  92. package/dist/core/delegation/worker-runner.js +1 -4
  93. package/dist/core/delegation/worker-runner.js.map +1 -1
  94. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts +3 -2
  95. package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
  96. package/dist/core/delegation/worker-write-reservation-coordinator.js +50 -25
  97. package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
  98. package/dist/core/durable-custom-message-turn-controller.d.ts +6 -0
  99. package/dist/core/durable-custom-message-turn-controller.d.ts.map +1 -1
  100. package/dist/core/durable-custom-message-turn-controller.js +38 -15
  101. package/dist/core/durable-custom-message-turn-controller.js.map +1 -1
  102. package/dist/core/extension-binding-controller.d.ts +5 -1
  103. package/dist/core/extension-binding-controller.d.ts.map +1 -1
  104. package/dist/core/extension-binding-controller.js +15 -0
  105. package/dist/core/extension-binding-controller.js.map +1 -1
  106. package/dist/core/extensions/factory-runtime.d.ts.map +1 -1
  107. package/dist/core/extensions/factory-runtime.js +5 -0
  108. package/dist/core/extensions/factory-runtime.js.map +1 -1
  109. package/dist/core/extensions/runner.d.ts.map +1 -1
  110. package/dist/core/extensions/runner.js +1 -0
  111. package/dist/core/extensions/runner.js.map +1 -1
  112. package/dist/core/extensions/types.d.ts +8 -4
  113. package/dist/core/extensions/types.d.ts.map +1 -1
  114. package/dist/core/extensions/types.js.map +1 -1
  115. package/dist/core/foreground-terminal-handoff-controller.d.ts +14 -0
  116. package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
  117. package/dist/core/foreground-terminal-handoff-controller.js +188 -72
  118. package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
  119. package/dist/core/goals/goal-session-controller.d.ts +2 -0
  120. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  121. package/dist/core/goals/goal-session-controller.js +8 -0
  122. package/dist/core/goals/goal-session-controller.js.map +1 -1
  123. package/dist/core/goals/goal-tool-core.d.ts +5 -4
  124. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  125. package/dist/core/goals/goal-tool-core.js +23 -19
  126. package/dist/core/goals/goal-tool-core.js.map +1 -1
  127. package/dist/core/learning/auto-learn-settings.d.ts +84 -0
  128. package/dist/core/learning/auto-learn-settings.d.ts.map +1 -0
  129. package/dist/core/learning/auto-learn-settings.js +66 -0
  130. package/dist/core/learning/auto-learn-settings.js.map +1 -0
  131. package/dist/core/learning/reflection-engine.d.ts +4 -0
  132. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  133. package/dist/core/learning/reflection-engine.js +48 -10
  134. package/dist/core/learning/reflection-engine.js.map +1 -1
  135. package/dist/core/local-prefix-warm-controller.d.ts +24 -0
  136. package/dist/core/local-prefix-warm-controller.d.ts.map +1 -0
  137. package/dist/core/local-prefix-warm-controller.js +79 -0
  138. package/dist/core/local-prefix-warm-controller.js.map +1 -0
  139. package/dist/core/memory/providers/file-store.d.ts +2 -0
  140. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  141. package/dist/core/memory/providers/file-store.js +71 -15
  142. package/dist/core/memory/providers/file-store.js.map +1 -1
  143. package/dist/core/memory/worker-memory-tools.d.ts +5 -0
  144. package/dist/core/memory/worker-memory-tools.d.ts.map +1 -0
  145. package/dist/core/memory/worker-memory-tools.js +5 -0
  146. package/dist/core/memory/worker-memory-tools.js.map +1 -0
  147. package/dist/core/model-capability.d.ts +7 -0
  148. package/dist/core/model-capability.d.ts.map +1 -1
  149. package/dist/core/model-capability.js +12 -0
  150. package/dist/core/model-capability.js.map +1 -1
  151. package/dist/core/model-registry.d.ts.map +1 -1
  152. package/dist/core/model-registry.js +2 -10
  153. package/dist/core/model-registry.js.map +1 -1
  154. package/dist/core/model-router-controller.d.ts +3 -2
  155. package/dist/core/model-router-controller.d.ts.map +1 -1
  156. package/dist/core/model-router-controller.js +3 -2
  157. package/dist/core/model-router-controller.js.map +1 -1
  158. package/dist/core/orchestration/contracts.d.ts +16 -12
  159. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  160. package/dist/core/orchestration/contracts.js +2 -2
  161. package/dist/core/orchestration/contracts.js.map +1 -1
  162. package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
  163. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  164. package/dist/core/orchestration/lane-tool-manifests.js +6 -1
  165. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  166. package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
  167. package/dist/core/orchestration/profile-registry.js +14 -0
  168. package/dist/core/orchestration/profile-registry.js.map +1 -1
  169. package/dist/core/orchestration/task-profile-writer.d.ts +7 -4
  170. package/dist/core/orchestration/task-profile-writer.d.ts.map +1 -1
  171. package/dist/core/orchestration/task-profile-writer.js +71 -59
  172. package/dist/core/orchestration/task-profile-writer.js.map +1 -1
  173. package/dist/core/orchestration/thinking-level-schema.d.ts +7 -0
  174. package/dist/core/orchestration/thinking-level-schema.d.ts.map +1 -0
  175. package/dist/core/orchestration/thinking-level-schema.js +19 -0
  176. package/dist/core/orchestration/thinking-level-schema.js.map +1 -0
  177. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  178. package/dist/core/orchestration/worker-execution-contract.js +12 -5
  179. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  180. package/dist/core/provider-prompt-contracts.d.ts +1 -4
  181. package/dist/core/provider-prompt-contracts.d.ts.map +1 -1
  182. package/dist/core/provider-prompt-contracts.js +4 -10
  183. package/dist/core/provider-prompt-contracts.js.map +1 -1
  184. package/dist/core/provider-request-context-controller.d.ts +2 -0
  185. package/dist/core/provider-request-context-controller.d.ts.map +1 -1
  186. package/dist/core/provider-request-context-controller.js +10 -3
  187. package/dist/core/provider-request-context-controller.js.map +1 -1
  188. package/dist/core/reflection-controller.d.ts +56 -27
  189. package/dist/core/reflection-controller.d.ts.map +1 -1
  190. package/dist/core/reflection-controller.js +206 -117
  191. package/dist/core/reflection-controller.js.map +1 -1
  192. package/dist/core/runtime-builder.d.ts +1 -0
  193. package/dist/core/runtime-builder.d.ts.map +1 -1
  194. package/dist/core/runtime-builder.js +25 -14
  195. package/dist/core/runtime-builder.js.map +1 -1
  196. package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
  197. package/dist/core/secrets/credential-exposure-guard.js +55 -10
  198. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  199. package/dist/core/session-role.d.ts +6 -8
  200. package/dist/core/session-role.d.ts.map +1 -1
  201. package/dist/core/session-role.js +8 -18
  202. package/dist/core/session-role.js.map +1 -1
  203. package/dist/core/settings-manager.d.ts +13 -16
  204. package/dist/core/settings-manager.d.ts.map +1 -1
  205. package/dist/core/settings-manager.js +53 -50
  206. package/dist/core/settings-manager.js.map +1 -1
  207. package/dist/core/skill-vault.d.ts +15 -0
  208. package/dist/core/skill-vault.d.ts.map +1 -1
  209. package/dist/core/skill-vault.js +79 -45
  210. package/dist/core/skill-vault.js.map +1 -1
  211. package/dist/core/skills.d.ts +3 -0
  212. package/dist/core/skills.d.ts.map +1 -1
  213. package/dist/core/skills.js +6 -6
  214. package/dist/core/skills.js.map +1 -1
  215. package/dist/core/system-prompt-builder.d.ts +2 -0
  216. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  217. package/dist/core/system-prompt-builder.js +52 -12
  218. package/dist/core/system-prompt-builder.js.map +1 -1
  219. package/dist/core/system-prompt.js +1 -1
  220. package/dist/core/system-prompt.js.map +1 -1
  221. package/dist/core/tool-capability-policy.d.ts +3 -0
  222. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  223. package/dist/core/tool-capability-policy.js +13 -2
  224. package/dist/core/tool-capability-policy.js.map +1 -1
  225. package/dist/core/toolkit/script-runner.d.ts +2 -1
  226. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  227. package/dist/core/toolkit/script-runner.js +10 -2
  228. package/dist/core/toolkit/script-runner.js.map +1 -1
  229. package/dist/core/tools/delegate-status.d.ts +1 -1
  230. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  231. package/dist/core/tools/delegate-status.js +1 -1
  232. package/dist/core/tools/delegate-status.js.map +1 -1
  233. package/dist/core/tools/delegate.d.ts +4 -15
  234. package/dist/core/tools/delegate.d.ts.map +1 -1
  235. package/dist/core/tools/delegate.js +111 -73
  236. package/dist/core/tools/delegate.js.map +1 -1
  237. package/dist/core/tools/goal.d.ts +3 -4
  238. package/dist/core/tools/goal.d.ts.map +1 -1
  239. package/dist/core/tools/goal.js +24 -7
  240. package/dist/core/tools/goal.js.map +1 -1
  241. package/dist/core/tools/profile-writer.d.ts +2 -8
  242. package/dist/core/tools/profile-writer.d.ts.map +1 -1
  243. package/dist/core/tools/profile-writer.js +6 -18
  244. package/dist/core/tools/profile-writer.js.map +1 -1
  245. package/dist/core/tools/run-toolkit-script.d.ts +1 -1
  246. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
  247. package/dist/core/tools/run-toolkit-script.js +2 -2
  248. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  249. package/dist/core/tools/skill-audit.d.ts +28 -1
  250. package/dist/core/tools/skill-audit.d.ts.map +1 -1
  251. package/dist/core/tools/skill-audit.js +56 -12
  252. package/dist/core/tools/skill-audit.js.map +1 -1
  253. package/dist/core/tools/skill.d.ts +12 -1
  254. package/dist/core/tools/skill.d.ts.map +1 -1
  255. package/dist/core/tools/skill.js +52 -0
  256. package/dist/core/tools/skill.js.map +1 -1
  257. package/dist/core/tools/skillify.d.ts.map +1 -1
  258. package/dist/core/tools/skillify.js +16 -7
  259. package/dist/core/tools/skillify.js.map +1 -1
  260. package/dist/core/tools/task-steps.js +1 -1
  261. package/dist/core/tools/task-steps.js.map +1 -1
  262. package/dist/core/tools/tmux-dispatch.d.ts +4 -16
  263. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  264. package/dist/core/tools/tmux-dispatch.js +5 -20
  265. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  266. package/dist/core/worktree-sync/codes.d.ts +1 -2
  267. package/dist/core/worktree-sync/codes.d.ts.map +1 -1
  268. package/dist/core/worktree-sync/codes.js +1 -2
  269. package/dist/core/worktree-sync/codes.js.map +1 -1
  270. package/dist/core/worktree-sync/lane-gate.d.ts +4 -8
  271. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -1
  272. package/dist/core/worktree-sync/lane-gate.js +5 -51
  273. package/dist/core/worktree-sync/lane-gate.js.map +1 -1
  274. package/dist/index.d.ts +5 -0
  275. package/dist/index.d.ts.map +1 -1
  276. package/dist/index.js +7 -0
  277. package/dist/index.js.map +1 -1
  278. package/dist/modes/interactive/auto-learn-controller.d.ts +6 -7
  279. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  280. package/dist/modes/interactive/auto-learn-controller.js +30 -207
  281. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  282. package/dist/modes/interactive/autonomy-commands.js +2 -2
  283. package/dist/modes/interactive/autonomy-commands.js.map +1 -1
  284. package/dist/modes/interactive/components/custom-message.js +17 -0
  285. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  286. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  287. package/dist/modes/interactive/components/fitness-role-selector.js +2 -2
  288. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  289. package/dist/modes/interactive/components/footer.js +1 -1
  290. package/dist/modes/interactive/components/footer.js.map +1 -1
  291. package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
  292. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/settings-selector.js +150 -73
  294. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  295. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  296. package/dist/modes/interactive/report-commands.js +8 -4
  297. package/dist/modes/interactive/report-commands.js.map +1 -1
  298. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
  299. package/dist/modes/interactive/settings-selector-flow.js +10 -0
  300. package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
  301. package/docs/extensions.md +8 -0
  302. package/docs/harness-architecture.md +28 -32
  303. package/docs/index.md +1 -1
  304. package/docs/process-matrix.md +8 -6
  305. package/docs/resources.md +1 -1
  306. package/docs/settings.md +61 -51
  307. package/docs/tmux-agent-manager.md +47 -40
  308. package/docs/usage.md +1 -1
  309. package/docs/worker-profiles.md +8 -6
  310. package/docs/worktree-sync.md +26 -20
  311. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  312. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  313. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  314. package/examples/extensions/sandbox/package-lock.json +2 -2
  315. package/examples/extensions/sandbox/package.json +1 -1
  316. package/examples/extensions/with-deps/package-lock.json +2 -2
  317. package/examples/extensions/with-deps/package.json +1 -1
  318. package/npm-shrinkwrap.json +12 -12
  319. package/package.json +4 -4
  320. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +0 -133
  321. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +0 -1
  322. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +0 -199
  323. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +0 -1
  324. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +0 -312
@@ -1 +1 @@
1
- {"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAuB,MAAM,mCAAmC,CAAC;AAGvG,OAAO,EAKN,gCAAgC,GAEhC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE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,KAAK,kBAAkB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;QACtF,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;IAEO,iBAAiB,CAAC,MAAc;QACvC,IAAI,CAAC,cAAc,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAEO,cAAc,CAAC,MAAsD,EAAE,MAAc;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport { MAX_SESSION_ENTRY_VISIT_COUNT, type SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, AgentRunawayStopInfo } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport {\n\ttype GoalContinuationLoopOptions,\n\ttype GoalContinuationLoopResult,\n\ttype GoalContinuationOnceOptions,\n\ttype GoalContinuationOnceResult,\n\tisInterruptedAssistantStopReason,\n\ttype PromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport {\n\ttype ExplicitGoalStartAuthority,\n\tparseExplicitChatGoal,\n\tpriorUserPromptText,\n} from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\ninterface QueuedOwnerChatGoal {\n\ttext: string;\n\tauthority: ExplicitGoalStartAuthority;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\tprivate readonly queuedOwnerChatGoals = new WeakMap<AgentMessage, QueuedOwnerChatGoal>();\n\tprivate queuedOwnerChatExecutionLease: GoalExecutionLease | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: async (text, options) => {\n\t\t\t\tconst firstTurnEntryIndex = this.deps.getSessionManager().getEntryCount();\n\t\t\t\tawait this.deps.prompt(text, options);\n\t\t\t\treturn this.getContinuationTurnOutcome(firstTurnEntryIndex);\n\t\t\t},\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tprivate getContinuationTurnOutcome(firstTurnEntryIndex: number): \"completed\" | \"interrupted\" {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst endIndex = sessionManager.getEntryCount();\n\t\tlet nextIndex = firstTurnEntryIndex;\n\t\tlet lastAssistantStopReason: AssistantMessage[\"stopReason\"] | undefined;\n\t\twhile (nextIndex < endIndex) {\n\t\t\tconst visitCount = Math.min(MAX_SESSION_ENTRY_VISIT_COUNT, endIndex - nextIndex);\n\t\t\tnextIndex = sessionManager.visitEntries(nextIndex, visitCount, (entry) => {\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tlastAssistantStopReason = entry.message.stopReason;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn isInterruptedAssistantStopReason(lastAssistantStopReason) ? \"interrupted\" : \"completed\";\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): ChatGoalAdmission {\n\t\treturn this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));\n\t}\n\n\tstartOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): string | undefined {\n\t\tconst admission = this.admitOwnerChatGoal(text, messages);\n\t\tif (admission.status === \"started\") return admission.state.goalId;\n\t\tif (admission.status === \"unfinished_goal_exists\") {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tqueueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void {\n\t\tthis.queuedOwnerChatGoals.set(message, { text, authority });\n\t}\n\n\tactivateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly { role: string; content?: unknown }[]): void {\n\t\tconst queued = this.queuedOwnerChatGoals.get(message);\n\t\tif (!queued) return;\n\t\tthis.queuedOwnerChatGoals.delete(message);\n\t\tconst goalId = this.startOwnerChatGoal(queued.text, messages);\n\t\tif (!goalId) return;\n\t\tthis.setStartAuthority(queued.authority);\n\t\tconst lease = this.beginExecution(goalId);\n\t\tif (!lease) {\n\t\t\tthis.setStartAuthority(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.queuedOwnerChatExecutionLease = lease;\n\t}\n\n\tendQueuedOwnerChatGoalExecution(): void {\n\t\tconst lease = this.queuedOwnerChatExecutionLease;\n\t\tif (!lease) return;\n\t\tthis.queuedOwnerChatExecutionLease = undefined;\n\t\tthis.setStartAuthority(undefined);\n\t\tthis.endExecution(lease);\n\t}\n\n\tadmitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission {\n\t\tconst admittedAt = now ?? new Date().toISOString();\n\t\tconst parsed = parseExplicitChatGoal(text, priorUserText);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${admittedAt}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tadmittedAt,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */\n\trecordContinuationTelemetry(pass: { turns: number; wallClockMs: number }): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\t/** Attribute one host-driven pass and derive stall state from the authoritative revision. */\n\tprivate recordContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\tprivate persistContinuationPass(\n\t\tpass: { turns: number; wallClockMs: number } & Partial<\n\t\t\tPick<GoalState, \"goalId\" | \"progressRevision\" | \"stallTurns\">\n\t\t>,\n\t): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tif (pass.goalId !== undefined && state.goalId !== pass.goalId) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal continuation accounting skipped because goal '${pass.goalId}' was replaced by '${state.goalId}' during the pass.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst now = new Date().toISOString();\n\t\tlet updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow,\n\t\t});\n\t\tif (\n\t\t\tpass.progressRevision !== undefined &&\n\t\t\tpass.stallTurns !== undefined &&\n\t\t\tisGoalExecutionActive(state.status) &&\n\t\t\t(state.progressRevision ?? 0) <= pass.progressRevision &&\n\t\t\tstate.stallTurns <= pass.stallTurns\n\t\t) {\n\t\t\tupdated = applyGoalEvent(updated, { type: \"no_progress\", now });\n\t\t}\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(_input: { tokenBudget?: number }): number | null {\n\t\treturn this.startAuthority?.tokenBudget ?? null;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkHarnessGuardBlocked(info: AgentRunawayStopInfo): boolean {\n\t\tconst reason =\n\t\t\tinfo.reason === \"provider_turn_limit\"\n\t\t\t\t? `provider_turn_limit: reached the explicit ${info.repeats}-request provider-turn limit`\n\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\treturn this.stopActiveGoal(\"blocked\", reason);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
1
+ {"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAuB,MAAM,mCAAmC,CAAC;AAGvG,OAAO,EAKN,gCAAgC,GAEhC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;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,CAAC,CAAC;QACvE,MAAM,UAAU,GAAG,eAAe,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;QACxF,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,KAAK,kBAAkB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;QACtF,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;IAEO,iBAAiB,CAAC,MAAc;QACvC,IAAI,CAAC,cAAc,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAEO,cAAc,CAAC,MAAsD,EAAE,MAAc;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport { MAX_SESSION_ENTRY_VISIT_COUNT, type SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, AgentRunawayStopInfo } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport {\n\ttype GoalContinuationLoopOptions,\n\ttype GoalContinuationLoopResult,\n\ttype GoalContinuationOnceOptions,\n\ttype GoalContinuationOnceResult,\n\tisInterruptedAssistantStopReason,\n\ttype PromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport {\n\ttype ExplicitGoalStartAuthority,\n\tparseExplicitChatGoal,\n\tpriorUserPromptText,\n} from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\ninterface QueuedOwnerChatGoal {\n\ttext: string;\n\tauthority: ExplicitGoalStartAuthority;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\tprivate readonly queuedOwnerChatGoals = new WeakMap<AgentMessage, QueuedOwnerChatGoal>();\n\tprivate queuedOwnerChatExecutionLease: GoalExecutionLease | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: async (text, options) => {\n\t\t\t\tconst firstTurnEntryIndex = this.deps.getSessionManager().getEntryCount();\n\t\t\t\tawait this.deps.prompt(text, options);\n\t\t\t\treturn this.getContinuationTurnOutcome(firstTurnEntryIndex);\n\t\t\t},\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tprivate getContinuationTurnOutcome(firstTurnEntryIndex: number): \"completed\" | \"interrupted\" {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst endIndex = sessionManager.getEntryCount();\n\t\tlet nextIndex = firstTurnEntryIndex;\n\t\tlet lastAssistantStopReason: AssistantMessage[\"stopReason\"] | undefined;\n\t\twhile (nextIndex < endIndex) {\n\t\t\tconst visitCount = Math.min(MAX_SESSION_ENTRY_VISIT_COUNT, endIndex - nextIndex);\n\t\t\tnextIndex = sessionManager.visitEntries(nextIndex, visitCount, (entry) => {\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tlastAssistantStopReason = entry.message.stopReason;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn isInterruptedAssistantStopReason(lastAssistantStopReason) ? \"interrupted\" : \"completed\";\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): ChatGoalAdmission {\n\t\treturn this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));\n\t}\n\n\tstartOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): string | undefined {\n\t\tconst admission = this.admitOwnerChatGoal(text, messages);\n\t\tif (admission.status === \"started\") return admission.state.goalId;\n\t\tif (admission.status === \"unfinished_goal_exists\") {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tqueueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void {\n\t\tthis.queuedOwnerChatGoals.set(message, { text, authority });\n\t}\n\n\tactivateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly { role: string; content?: unknown }[]): void {\n\t\tconst queued = this.queuedOwnerChatGoals.get(message);\n\t\tif (!queued) return;\n\t\tthis.queuedOwnerChatGoals.delete(message);\n\t\tconst goalId = this.startOwnerChatGoal(queued.text, messages);\n\t\tif (!goalId) return;\n\t\tthis.setStartAuthority(queued.authority);\n\t\tconst lease = this.beginExecution(goalId);\n\t\tif (!lease) {\n\t\t\tthis.setStartAuthority(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.queuedOwnerChatExecutionLease = lease;\n\t}\n\n\tendQueuedOwnerChatGoalExecution(): void {\n\t\tconst lease = this.queuedOwnerChatExecutionLease;\n\t\tif (!lease) return;\n\t\tthis.queuedOwnerChatExecutionLease = undefined;\n\t\tthis.setStartAuthority(undefined);\n\t\tthis.endExecution(lease);\n\t}\n\n\tadmitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission {\n\t\tconst admittedAt = now ?? new Date().toISOString();\n\t\tconst parsed = parseExplicitChatGoal(text, priorUserText);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${admittedAt}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tadmittedAt,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */\n\trecordContinuationTelemetry(pass: { turns: number; wallClockMs: number }): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\t/** Attribute one host-driven pass and derive stall state from the authoritative revision. */\n\tprivate recordContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\tprivate persistContinuationPass(\n\t\tpass: { turns: number; wallClockMs: number } & Partial<\n\t\t\tPick<GoalState, \"goalId\" | \"progressRevision\" | \"stallTurns\">\n\t\t>,\n\t): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tif (pass.goalId !== undefined && state.goalId !== pass.goalId) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal continuation accounting skipped because goal '${pass.goalId}' was replaced by '${state.goalId}' during the pass.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst now = new Date().toISOString();\n\t\tlet updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow,\n\t\t});\n\t\tif (\n\t\t\tpass.progressRevision !== undefined &&\n\t\t\tpass.stallTurns !== undefined &&\n\t\t\tisGoalExecutionActive(state.status) &&\n\t\t\t(state.progressRevision ?? 0) <= pass.progressRevision &&\n\t\t\tstate.stallTurns <= pass.stallTurns\n\t\t) {\n\t\t\tupdated = applyGoalEvent(updated, { type: \"no_progress\", now });\n\t\t}\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Goal identity authoritatively owned by the current foreground execution, if one was adopted. */\n\tgetExecutionGoalId(): string | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.resolveExecutionState(lease);\n\t\treturn lease.goalId;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(_input: { tokenBudget?: number }): number | null {\n\t\treturn this.startAuthority?.tokenBudget ?? null;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkHarnessGuardBlocked(info: AgentRunawayStopInfo): boolean {\n\t\tconst reason =\n\t\t\tinfo.reason === \"provider_turn_limit\"\n\t\t\t\t? `provider_turn_limit: reached the explicit ${info.repeats}-request provider-turn limit`\n\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\treturn this.stopActiveGoal(\"blocked\", reason);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
@@ -85,19 +85,20 @@ export interface ApplyGoalActionOptions {
85
85
  */
86
86
  requireVerifiedEvidenceForCompletion?: boolean;
87
87
  /**
88
- * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of
89
- * these still reference a requirement of the goal being closed.
88
+ * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any remain.
90
89
  */
91
90
  openTaskSteps?: readonly OpenTaskStepRef[];
92
- /** Live background tool_task records used to re-check kind:"tool" evidence at complete time. */
91
+ /** Live background tool_task records used to gate goal-owned work and re-check tool evidence. */
93
92
  backgroundToolTasks?: readonly BackgroundToolTaskRef[];
94
- /** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */
93
+ /** Active ICM pipeline run; agent complete refuses while any active run remains. */
95
94
  activePipeline?: {
96
95
  runId: string;
97
96
  pipelineName: string;
98
97
  goalId?: string;
99
98
  status: string;
100
99
  };
100
+ /** Queued/running worker lanes owned by this goal or bound to one of its requirements. */
101
+ activeGoalLaneIds?: readonly string[];
101
102
  }
102
103
  /**
103
104
  * Apply one agent-facing goal action to the current ledger state.
@@ -1 +1 @@
1
- {"version":3,"file":"goal-tool-core.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,qBAAqB,EAA0B,MAAM,uCAAuC,CAAC;AAI3G,OAAO,EAIN,KAAK,gBAAgB,EACrB,KAAK,SAAS,EAId,MAAM,iBAAiB,CAAC;AASzB;;;;;;;;;GASG;AACH,MAAM,MAAM,UAAU,GACnB;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAC3E;IAAE,MAAM,EAAE,iBAAiB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACpG;IAAE,MAAM,EAAE,qBAAqB,CAAC;IAAC,a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MG;AACH,wBAAgB,eAAe,CAC9B,OAAO,EAAE,SAAS,GAAG,SAAS,EAC9B,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,sBAAsB,GAC9B,gBAAgB,CA2DlB;AAiND;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,SAAS,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,gBAAgB,CAWlG;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,SAAS,EAChB,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,UAAU,CAAC;IAAC,aAAa,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;CAAE,GAC3E,MAAM,CAeR;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAuBD;;;GAGG;AACH,wBAAgB,mCAAmC,CAClD,KAAK,EAAE,SAAS,EAChB,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,aAAa,EAAE,SAAS,eAAe,EAAE,GACvC,MAAM,EAAE,CAcV;AAED;;;;;GAKG;AACH,wBAAgB,kCAAkC,CACjD,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,SAAS,EAChB,aAAa,EAAE,SAAS,eAAe,EAAE,GAAG,SAAS,GACnD,MAAM,EAAE,CAYV"}
@@ -230,30 +230,34 @@ function toGoalEvent(state, action, now, options) {
230
230
  .join(", ")}).`,
231
231
  };
232
232
  }
233
+ const activeGoalLaneIds = [...new Set(options?.activeGoalLaneIds ?? [])];
234
+ if (activeGoalLaneIds.length > 0) {
235
+ return {
236
+ ok: false,
237
+ error: `Cannot complete goal: goal-owned worker lane(s) are still active (${activeGoalLaneIds.join(", ")}). Wait for their terminal handoffs or explicitly cancel them first.`,
238
+ };
239
+ }
233
240
  const requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;
234
- const linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);
235
- if (linkedOpenSteps.length > 0) {
241
+ const openStepIds = findOpenTaskStepIds(options?.openTaskSteps);
242
+ if (openStepIds.length > 0) {
236
243
  return {
237
244
  ok: false,
238
- error: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(", ")}). Update them via task_steps first.`,
245
+ error: `Cannot complete goal: open task_steps work remains (${openStepIds.join(", ")}). Complete or explicitly cancel those steps first.`,
239
246
  };
240
247
  }
241
- const pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);
248
+ const pendingToolTasks = findBlockingToolTasks(state, options?.backgroundToolTasks);
242
249
  if (pendingToolTasks.length > 0) {
243
250
  return {
244
251
  ok: false,
245
- error: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(", ")}). Wait once via tool_task, then record the terminal result.`,
252
+ error: `Cannot complete goal: goal-owned or cited tool_task(s) are not complete (${pendingToolTasks.join(", ")}). Wait once via tool_task, then record the terminal result.`,
246
253
  };
247
254
  }
248
255
  const activePipeline = options?.activePipeline;
249
256
  if (activePipeline && activePipeline.status === "active") {
250
- const joined = Boolean(activePipeline.goalId && activePipeline.goalId === state.goalId);
251
- if (joined) {
252
- return {
253
- ok: false,
254
- error: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,
255
- };
256
- }
257
+ return {
258
+ ok: false,
259
+ error: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,
260
+ };
257
261
  }
258
262
  const unprovenRequirementIds = getUnprovenGoalRequirementIds(state);
259
263
  if (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {
@@ -315,17 +319,17 @@ export function summarizeGoalState(state, options) {
315
319
  }
316
320
  return lines.join("\n");
317
321
  }
318
- function findLinkedOpenTaskSteps(state, openTaskSteps) {
319
- if (!openTaskSteps || openTaskSteps.length === 0)
320
- return [];
321
- return openTaskSteps
322
- .filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))
323
- .map((step) => step.id);
322
+ function findOpenTaskStepIds(openTaskSteps) {
323
+ return openTaskSteps?.map((step) => step.id) ?? [];
324
324
  }
325
- function findNonterminalCitedToolTasks(state, backgroundToolTasks) {
325
+ function findBlockingToolTasks(state, backgroundToolTasks) {
326
326
  if (!backgroundToolTasks || backgroundToolTasks.length === 0)
327
327
  return [];
328
328
  const pending = new Set();
329
+ for (const task of backgroundToolTasks) {
330
+ if (task.goalId === state.goalId && task.status === "running")
331
+ pending.add(task.taskId);
332
+ }
329
333
  for (const evidence of state.evidence) {
330
334
  if (evidence.kind !== "tool" || !evidence.uri)
331
335
  continue;
@@ -1 +1 @@
1
- {"version":3,"file":"goal-tool-core.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACN,cAAc,EACd,eAAe,EAIf,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,2BAA2B,GAAG,KAAK,C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,EAAE,aAAa,CAAC,CAAC;IACjG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY;aACrC,MAAM,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type BackgroundToolTaskRef, findBackgroundToolTask } from \"../background-tool-task-controller.ts\";\nimport { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\nconst MIN_AGENT_BLOCK_STALL_TURNS = 3;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"increment\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n\t/**\n\t * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of\n\t * these still reference a requirement of the goal being closed.\n\t */\n\topenTaskSteps?: readonly OpenTaskStepRef[];\n\t/** Live background tool_task records used to re-check kind:\"tool\" evidence at complete time. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n\t/** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */\n\tactivePipeline?: { runId: string; pipelineName: string; goalId?: string; status: string };\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tif (action.action === \"increment\") {\n\t\tconst firstOpen = current.requirements.find((requirement) => requirement.status === \"open\");\n\t\tif (firstOpen) {\n\t\t\tconst used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));\n\t\t\tconst unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);\n\t\t\tif (unused.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn applyGoalAction(\n\t\t\t\tcurrent,\n\t\t\t\t{ action: \"satisfy_requirement\", requirementId: firstOpen.id, evidenceIds: unused },\n\t\t\t\tnow,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\t\treturn applyGoalAction(current, { action: \"complete\" }, now, options);\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"increment\":\n\t\t\treturn { ok: false, error: \"increment must be expanded by applyGoalAction.\" };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);\n\t\t\tif (linkedOpenSteps.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(\", \")}). Update them via task_steps first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);\n\t\t\tif (pendingToolTasks.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(\", \")}). Wait once via tool_task, then record the terminal result.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activePipeline = options?.activePipeline;\n\t\t\tif (activePipeline && activePipeline.status === \"active\") {\n\t\t\t\tconst joined = Boolean(activePipeline.goalId && activePipeline.goalId === state.goalId);\n\t\t\t\tif (joined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\tif (state.stallTurns < MIN_AGENT_BLOCK_STALL_TURNS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot block goal: the host has recorded ${state.stallTurns}/${MIN_AGENT_BLOCK_STALL_TURNS} consecutive no-progress goal turns. Keep the goal active until the same blocker has persisted for at least three consecutive goal turns.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n\tevidence?: readonly string[];\n\tpipelineRunId?: string;\n\tpipelineStageId?: string;\n}\n\nfunction findLinkedOpenTaskSteps(state: GoalState, openTaskSteps: readonly OpenTaskStepRef[] | undefined): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\treturn openTaskSteps\n\t\t.filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))\n\t\t.map((step) => step.id);\n}\n\nfunction findNonterminalCitedToolTasks(\n\tstate: GoalState,\n\tbackgroundToolTasks: readonly BackgroundToolTaskRef[] | undefined,\n): string[] {\n\tif (!backgroundToolTasks || backgroundToolTasks.length === 0) return [];\n\tconst pending = new Set<string>();\n\tfor (const evidence of state.evidence) {\n\t\tif (evidence.kind !== \"tool\" || !evidence.uri) continue;\n\t\tconst task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);\n\t\tif (task && task.status !== \"completed\") pending.add(task.taskId);\n\t}\n\treturn [...pending];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
1
+ {"version":3,"file":"goal-tool-core.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACN,cAAc,EACd,eAAe,EAIf,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAClC,MAAM,2BAA2B,GAAG,CAAC,CAAC;AAmFtC,SAAS,iBAAiB,CAAC,KAAgB,EAAE,aAAqB;IACjE,OAAO,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,KAAK,aAAa,CAAC,CAAC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,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type BackgroundToolTaskRef, findBackgroundToolTask } from \"../background-tool-task-controller.ts\";\nimport { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\nconst MIN_AGENT_BLOCK_STALL_TURNS = 3;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"increment\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n\t/**\n\t * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any remain.\n\t */\n\topenTaskSteps?: readonly OpenTaskStepRef[];\n\t/** Live background tool_task records used to gate goal-owned work and re-check tool evidence. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n\t/** Active ICM pipeline run; agent complete refuses while any active run remains. */\n\tactivePipeline?: { runId: string; pipelineName: string; goalId?: string; status: string };\n\t/** Queued/running worker lanes owned by this goal or bound to one of its requirements. */\n\tactiveGoalLaneIds?: readonly string[];\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tif (action.action === \"increment\") {\n\t\tconst firstOpen = current.requirements.find((requirement) => requirement.status === \"open\");\n\t\tif (firstOpen) {\n\t\t\tconst used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));\n\t\t\tconst unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);\n\t\t\tif (unused.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn applyGoalAction(\n\t\t\t\tcurrent,\n\t\t\t\t{ action: \"satisfy_requirement\", requirementId: firstOpen.id, evidenceIds: unused },\n\t\t\t\tnow,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\t\treturn applyGoalAction(current, { action: \"complete\" }, now, options);\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"increment\":\n\t\t\treturn { ok: false, error: \"increment must be expanded by applyGoalAction.\" };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activeGoalLaneIds = [...new Set(options?.activeGoalLaneIds ?? [])];\n\t\t\tif (activeGoalLaneIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: goal-owned worker lane(s) are still active (${activeGoalLaneIds.join(\", \")}). Wait for their terminal handoffs or explicitly cancel them first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst openStepIds = findOpenTaskStepIds(options?.openTaskSteps);\n\t\t\tif (openStepIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: open task_steps work remains (${openStepIds.join(\", \")}). Complete or explicitly cancel those steps first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pendingToolTasks = findBlockingToolTasks(state, options?.backgroundToolTasks);\n\t\t\tif (pendingToolTasks.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: goal-owned or cited tool_task(s) are not complete (${pendingToolTasks.join(\", \")}). Wait once via tool_task, then record the terminal result.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activePipeline = options?.activePipeline;\n\t\t\tif (activePipeline && activePipeline.status === \"active\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\tif (state.stallTurns < MIN_AGENT_BLOCK_STALL_TURNS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot block goal: the host has recorded ${state.stallTurns}/${MIN_AGENT_BLOCK_STALL_TURNS} consecutive no-progress goal turns. Keep the goal active until the same blocker has persisted for at least three consecutive goal turns.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n\tevidence?: readonly string[];\n\tpipelineRunId?: string;\n\tpipelineStageId?: string;\n}\n\nfunction findOpenTaskStepIds(openTaskSteps: readonly OpenTaskStepRef[] | undefined): string[] {\n\treturn openTaskSteps?.map((step) => step.id) ?? [];\n}\n\nfunction findBlockingToolTasks(\n\tstate: GoalState,\n\tbackgroundToolTasks: readonly BackgroundToolTaskRef[] | undefined,\n): string[] {\n\tif (!backgroundToolTasks || backgroundToolTasks.length === 0) return [];\n\tconst pending = new Set<string>();\n\tfor (const task of backgroundToolTasks) {\n\t\tif (task.goalId === state.goalId && task.status === \"running\") pending.add(task.taskId);\n\t}\n\tfor (const evidence of state.evidence) {\n\t\tif (evidence.kind !== \"tool\" || !evidence.uri) continue;\n\t\tconst task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);\n\t\tif (task && task.status !== \"completed\") pending.add(task.taskId);\n\t}\n\treturn [...pending];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
@@ -0,0 +1,84 @@
1
+ import type { AutoLearnSettings, AutonomyMode } from "../settings-manager.ts";
2
+ /** The authoritative Auto Learn defaults used by runtime resolution and settings UI. */
3
+ export declare const DEFAULT_AUTO_LEARN_SETTINGS: {
4
+ readonly enabled: true;
5
+ readonly model: "active";
6
+ readonly thinkingLevel: "low";
7
+ readonly longSessionMessages: 32;
8
+ readonly longSessionContextPercent: 70;
9
+ readonly cooldownMinutes: number;
10
+ readonly leaseMinutes: 90;
11
+ readonly maxConcurrentLearners: 1;
12
+ readonly applyHighConfidence: false;
13
+ readonly reflectionReview: true;
14
+ readonly reflectionMinToolCalls: 12;
15
+ readonly reflectionCooldownMinutes: number;
16
+ readonly complexTaskToolCalls: 12;
17
+ };
18
+ export declare const AUTONOMY_AUTO_LEARN_PRESETS: {
19
+ readonly off: {
20
+ readonly enabled: true;
21
+ readonly model: "active";
22
+ readonly thinkingLevel: "low";
23
+ readonly longSessionMessages: 32;
24
+ readonly longSessionContextPercent: 70;
25
+ readonly cooldownMinutes: number;
26
+ readonly leaseMinutes: 90;
27
+ readonly maxConcurrentLearners: 1;
28
+ readonly applyHighConfidence: false;
29
+ readonly reflectionReview: true;
30
+ readonly reflectionMinToolCalls: 12;
31
+ readonly reflectionCooldownMinutes: number;
32
+ readonly complexTaskToolCalls: 12;
33
+ };
34
+ readonly safe: {
35
+ readonly enabled: true;
36
+ readonly model: "active";
37
+ readonly thinkingLevel: "low";
38
+ readonly cooldownMinutes: number;
39
+ readonly maxConcurrentLearners: 1;
40
+ readonly applyHighConfidence: false;
41
+ readonly reflectionReview: true;
42
+ readonly reflectionMinToolCalls: 12;
43
+ readonly reflectionCooldownMinutes: number;
44
+ readonly complexTaskToolCalls: 12;
45
+ readonly longSessionMessages: 64;
46
+ readonly longSessionContextPercent: 85;
47
+ readonly leaseMinutes: 60;
48
+ };
49
+ readonly balanced: {
50
+ readonly enabled: true;
51
+ readonly model: "active";
52
+ readonly thinkingLevel: "low";
53
+ readonly cooldownMinutes: number;
54
+ readonly leaseMinutes: 90;
55
+ readonly maxConcurrentLearners: 1;
56
+ readonly applyHighConfidence: false;
57
+ readonly reflectionReview: true;
58
+ readonly reflectionMinToolCalls: 12;
59
+ readonly reflectionCooldownMinutes: number;
60
+ readonly complexTaskToolCalls: 12;
61
+ readonly longSessionMessages: 64;
62
+ readonly longSessionContextPercent: 85;
63
+ };
64
+ readonly full: {
65
+ readonly enabled: true;
66
+ readonly model: "active";
67
+ readonly thinkingLevel: "low";
68
+ readonly cooldownMinutes: number;
69
+ readonly leaseMinutes: 90;
70
+ readonly maxConcurrentLearners: 1;
71
+ readonly reflectionReview: true;
72
+ readonly reflectionMinToolCalls: 12;
73
+ readonly reflectionCooldownMinutes: number;
74
+ readonly complexTaskToolCalls: 12;
75
+ readonly longSessionMessages: 64;
76
+ readonly longSessionContextPercent: 85;
77
+ readonly applyHighConfidence: true;
78
+ };
79
+ };
80
+ export declare function getAutoLearnPreset(mode: AutonomyMode, current?: AutoLearnSettings): Required<AutoLearnSettings>;
81
+ export declare function resolveAutoLearnSettings(mode: AutonomyMode, settings?: AutoLearnSettings): Required<AutoLearnSettings>;
82
+ /** One settings/environment gate shared by root prompt construction and current-turn cue delivery. */
83
+ export declare function isCurrentSessionReflectionEnabled(settings: Pick<Required<AutoLearnSettings>, "enabled" | "reflectionReview">, env?: NodeJS.ProcessEnv): boolean;
84
+ //# sourceMappingURL=auto-learn-settings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-learn-settings.d.ts","sourceRoot":"","sources":["../../../src/core/learning/auto-learn-settings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE9E,wFAAwF;AACxF,eAAO,MAAM,2BAA2B;;oBAEhC,QAAQ;4BACA,KAAK;kCACC,EAAE;wCACI,EAAE;;2BAEf,EAAE;oCACO,CAAC;;;qCAGA,EAAE;;mCAEJ,EAAE;CACuB,CAAC;AAEjD,eAAO,MAAM,2BAA2B;;;wBAdhC,QAAQ;gCACA,KAAK;sCACC,EAAE;4CACI,EAAE;;+BAEf,EAAE;wCACO,CAAC;;;yCAGA,EAAE;;uCAEJ,EAAE;;;;wBAXjB,QAAQ;gCACA,KAAK;;wCAKG,CAAC;;;yCAGA,EAAE;;uCAEJ,EAAE;sCAOF,EAAE;4CACI,EAAE;+BACf,EAAE;;;;wBApBV,QAAQ;gCACA,KAAK;;+BAIN,EAAE;wCACO,CAAC;;;yCAGA,EAAE;;uCAEJ,EAAE;sCAaF,EAAE;4CACI,EAAE;;;;wBAzBvB,QAAQ;gCACA,KAAK;;+BAIN,EAAE;wCACO,CAAC;;yCAGA,EAAE;;uCAEJ,EAAE;sCAkBF,EAAE;4CACI,EAAE;;;CAGuC,CAAC;AAEvE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,GAAE,iBAAsB,GAAG,QAAQ,CAAC,iBAAiB,CAAC,CAGnH;AAED,wBAAgB,wBAAwB,CACvC,IAAI,EAAE,YAAY,EAClB,QAAQ,GAAE,iBAAsB,GAC9B,QAAQ,CAAC,iBAAiB,CAAC,CAiB7B;AAED,sGAAsG;AACtG,wBAAgB,iCAAiC,CAChD,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,SAAS,GAAG,kBA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