@wrongstack/core 0.297.0 → 0.298.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (806) hide show
  1. package/dist/chronicle/index.js +126 -22
  2. package/dist/chronicle/project-server-client.d.ts +12 -0
  3. package/dist/chronicle/project-server-protocol.d.ts +22 -0
  4. package/dist/chronicle/project-server.js +238 -157
  5. package/dist/coordination/agents/index.js +136 -1
  6. package/dist/coordination/agents/role-skills.d.ts +3 -2
  7. package/dist/coordination/brain-trace.d.ts +2 -1
  8. package/dist/coordination/director/director-task-registry.d.ts +12 -0
  9. package/dist/coordination/fleet-supervisor.d.ts +21 -0
  10. package/dist/coordination/index.d.ts +23 -21
  11. package/dist/coordination/index.js +16493 -16068
  12. package/dist/coordination/mail-tools.d.ts +3 -3
  13. package/dist/coordination/mailbox-credential-store.d.ts +22 -2
  14. package/dist/coordination/mailbox-credential-throttle.d.ts +63 -0
  15. package/dist/coordination/mailbox-project-server-client.d.ts +16 -0
  16. package/dist/coordination/mailbox-project-server-protocol.d.ts +43 -5
  17. package/dist/coordination/mailbox-project-server.js +508 -253
  18. package/dist/coordination/provider-status-tracker.d.ts +2 -0
  19. package/dist/coordination/remote-mailbox-credential-store.d.ts +5 -5
  20. package/dist/coordination/remote-mailbox.d.ts +8 -4
  21. package/dist/coordination/sqlite-mailbox-credentials.d.ts +11 -0
  22. package/dist/core/fallback-profile-manager.d.ts +14 -0
  23. package/dist/core/index.js +451 -137
  24. package/dist/core/instruction-bundle.d.ts +12 -0
  25. package/dist/core/system-prompt-builder.d.ts +14 -0
  26. package/dist/core/system-prompt-skill-bodies.d.ts +1 -1
  27. package/dist/core/system-prompt-skill-text.d.ts +1 -2
  28. package/dist/defaults/index.js +2191 -1208
  29. package/dist/design/index.js +47 -8
  30. package/dist/execution/design-materialize.d.ts +22 -0
  31. package/dist/execution/index.js +495 -248
  32. package/dist/execution/skill-loader.d.ts +10 -1
  33. package/dist/execution/tool-error-taxonomy.d.ts +31 -0
  34. package/dist/execution/tool-executor.d.ts +1 -0
  35. package/dist/goal/index.js +3 -1
  36. package/dist/hooks/index.js +5 -0
  37. package/dist/hq/auth-audit.d.ts +6 -0
  38. package/dist/hq/auth-store.d.ts +59 -3
  39. package/dist/hq/index.js +401 -101
  40. package/dist/hq/kanban-store.d.ts +3 -0
  41. package/dist/hq/protocol/core.d.ts +3 -15
  42. package/dist/hq/protocol/envelope.d.ts +29 -0
  43. package/dist/hq/protocol/governance.d.ts +34 -0
  44. package/dist/hq/protocol/project.d.ts +3 -0
  45. package/dist/hq/protocol/resume.d.ts +1 -1
  46. package/dist/hq/protocol.d.ts +9 -8
  47. package/dist/hq/protocol.js +675 -0
  48. package/dist/index.js +9012 -6916
  49. package/dist/infrastructure/index.js +199 -102
  50. package/dist/kernel/events/session-events.d.ts +3 -0
  51. package/dist/kernel/events/tool-events.d.ts +3 -1
  52. package/dist/models/index.js +1 -1
  53. package/dist/observability/index.js +27 -0
  54. package/dist/observability/prometheus.d.ts +11 -0
  55. package/dist/plugin/index.d.ts +5 -1
  56. package/dist/plugin/index.js +988 -558
  57. package/dist/plugins/auto-review-plugin.d.ts +1 -11
  58. package/dist/plugins/review-store-maintenance.d.ts +26 -0
  59. package/dist/plugins/review-types.d.ts +6 -0
  60. package/dist/security/auto-approve-policy.d.ts +37 -0
  61. package/dist/security/capabilities.d.ts +45 -1
  62. package/dist/security/error-sanitize.d.ts +49 -0
  63. package/dist/security/file-permissions.d.ts +41 -0
  64. package/dist/security/index.d.ts +9 -6
  65. package/dist/security/index.js +3008 -2029
  66. package/dist/security/permission-helpers.d.ts +93 -0
  67. package/dist/security/permission-policy.d.ts +37 -35
  68. package/dist/security/secret-vault.d.ts +17 -0
  69. package/dist/security/totp.d.ts +86 -0
  70. package/dist/skills/frontmatter.d.ts +12 -1
  71. package/dist/skills/github-fetcher.d.ts +48 -0
  72. package/dist/skills/index.js +137 -26
  73. package/dist/skills/limits.d.ts +19 -0
  74. package/dist/skills/skill-installer.d.ts +13 -0
  75. package/dist/storage/index.js +929 -733
  76. package/dist/storage/provider-config-watcher.d.ts +1 -0
  77. package/dist/storage/session-helpers.d.ts +1 -0
  78. package/dist/storage/session-store.d.ts +9 -2
  79. package/dist/storage/session-workspace-checkpoints.d.ts +5 -0
  80. package/dist/tools/fallback-manage-tools.d.ts +6 -0
  81. package/dist/tools/index.js +287 -131
  82. package/dist/tools/mcp-use.d.ts +1 -1
  83. package/dist/types/blocks.d.ts +7 -0
  84. package/dist/types/config/autonomy.d.ts +15 -7
  85. package/dist/types/config/mcp-features.d.ts +9 -1
  86. package/dist/types/config/root.d.ts +10 -4
  87. package/dist/types/context-window.d.ts +15 -0
  88. package/dist/types/index.d.ts +1 -1
  89. package/dist/types/secret-vault.d.ts +8 -0
  90. package/dist/types/session.d.ts +2 -0
  91. package/dist/types/skill.d.ts +56 -0
  92. package/dist/types/tool-executor.d.ts +2 -0
  93. package/dist/utils/env-typed.d.ts +64 -0
  94. package/dist/utils/glob-match.d.ts +21 -1
  95. package/dist/utils/heap-watchdog.js +1 -1
  96. package/dist/utils/incoming-images.d.ts +19 -0
  97. package/dist/utils/index.d.ts +16 -12
  98. package/dist/utils/index.js +3128 -2800
  99. package/dist/utils/path-segment.d.ts +29 -0
  100. package/dist/utils/sage-output-block.js +48 -0
  101. package/dist/utils/win32-cmd.d.ts +25 -0
  102. package/dist/worktree/index.js +5 -0
  103. package/instructions/llm/chimera-review.md +4 -6
  104. package/package.json +13 -4
  105. package/skills/auto-review/SKILL.md +11 -76
  106. package/skills/chimera/SKILL.md +31 -49
  107. package/skills/data-governance/SKILL.md +92 -0
  108. package/skills/wrongstack-kanban/SKILL.md +125 -64
  109. package/dist/agent-status-helpers.d.ts.map +0 -1
  110. package/dist/agent-status-tracker.d.ts.map +0 -1
  111. package/dist/boot.d.ts.map +0 -1
  112. package/dist/chronicle/context.d.ts.map +0 -1
  113. package/dist/chronicle/decision-adapter.d.ts.map +0 -1
  114. package/dist/chronicle/domain-adapter.d.ts.map +0 -1
  115. package/dist/chronicle/event-hash.d.ts.map +0 -1
  116. package/dist/chronicle/file-observer.d.ts.map +0 -1
  117. package/dist/chronicle/health-monitor.d.ts.map +0 -1
  118. package/dist/chronicle/identity.d.ts.map +0 -1
  119. package/dist/chronicle/index.d.ts.map +0 -1
  120. package/dist/chronicle/index.js.map +0 -7
  121. package/dist/chronicle/journal.d.ts.map +0 -1
  122. package/dist/chronicle/legacy-journal-import.d.ts.map +0 -1
  123. package/dist/chronicle/metrics-store.d.ts.map +0 -1
  124. package/dist/chronicle/partition-filename.d.ts.map +0 -1
  125. package/dist/chronicle/partition-range-cache.d.ts.map +0 -1
  126. package/dist/chronicle/process-adapter.d.ts.map +0 -1
  127. package/dist/chronicle/project-access.d.ts.map +0 -1
  128. package/dist/chronicle/project-server-client.d.ts.map +0 -1
  129. package/dist/chronicle/project-server-endpoint.d.ts.map +0 -1
  130. package/dist/chronicle/project-server-protocol.d.ts.map +0 -1
  131. package/dist/chronicle/project-server.d.ts.map +0 -1
  132. package/dist/chronicle/project-server.js.map +0 -7
  133. package/dist/chronicle/prompt-manifest.d.ts.map +0 -1
  134. package/dist/chronicle/provider-adapter.d.ts.map +0 -1
  135. package/dist/chronicle/query.d.ts.map +0 -1
  136. package/dist/chronicle/review-adapter.d.ts.map +0 -1
  137. package/dist/chronicle/rollup-adapter.d.ts.map +0 -1
  138. package/dist/chronicle/sink.d.ts.map +0 -1
  139. package/dist/chronicle/sqlite-journal.d.ts.map +0 -1
  140. package/dist/chronicle/sqlite-query.d.ts.map +0 -1
  141. package/dist/chronicle/stream-adapter.d.ts.map +0 -1
  142. package/dist/chronicle/tool-adapter.d.ts.map +0 -1
  143. package/dist/chronicle/types.d.ts.map +0 -1
  144. package/dist/coordination/adaptive-concurrency.d.ts.map +0 -1
  145. package/dist/coordination/agent-bridge.d.ts.map +0 -1
  146. package/dist/coordination/agent-monitor.d.ts.map +0 -1
  147. package/dist/coordination/agent-subagent-runner.d.ts.map +0 -1
  148. package/dist/coordination/agents/agent-prompts.d.ts.map +0 -1
  149. package/dist/coordination/agents/index.d.ts.map +0 -1
  150. package/dist/coordination/agents/index.js.map +0 -7
  151. package/dist/coordination/agents/phase1-discovery.d.ts.map +0 -1
  152. package/dist/coordination/agents/phase2-planning.d.ts.map +0 -1
  153. package/dist/coordination/agents/phase3-build.d.ts.map +0 -1
  154. package/dist/coordination/agents/phase3-techstack.d.ts.map +0 -1
  155. package/dist/coordination/agents/phase3-wave1-platform.d.ts.map +0 -1
  156. package/dist/coordination/agents/phase3-wave2-meta.d.ts.map +0 -1
  157. package/dist/coordination/agents/phase4-verify.d.ts.map +0 -1
  158. package/dist/coordination/agents/phase5-review.d.ts.map +0 -1
  159. package/dist/coordination/agents/phase6-domain.d.ts.map +0 -1
  160. package/dist/coordination/agents/phase7-knowledge.d.ts.map +0 -1
  161. package/dist/coordination/agents/phase8-delivery.d.ts.map +0 -1
  162. package/dist/coordination/agents/phase8-wave3-products.d.ts.map +0 -1
  163. package/dist/coordination/agents/phase9-meta.d.ts.map +0 -1
  164. package/dist/coordination/agents/phase9-wave4-platform-meta.d.ts.map +0 -1
  165. package/dist/coordination/agents/project-agent-config-validation.d.ts.map +0 -1
  166. package/dist/coordination/agents/project-agent-consolidation.d.ts.map +0 -1
  167. package/dist/coordination/agents/project-agent-files.d.ts.map +0 -1
  168. package/dist/coordination/agents/project-agent-identity-types.d.ts.map +0 -1
  169. package/dist/coordination/agents/project-agent-identity.d.ts.map +0 -1
  170. package/dist/coordination/agents/project-agent-knowledge-manifests.d.ts.map +0 -1
  171. package/dist/coordination/agents/project-agent-learning-entries.d.ts.map +0 -1
  172. package/dist/coordination/agents/project-agent-learning-normalize.d.ts.map +0 -1
  173. package/dist/coordination/agents/project-agent-learning-policy.d.ts.map +0 -1
  174. package/dist/coordination/agents/project-agent-learning-structured.d.ts.map +0 -1
  175. package/dist/coordination/agents/project-agent-paths.d.ts.map +0 -1
  176. package/dist/coordination/agents/project-agent-profile.d.ts.map +0 -1
  177. package/dist/coordination/agents/role-skills.d.ts.map +0 -1
  178. package/dist/coordination/agents/types.d.ts.map +0 -1
  179. package/dist/coordination/agents.d.ts.map +0 -1
  180. package/dist/coordination/auto-extend.d.ts.map +0 -1
  181. package/dist/coordination/autonomous-brain.d.ts.map +0 -1
  182. package/dist/coordination/autonomous-coordinator.d.ts.map +0 -1
  183. package/dist/coordination/brain-cache.d.ts.map +0 -1
  184. package/dist/coordination/brain-heuristics.d.ts.map +0 -1
  185. package/dist/coordination/brain-ledger.d.ts.map +0 -1
  186. package/dist/coordination/brain-monitor.d.ts.map +0 -1
  187. package/dist/coordination/brain-rules.d.ts.map +0 -1
  188. package/dist/coordination/brain-telemetry.d.ts.map +0 -1
  189. package/dist/coordination/brain-trace.d.ts.map +0 -1
  190. package/dist/coordination/brain.d.ts.map +0 -1
  191. package/dist/coordination/change-manager.d.ts.map +0 -1
  192. package/dist/coordination/checkpoint-wiring.d.ts.map +0 -1
  193. package/dist/coordination/collab-bus.d.ts.map +0 -1
  194. package/dist/coordination/collab-debug-types.d.ts.map +0 -1
  195. package/dist/coordination/collab-debug.d.ts.map +0 -1
  196. package/dist/coordination/collab-director-host.d.ts.map +0 -1
  197. package/dist/coordination/commit-safety.d.ts.map +0 -1
  198. package/dist/coordination/consensus-protocol.d.ts.map +0 -1
  199. package/dist/coordination/coordinator/error-classifier.d.ts.map +0 -1
  200. package/dist/coordination/delegate-tool.d.ts.map +0 -1
  201. package/dist/coordination/dep-watcher-bridge.d.ts.map +0 -1
  202. package/dist/coordination/dep-watcher.d.ts.map +0 -1
  203. package/dist/coordination/director/director-btw-notes.d.ts.map +0 -1
  204. package/dist/coordination/director/director-budget-policy.d.ts.map +0 -1
  205. package/dist/coordination/director/director-collab.d.ts.map +0 -1
  206. package/dist/coordination/director/director-errors.d.ts.map +0 -1
  207. package/dist/coordination/director/director-task-registry.d.ts.map +0 -1
  208. package/dist/coordination/director/director-toolset.d.ts.map +0 -1
  209. package/dist/coordination/director-basic-tools.d.ts.map +0 -1
  210. package/dist/coordination/director-collab-tools.d.ts.map +0 -1
  211. package/dist/coordination/director-host-contracts.d.ts.map +0 -1
  212. package/dist/coordination/director-input-helpers.d.ts.map +0 -1
  213. package/dist/coordination/director-kanban-queue-helpers.d.ts.map +0 -1
  214. package/dist/coordination/director-options.d.ts.map +0 -1
  215. package/dist/coordination/director-prompts.d.ts.map +0 -1
  216. package/dist/coordination/director-quality-gate-tool.d.ts.map +0 -1
  217. package/dist/coordination/director-session.d.ts.map +0 -1
  218. package/dist/coordination/director-spawn-model.d.ts.map +0 -1
  219. package/dist/coordination/director-tools.d.ts.map +0 -1
  220. package/dist/coordination/director.d.ts.map +0 -1
  221. package/dist/coordination/dispatcher.d.ts.map +0 -1
  222. package/dist/coordination/file-author-tracker.d.ts.map +0 -1
  223. package/dist/coordination/fleet-bus.d.ts.map +0 -1
  224. package/dist/coordination/fleet-event-validation.d.ts.map +0 -1
  225. package/dist/coordination/fleet-manager.d.ts.map +0 -1
  226. package/dist/coordination/fleet-spawn.d.ts.map +0 -1
  227. package/dist/coordination/fleet-status-tool.d.ts.map +0 -1
  228. package/dist/coordination/fleet-supervisor.d.ts.map +0 -1
  229. package/dist/coordination/fleet.d.ts.map +0 -1
  230. package/dist/coordination/global-mailbox-completion.d.ts.map +0 -1
  231. package/dist/coordination/global-mailbox-paths.d.ts.map +0 -1
  232. package/dist/coordination/icoordinator.d.ts.map +0 -1
  233. package/dist/coordination/ifleet-manager.d.ts.map +0 -1
  234. package/dist/coordination/in-memory-transport.d.ts.map +0 -1
  235. package/dist/coordination/index.d.ts.map +0 -1
  236. package/dist/coordination/index.js.map +0 -7
  237. package/dist/coordination/knowledge-graph.d.ts.map +0 -1
  238. package/dist/coordination/large-answer-store.d.ts.map +0 -1
  239. package/dist/coordination/mail-tools.d.ts.map +0 -1
  240. package/dist/coordination/mailbox-actions.d.ts.map +0 -1
  241. package/dist/coordination/mailbox-auth-types.d.ts.map +0 -1
  242. package/dist/coordination/mailbox-codecs.d.ts.map +0 -1
  243. package/dist/coordination/mailbox-constants.d.ts.map +0 -1
  244. package/dist/coordination/mailbox-credential-store.d.ts.map +0 -1
  245. package/dist/coordination/mailbox-events.d.ts.map +0 -1
  246. package/dist/coordination/mailbox-health.d.ts.map +0 -1
  247. package/dist/coordination/mailbox-hooks.d.ts.map +0 -1
  248. package/dist/coordination/mailbox-http-auth.d.ts.map +0 -1
  249. package/dist/coordination/mailbox-http-rate-limit.d.ts.map +0 -1
  250. package/dist/coordination/mailbox-http-router.d.ts.map +0 -1
  251. package/dist/coordination/mailbox-http-validation.d.ts.map +0 -1
  252. package/dist/coordination/mailbox-message-codec.d.ts.map +0 -1
  253. package/dist/coordination/mailbox-parse-state.d.ts.map +0 -1
  254. package/dist/coordination/mailbox-project-server-client.d.ts.map +0 -1
  255. package/dist/coordination/mailbox-project-server-endpoint.d.ts.map +0 -1
  256. package/dist/coordination/mailbox-project-server-protocol.d.ts.map +0 -1
  257. package/dist/coordination/mailbox-project-server.d.ts.map +0 -1
  258. package/dist/coordination/mailbox-project-server.js.map +0 -7
  259. package/dist/coordination/mailbox-receipt-folding.d.ts.map +0 -1
  260. package/dist/coordination/mailbox-registry-codec.d.ts.map +0 -1
  261. package/dist/coordination/mailbox-retention-state.d.ts.map +0 -1
  262. package/dist/coordination/mailbox-status-mappers.d.ts.map +0 -1
  263. package/dist/coordination/mailbox-tool.d.ts.map +0 -1
  264. package/dist/coordination/mailbox-type-properties.d.ts.map +0 -1
  265. package/dist/coordination/mailbox-types.d.ts.map +0 -1
  266. package/dist/coordination/model-matrix.d.ts.map +0 -1
  267. package/dist/coordination/multi-agent-coordinator.d.ts.map +0 -1
  268. package/dist/coordination/multi-agent-timeout.d.ts.map +0 -1
  269. package/dist/coordination/null-fleet-bus.d.ts.map +0 -1
  270. package/dist/coordination/package-author-tracker.d.ts.map +0 -1
  271. package/dist/coordination/package-outdated-watcher.d.ts.map +0 -1
  272. package/dist/coordination/provider-status-tracker.d.ts.map +0 -1
  273. package/dist/coordination/remote-mailbox-credential-store.d.ts.map +0 -1
  274. package/dist/coordination/remote-mailbox.d.ts.map +0 -1
  275. package/dist/coordination/single-instance-mailbox.d.ts.map +0 -1
  276. package/dist/coordination/spawn-budget.d.ts.map +0 -1
  277. package/dist/coordination/sqlite-mailbox-compaction.d.ts.map +0 -1
  278. package/dist/coordination/sqlite-mailbox-credentials.d.ts.map +0 -1
  279. package/dist/coordination/sqlite-mailbox-rows.d.ts.map +0 -1
  280. package/dist/coordination/sqlite-mailbox-schema.d.ts.map +0 -1
  281. package/dist/coordination/sqlite-mailbox.d.ts.map +0 -1
  282. package/dist/coordination/subagent-budget.d.ts.map +0 -1
  283. package/dist/coordination/subagent-nicknames.d.ts.map +0 -1
  284. package/dist/coordination/subagent-result-tool.d.ts.map +0 -1
  285. package/dist/coordination/task-auctioneer.d.ts.map +0 -1
  286. package/dist/coordination/task-dag.d.ts.map +0 -1
  287. package/dist/coordination/techstack-mailbox-consumer.d.ts.map +0 -1
  288. package/dist/coordination/transport.d.ts.map +0 -1
  289. package/dist/coordination/worktree-task-runner.d.ts.map +0 -1
  290. package/dist/core/agent-internals.d.ts.map +0 -1
  291. package/dist/core/agent-loop.d.ts.map +0 -1
  292. package/dist/core/agent-response.d.ts.map +0 -1
  293. package/dist/core/agent-tools.d.ts.map +0 -1
  294. package/dist/core/agent-types.d.ts.map +0 -1
  295. package/dist/core/agent.d.ts.map +0 -1
  296. package/dist/core/btw.d.ts.map +0 -1
  297. package/dist/core/context.d.ts.map +0 -1
  298. package/dist/core/continue-intent.d.ts.map +0 -1
  299. package/dist/core/continue-to-next-iteration.d.ts.map +0 -1
  300. package/dist/core/conversation-state.d.ts.map +0 -1
  301. package/dist/core/fallback-model.d.ts.map +0 -1
  302. package/dist/core/fallback-profile-manager.d.ts.map +0 -1
  303. package/dist/core/fleet-pulse.d.ts.map +0 -1
  304. package/dist/core/index.d.ts.map +0 -1
  305. package/dist/core/index.js.map +0 -7
  306. package/dist/core/input-builder.d.ts.map +0 -1
  307. package/dist/core/instruction-bundle.d.ts.map +0 -1
  308. package/dist/core/iteration-limit.d.ts.map +0 -1
  309. package/dist/core/mailbox-loop.d.ts.map +0 -1
  310. package/dist/core/model-availability-calendar.d.ts.map +0 -1
  311. package/dist/core/model-ref.d.ts.map +0 -1
  312. package/dist/core/model-ref.js.map +0 -7
  313. package/dist/core/modes/brief.d.ts.map +0 -1
  314. package/dist/core/modes/default.d.ts.map +0 -1
  315. package/dist/core/modes/teach.d.ts.map +0 -1
  316. package/dist/core/provider-runner.d.ts.map +0 -1
  317. package/dist/core/queued-messages.d.ts.map +0 -1
  318. package/dist/core/request-provider-binding.d.ts.map +0 -1
  319. package/dist/core/run-env.d.ts.map +0 -1
  320. package/dist/core/streaming-response-builder.d.ts.map +0 -1
  321. package/dist/core/system-prompt-blocks.d.ts.map +0 -1
  322. package/dist/core/system-prompt-builder.d.ts.map +0 -1
  323. package/dist/core/system-prompt-environment-probes.d.ts.map +0 -1
  324. package/dist/core/system-prompt-environment.d.ts.map +0 -1
  325. package/dist/core/system-prompt-memory-skills.d.ts.map +0 -1
  326. package/dist/core/system-prompt-plan.d.ts.map +0 -1
  327. package/dist/core/system-prompt-shell.d.ts.map +0 -1
  328. package/dist/core/system-prompt-skill-bodies.d.ts.map +0 -1
  329. package/dist/core/system-prompt-skill-text.d.ts.map +0 -1
  330. package/dist/defaults/index.d.ts.map +0 -1
  331. package/dist/defaults/index.js.map +0 -7
  332. package/dist/design/index.d.ts.map +0 -1
  333. package/dist/design/index.js.map +0 -7
  334. package/dist/execution/auto-compaction-middleware.d.ts.map +0 -1
  335. package/dist/execution/autonomous-runner.d.ts.map +0 -1
  336. package/dist/execution/autonomy-brain.d.ts.map +0 -1
  337. package/dist/execution/autonomy-prompt-contributor.d.ts.map +0 -1
  338. package/dist/execution/brain-chain.d.ts.map +0 -1
  339. package/dist/execution/brain-circuit.d.ts.map +0 -1
  340. package/dist/execution/brain-evaluation.d.ts.map +0 -1
  341. package/dist/execution/brain-runtime-constants.d.ts.map +0 -1
  342. package/dist/execution/brain-runtime.d.ts.map +0 -1
  343. package/dist/execution/compaction-core.d.ts.map +0 -1
  344. package/dist/execution/compaction-scoring.d.ts.map +0 -1
  345. package/dist/execution/compaction-summary-cache.d.ts.map +0 -1
  346. package/dist/execution/compactor.d.ts.map +0 -1
  347. package/dist/execution/council-brain.d.ts.map +0 -1
  348. package/dist/execution/council-orchestrator.d.ts.map +0 -1
  349. package/dist/execution/council-personas.d.ts.map +0 -1
  350. package/dist/execution/council-profiles.d.ts.map +0 -1
  351. package/dist/execution/council-prompts.d.ts.map +0 -1
  352. package/dist/execution/council-resolution.d.ts.map +0 -1
  353. package/dist/execution/design-color.d.ts.map +0 -1
  354. package/dist/execution/design-detect.d.ts.map +0 -1
  355. package/dist/execution/design-kit-loader.d.ts.map +0 -1
  356. package/dist/execution/design-materialize.d.ts.map +0 -1
  357. package/dist/execution/design-project-store.d.ts.map +0 -1
  358. package/dist/execution/design-tune.d.ts.map +0 -1
  359. package/dist/execution/design-verify.d.ts.map +0 -1
  360. package/dist/execution/enhance-recovery.d.ts.map +0 -1
  361. package/dist/execution/error-handler.d.ts.map +0 -1
  362. package/dist/execution/eternal-autonomy-types.d.ts.map +0 -1
  363. package/dist/execution/eternal-autonomy.d.ts.map +0 -1
  364. package/dist/execution/goal-preamble.d.ts.map +0 -1
  365. package/dist/execution/index.d.ts.map +0 -1
  366. package/dist/execution/index.js.map +0 -7
  367. package/dist/execution/intelligent-compactor.d.ts.map +0 -1
  368. package/dist/execution/model-runtime.d.ts.map +0 -1
  369. package/dist/execution/one-shot-llm.d.ts.map +0 -1
  370. package/dist/execution/parallel-eternal-engine.d.ts.map +0 -1
  371. package/dist/execution/prompt-enhancer.d.ts.map +0 -1
  372. package/dist/execution/prompt-enhancer.js.map +0 -7
  373. package/dist/execution/prompt-loader.d.ts.map +0 -1
  374. package/dist/execution/provider-runner-impl.d.ts.map +0 -1
  375. package/dist/execution/regex-patterns.d.ts.map +0 -1
  376. package/dist/execution/retry-policy.d.ts.map +0 -1
  377. package/dist/execution/selective-compactor.d.ts.map +0 -1
  378. package/dist/execution/skill-loader.d.ts.map +0 -1
  379. package/dist/execution/strategy-compactor.d.ts.map +0 -1
  380. package/dist/execution/subagent-compaction.d.ts.map +0 -1
  381. package/dist/execution/tool-executor-logging.d.ts.map +0 -1
  382. package/dist/execution/tool-executor-results.d.ts.map +0 -1
  383. package/dist/execution/tool-executor-stream.d.ts.map +0 -1
  384. package/dist/execution/tool-executor-support.d.ts.map +0 -1
  385. package/dist/execution/tool-executor.d.ts.map +0 -1
  386. package/dist/extension/extension-points.d.ts.map +0 -1
  387. package/dist/extension/index.d.ts.map +0 -1
  388. package/dist/extension/index.js.map +0 -7
  389. package/dist/extension/registry.d.ts.map +0 -1
  390. package/dist/fleet-notifier.d.ts.map +0 -1
  391. package/dist/goal/checkpoint.d.ts.map +0 -1
  392. package/dist/goal/goal-assessor.d.ts.map +0 -1
  393. package/dist/goal/goal-planner.d.ts.map +0 -1
  394. package/dist/goal/goal-runner.d.ts.map +0 -1
  395. package/dist/goal/index.d.ts.map +0 -1
  396. package/dist/goal/index.js.map +0 -7
  397. package/dist/goal/phase-board-mutations.d.ts.map +0 -1
  398. package/dist/goal/phase-graph-builder.d.ts.map +0 -1
  399. package/dist/goal/phase-orchestrator-integration.d.ts.map +0 -1
  400. package/dist/goal/phase-orchestrator-queries.d.ts.map +0 -1
  401. package/dist/goal/phase-orchestrator-runtime.d.ts.map +0 -1
  402. package/dist/goal/phase-orchestrator-types.d.ts.map +0 -1
  403. package/dist/goal/phase-orchestrator.d.ts.map +0 -1
  404. package/dist/goal/phase-store.d.ts.map +0 -1
  405. package/dist/goal/types.d.ts.map +0 -1
  406. package/dist/hooks/http-executor.d.ts.map +0 -1
  407. package/dist/hooks/index.d.ts.map +0 -1
  408. package/dist/hooks/index.js.map +0 -7
  409. package/dist/hooks/registry.d.ts.map +0 -1
  410. package/dist/hooks/runner.d.ts.map +0 -1
  411. package/dist/hooks/shell-executor.d.ts.map +0 -1
  412. package/dist/hooks/shell-hooks-equal.d.ts.map +0 -1
  413. package/dist/hq/alerts.d.ts.map +0 -1
  414. package/dist/hq/auth-audit.d.ts.map +0 -1
  415. package/dist/hq/auth-store.d.ts.map +0 -1
  416. package/dist/hq/bootstrap-store.d.ts.map +0 -1
  417. package/dist/hq/brain-bridge.d.ts.map +0 -1
  418. package/dist/hq/bridge-context.d.ts.map +0 -1
  419. package/dist/hq/commands.d.ts.map +0 -1
  420. package/dist/hq/cost-bridge.d.ts.map +0 -1
  421. package/dist/hq/exposure.d.ts.map +0 -1
  422. package/dist/hq/factory.d.ts.map +0 -1
  423. package/dist/hq/fleet-bridge.d.ts.map +0 -1
  424. package/dist/hq/index.d.ts.map +0 -1
  425. package/dist/hq/index.js.map +0 -7
  426. package/dist/hq/kanban-store.d.ts.map +0 -1
  427. package/dist/hq/mailbox-mapper.d.ts.map +0 -1
  428. package/dist/hq/persistence/event-log.d.ts.map +0 -1
  429. package/dist/hq/persistence/jsonl-io.d.ts.map +0 -1
  430. package/dist/hq/persistence/simple-log.d.ts.map +0 -1
  431. package/dist/hq/persistence/snapshot-store.d.ts.map +0 -1
  432. package/dist/hq/persistence/timeseries-store.d.ts.map +0 -1
  433. package/dist/hq/persistence.d.ts.map +0 -1
  434. package/dist/hq/protocol/brain.d.ts.map +0 -1
  435. package/dist/hq/protocol/browser.d.ts.map +0 -1
  436. package/dist/hq/protocol/client.d.ts.map +0 -1
  437. package/dist/hq/protocol/core.d.ts.map +0 -1
  438. package/dist/hq/protocol/fleet.d.ts.map +0 -1
  439. package/dist/hq/protocol/kanban.d.ts.map +0 -1
  440. package/dist/hq/protocol/mailbox.d.ts.map +0 -1
  441. package/dist/hq/protocol/mcp.d.ts.map +0 -1
  442. package/dist/hq/protocol/peer.d.ts.map +0 -1
  443. package/dist/hq/protocol/project.d.ts.map +0 -1
  444. package/dist/hq/protocol/resume.d.ts.map +0 -1
  445. package/dist/hq/protocol/session.d.ts.map +0 -1
  446. package/dist/hq/protocol/tool.d.ts.map +0 -1
  447. package/dist/hq/protocol.d.ts.map +0 -1
  448. package/dist/hq/publisher.d.ts.map +0 -1
  449. package/dist/hq/redaction.d.ts.map +0 -1
  450. package/dist/hq/session-bridge.d.ts.map +0 -1
  451. package/dist/hq/tool-bridge.d.ts.map +0 -1
  452. package/dist/hq/transcript-mapper.d.ts.map +0 -1
  453. package/dist/hq/worktree-bridge.d.ts.map +0 -1
  454. package/dist/hq/write-queues.d.ts.map +0 -1
  455. package/dist/index.d.ts.map +0 -1
  456. package/dist/index.js.map +0 -7
  457. package/dist/infrastructure/context-manager.d.ts.map +0 -1
  458. package/dist/infrastructure/index.d.ts.map +0 -1
  459. package/dist/infrastructure/index.js.map +0 -7
  460. package/dist/infrastructure/logger.d.ts.map +0 -1
  461. package/dist/infrastructure/mcp-servers.d.ts.map +0 -1
  462. package/dist/infrastructure/path-resolver.d.ts.map +0 -1
  463. package/dist/infrastructure/provider-cache-ledger.d.ts.map +0 -1
  464. package/dist/infrastructure/token-counter.d.ts.map +0 -1
  465. package/dist/kernel/container.d.ts.map +0 -1
  466. package/dist/kernel/events/agent-events.d.ts.map +0 -1
  467. package/dist/kernel/events/brain-events.d.ts.map +0 -1
  468. package/dist/kernel/events/file-events.d.ts.map +0 -1
  469. package/dist/kernel/events/fleet-events.d.ts.map +0 -1
  470. package/dist/kernel/events/memory-events.d.ts.map +0 -1
  471. package/dist/kernel/events/network-events.d.ts.map +0 -1
  472. package/dist/kernel/events/process-events.d.ts.map +0 -1
  473. package/dist/kernel/events/provider-events.d.ts.map +0 -1
  474. package/dist/kernel/events/sdd-events.d.ts.map +0 -1
  475. package/dist/kernel/events/session-events.d.ts.map +0 -1
  476. package/dist/kernel/events/tool-events.d.ts.map +0 -1
  477. package/dist/kernel/events/worktree-events.d.ts.map +0 -1
  478. package/dist/kernel/events.d.ts.map +0 -1
  479. package/dist/kernel/index.d.ts.map +0 -1
  480. package/dist/kernel/index.js.map +0 -7
  481. package/dist/kernel/pipeline.d.ts.map +0 -1
  482. package/dist/kernel/run-controller.d.ts.map +0 -1
  483. package/dist/kernel/tokens.d.ts.map +0 -1
  484. package/dist/mailbox-attach.d.ts.map +0 -1
  485. package/dist/middleware/collab-pause.d.ts.map +0 -1
  486. package/dist/models/alibaba-token-plan-catalog.d.ts.map +0 -1
  487. package/dist/models/codex-catalog.d.ts.map +0 -1
  488. package/dist/models/index.d.ts.map +0 -1
  489. package/dist/models/index.js.map +0 -7
  490. package/dist/models/llm-selector.d.ts.map +0 -1
  491. package/dist/models/mode-store.d.ts.map +0 -1
  492. package/dist/models/model-intelligence.d.ts.map +0 -1
  493. package/dist/models/model-router.d.ts.map +0 -1
  494. package/dist/models/models-registry.d.ts.map +0 -1
  495. package/dist/models/provider-model-resolve.d.ts.map +0 -1
  496. package/dist/notifications/index.d.ts.map +0 -1
  497. package/dist/notifications/index.js.map +0 -7
  498. package/dist/notifications/notifier-impl.d.ts.map +0 -1
  499. package/dist/notifications/notifier.d.ts.map +0 -1
  500. package/dist/notifications/types.d.ts.map +0 -1
  501. package/dist/observability/event-bridge.d.ts.map +0 -1
  502. package/dist/observability/health.d.ts.map +0 -1
  503. package/dist/observability/index.d.ts.map +0 -1
  504. package/dist/observability/index.js.map +0 -7
  505. package/dist/observability/metrics.d.ts.map +0 -1
  506. package/dist/observability/network-telemetry.d.ts.map +0 -1
  507. package/dist/observability/otel-tracer.d.ts.map +0 -1
  508. package/dist/observability/otlp-metrics.d.ts.map +0 -1
  509. package/dist/observability/otlp-traces.d.ts.map +0 -1
  510. package/dist/observability/process-telemetry.d.ts.map +0 -1
  511. package/dist/observability/prometheus.d.ts.map +0 -1
  512. package/dist/observability/redact-command.d.ts.map +0 -1
  513. package/dist/observability/tracer.d.ts.map +0 -1
  514. package/dist/plugin/api.d.ts.map +0 -1
  515. package/dist/plugin/config.d.ts.map +0 -1
  516. package/dist/plugin/index.d.ts.map +0 -1
  517. package/dist/plugin/index.js.map +0 -7
  518. package/dist/plugin/loader.d.ts.map +0 -1
  519. package/dist/plugins/auto-review-plugin.d.ts.map +0 -1
  520. package/dist/plugins/chimera-plugin.d.ts.map +0 -1
  521. package/dist/plugins/prompts-plugin.d.ts.map +0 -1
  522. package/dist/plugins/review-claim-registry.d.ts.map +0 -1
  523. package/dist/plugins/review-context-builder.d.ts.map +0 -1
  524. package/dist/plugins/review-finding-commands.d.ts.map +0 -1
  525. package/dist/plugins/review-finding-integration.d.ts.map +0 -1
  526. package/dist/plugins/review-finding-parser.d.ts.map +0 -1
  527. package/dist/plugins/review-finding-store.d.ts.map +0 -1
  528. package/dist/plugins/review-finding-types.d.ts.map +0 -1
  529. package/dist/plugins/review-report-integration.d.ts.map +0 -1
  530. package/dist/plugins/review-report-store.d.ts.map +0 -1
  531. package/dist/plugins/review-report-types.d.ts.map +0 -1
  532. package/dist/plugins/review-types.d.ts.map +0 -1
  533. package/dist/plugins/skills-plugin.d.ts.map +0 -1
  534. package/dist/plugins/sync-plugin.d.ts.map +0 -1
  535. package/dist/prompts/index.d.ts.map +0 -1
  536. package/dist/prompts/prompt-installer.d.ts.map +0 -1
  537. package/dist/prompts/prompt-manifest-store.d.ts.map +0 -1
  538. package/dist/registry/index.d.ts.map +0 -1
  539. package/dist/registry/index.js.map +0 -7
  540. package/dist/registry/provider-registry.d.ts.map +0 -1
  541. package/dist/registry/slash-command-registry.d.ts.map +0 -1
  542. package/dist/registry/tool-registry.d.ts.map +0 -1
  543. package/dist/replay/hash.d.ts.map +0 -1
  544. package/dist/replay/index.d.ts.map +0 -1
  545. package/dist/replay/index.js.map +0 -7
  546. package/dist/replay/replay-provider-runner.d.ts.map +0 -1
  547. package/dist/security/capabilities.d.ts.map +0 -1
  548. package/dist/security/config-secrets.d.ts.map +0 -1
  549. package/dist/security/directory-permission-policy.d.ts.map +0 -1
  550. package/dist/security/directory-policy-schema.d.ts.map +0 -1
  551. package/dist/security/index.d.ts.map +0 -1
  552. package/dist/security/index.js.map +0 -7
  553. package/dist/security/kanban-boundary.d.ts.map +0 -1
  554. package/dist/security/permission-policy-schema.d.ts.map +0 -1
  555. package/dist/security/permission-policy.d.ts.map +0 -1
  556. package/dist/security/readonly-permission-policy.d.ts.map +0 -1
  557. package/dist/security/secret-scrubber.d.ts.map +0 -1
  558. package/dist/security/secret-vault.d.ts.map +0 -1
  559. package/dist/security/trust-boundary.d.ts.map +0 -1
  560. package/dist/security/yolo-risk.d.ts.map +0 -1
  561. package/dist/session-registry-atomic-file.d.ts.map +0 -1
  562. package/dist/session-registry-types.d.ts.map +0 -1
  563. package/dist/session-registry.d.ts.map +0 -1
  564. package/dist/skills/foreign-sources.d.ts.map +0 -1
  565. package/dist/skills/frontmatter.d.ts.map +0 -1
  566. package/dist/skills/github-fetcher.d.ts.map +0 -1
  567. package/dist/skills/index.d.ts.map +0 -1
  568. package/dist/skills/index.js.map +0 -7
  569. package/dist/skills/limits.d.ts.map +0 -1
  570. package/dist/skills/manifest-store.d.ts.map +0 -1
  571. package/dist/skills/registry/github-direct-adapter.d.ts.map +0 -1
  572. package/dist/skills/registry/registry-adapter.d.ts.map +0 -1
  573. package/dist/skills/registry/skills-sh-adapter.d.ts.map +0 -1
  574. package/dist/skills/skill-generator.d.ts.map +0 -1
  575. package/dist/skills/skill-installer.d.ts.map +0 -1
  576. package/dist/storage/annotations-store.d.ts.map +0 -1
  577. package/dist/storage/attachment-store.d.ts.map +0 -1
  578. package/dist/storage/cloud-sync.d.ts.map +0 -1
  579. package/dist/storage/completed-work-checkpoint.d.ts.map +0 -1
  580. package/dist/storage/config-loader/bootstrap.d.ts.map +0 -1
  581. package/dist/storage/config-loader/default-repair.d.ts.map +0 -1
  582. package/dist/storage/config-loader/defaults.d.ts.map +0 -1
  583. package/dist/storage/config-loader/diagnostics.d.ts.map +0 -1
  584. package/dist/storage/config-loader/env-overrides.d.ts.map +0 -1
  585. package/dist/storage/config-loader/in-project-policy.d.ts.map +0 -1
  586. package/dist/storage/config-loader/inline-provider-models.d.ts.map +0 -1
  587. package/dist/storage/config-loader/legacy-sage-migration.d.ts.map +0 -1
  588. package/dist/storage/config-loader/path-identity.d.ts.map +0 -1
  589. package/dist/storage/config-loader/types.d.ts.map +0 -1
  590. package/dist/storage/config-loader/validation.d.ts.map +0 -1
  591. package/dist/storage/config-loader.d.ts.map +0 -1
  592. package/dist/storage/config-migration.d.ts.map +0 -1
  593. package/dist/storage/config-store.d.ts.map +0 -1
  594. package/dist/storage/director-state.d.ts.map +0 -1
  595. package/dist/storage/file-session-writer.d.ts.map +0 -1
  596. package/dist/storage/goal-coordination.d.ts.map +0 -1
  597. package/dist/storage/goal-kanban.d.ts.map +0 -1
  598. package/dist/storage/goal-store.d.ts.map +0 -1
  599. package/dist/storage/index.d.ts.map +0 -1
  600. package/dist/storage/index.js.map +0 -7
  601. package/dist/storage/input-history-store.d.ts.map +0 -1
  602. package/dist/storage/memory-backend.d.ts.map +0 -1
  603. package/dist/storage/memory-consolidator.d.ts.map +0 -1
  604. package/dist/storage/memory-graph-backend.d.ts.map +0 -1
  605. package/dist/storage/plan-store.d.ts.map +0 -1
  606. package/dist/storage/plan-templates.d.ts.map +0 -1
  607. package/dist/storage/prompt-store.d.ts.map +0 -1
  608. package/dist/storage/prompt-usage-store.d.ts.map +0 -1
  609. package/dist/storage/provider-config-watcher.d.ts.map +0 -1
  610. package/dist/storage/queue-store.d.ts.map +0 -1
  611. package/dist/storage/recovery-lock.d.ts.map +0 -1
  612. package/dist/storage/replay-log-store.d.ts.map +0 -1
  613. package/dist/storage/session-analyzer.d.ts.map +0 -1
  614. package/dist/storage/session-checkpoint-cas.d.ts.map +0 -1
  615. package/dist/storage/session-event-bridge.d.ts.map +0 -1
  616. package/dist/storage/session-helpers.d.ts.map +0 -1
  617. package/dist/storage/session-id-resolver.d.ts.map +0 -1
  618. package/dist/storage/session-id.d.ts.map +0 -1
  619. package/dist/storage/session-read-scrubber.d.ts.map +0 -1
  620. package/dist/storage/session-reader.d.ts.map +0 -1
  621. package/dist/storage/session-recovery.d.ts.map +0 -1
  622. package/dist/storage/session-resume-validation.d.ts.map +0 -1
  623. package/dist/storage/session-rewind-apply.d.ts.map +0 -1
  624. package/dist/storage/session-rewinder.d.ts.map +0 -1
  625. package/dist/storage/session-store/delete-session-artifacts.d.ts.map +0 -1
  626. package/dist/storage/session-store/delete-session-guards.d.ts.map +0 -1
  627. package/dist/storage/session-store/directory-scan.d.ts.map +0 -1
  628. package/dist/storage/session-store/directory-session-files.d.ts.map +0 -1
  629. package/dist/storage/session-store/events.d.ts.map +0 -1
  630. package/dist/storage/session-store/fork-session.d.ts.map +0 -1
  631. package/dist/storage/session-store/index-reader.d.ts.map +0 -1
  632. package/dist/storage/session-store/load-cache.d.ts.map +0 -1
  633. package/dist/storage/session-store/load-session-data.d.ts.map +0 -1
  634. package/dist/storage/session-store/paths.d.ts.map +0 -1
  635. package/dist/storage/session-store/prune-helpers.d.ts.map +0 -1
  636. package/dist/storage/session-store/replay.d.ts.map +0 -1
  637. package/dist/storage/session-store/search-events.d.ts.map +0 -1
  638. package/dist/storage/session-store/shard-manifest.d.ts.map +0 -1
  639. package/dist/storage/session-store/summary-builder.d.ts.map +0 -1
  640. package/dist/storage/session-store/summary-header.d.ts.map +0 -1
  641. package/dist/storage/session-store/types.d.ts.map +0 -1
  642. package/dist/storage/session-store.d.ts.map +0 -1
  643. package/dist/storage/session-summary.d.ts.map +0 -1
  644. package/dist/storage/session-tool-call-ends.d.ts.map +0 -1
  645. package/dist/storage/session-writer-scrubber.d.ts.map +0 -1
  646. package/dist/storage/session-writer-truncate.d.ts.map +0 -1
  647. package/dist/storage/storage-concurrency.d.ts.map +0 -1
  648. package/dist/storage/task-store.d.ts.map +0 -1
  649. package/dist/storage/todos-checkpoint.d.ts.map +0 -1
  650. package/dist/storage/tool-audit-log.d.ts.map +0 -1
  651. package/dist/tasking/index.d.ts.map +0 -1
  652. package/dist/tasking/index.js.map +0 -7
  653. package/dist/tasking/task-store.d.ts.map +0 -1
  654. package/dist/tasking/task-tracker.d.ts.map +0 -1
  655. package/dist/tools/council-tool.d.ts.map +0 -1
  656. package/dist/tools/fallback-chain-manage-tool.d.ts.map +0 -1
  657. package/dist/tools/fallback-favorite-manage-tool.d.ts.map +0 -1
  658. package/dist/tools/fallback-manage-helpers.d.ts.map +0 -1
  659. package/dist/tools/fallback-manage-tool-options.d.ts.map +0 -1
  660. package/dist/tools/fallback-manage-tools.d.ts.map +0 -1
  661. package/dist/tools/fallback-model-ref-parse.d.ts.map +0 -1
  662. package/dist/tools/fallback-provider-key-store.d.ts.map +0 -1
  663. package/dist/tools/fallback-system-config-view-tool.d.ts.map +0 -1
  664. package/dist/tools/index.d.ts.map +0 -1
  665. package/dist/tools/index.js.map +0 -7
  666. package/dist/tools/mcp-control.d.ts.map +0 -1
  667. package/dist/tools/mcp-use.d.ts.map +0 -1
  668. package/dist/tools/one-shot-llm-tool.d.ts.map +0 -1
  669. package/dist/tools/plugin-manager.d.ts.map +0 -1
  670. package/dist/types/agent-bridge.d.ts.map +0 -1
  671. package/dist/types/attachment.d.ts.map +0 -1
  672. package/dist/types/autonomy.d.ts.map +0 -1
  673. package/dist/types/blocks.d.ts.map +0 -1
  674. package/dist/types/compactor.d.ts.map +0 -1
  675. package/dist/types/config/autonomy.d.ts.map +0 -1
  676. package/dist/types/config/context.d.ts.map +0 -1
  677. package/dist/types/config/fleet-chat.d.ts.map +0 -1
  678. package/dist/types/config/mcp-features.d.ts.map +0 -1
  679. package/dist/types/config/providers.d.ts.map +0 -1
  680. package/dist/types/config/root.d.ts.map +0 -1
  681. package/dist/types/config/runtime.d.ts.map +0 -1
  682. package/dist/types/config/skills-fleet-brain.d.ts.map +0 -1
  683. package/dist/types/config/tools.d.ts.map +0 -1
  684. package/dist/types/config.d.ts.map +0 -1
  685. package/dist/types/context-evidence.d.ts.map +0 -1
  686. package/dist/types/context-window.d.ts.map +0 -1
  687. package/dist/types/council.d.ts.map +0 -1
  688. package/dist/types/default-config.d.ts.map +0 -1
  689. package/dist/types/design-kit.d.ts.map +0 -1
  690. package/dist/types/error-handler.d.ts.map +0 -1
  691. package/dist/types/errors.d.ts.map +0 -1
  692. package/dist/types/file-event-record.d.ts.map +0 -1
  693. package/dist/types/hooks.d.ts.map +0 -1
  694. package/dist/types/index.d.ts.map +0 -1
  695. package/dist/types/index.js.map +0 -7
  696. package/dist/types/input-reader.d.ts.map +0 -1
  697. package/dist/types/logger.d.ts.map +0 -1
  698. package/dist/types/memory.d.ts.map +0 -1
  699. package/dist/types/messages.d.ts.map +0 -1
  700. package/dist/types/mode-prompts.d.ts.map +0 -1
  701. package/dist/types/mode.d.ts.map +0 -1
  702. package/dist/types/models-registry.d.ts.map +0 -1
  703. package/dist/types/multi-agent.d.ts.map +0 -1
  704. package/dist/types/observability.d.ts.map +0 -1
  705. package/dist/types/one-shot-llm.d.ts.map +0 -1
  706. package/dist/types/path-resolver.d.ts.map +0 -1
  707. package/dist/types/permission.d.ts.map +0 -1
  708. package/dist/types/plugin.d.ts.map +0 -1
  709. package/dist/types/prompt-registry.d.ts.map +0 -1
  710. package/dist/types/prompt.d.ts.map +0 -1
  711. package/dist/types/provider-runner.d.ts.map +0 -1
  712. package/dist/types/provider.d.ts.map +0 -1
  713. package/dist/types/quota-regex.d.ts.map +0 -1
  714. package/dist/types/renderer.d.ts.map +0 -1
  715. package/dist/types/retry-policy.d.ts.map +0 -1
  716. package/dist/types/secret-scrubber.d.ts.map +0 -1
  717. package/dist/types/secret-vault.d.ts.map +0 -1
  718. package/dist/types/selector.d.ts.map +0 -1
  719. package/dist/types/session-markers.d.ts.map +0 -1
  720. package/dist/types/session-markers.js.map +0 -7
  721. package/dist/types/session-reader.d.ts.map +0 -1
  722. package/dist/types/session-rewinder.d.ts.map +0 -1
  723. package/dist/types/session.d.ts.map +0 -1
  724. package/dist/types/side-effect.d.ts.map +0 -1
  725. package/dist/types/skill.d.ts.map +0 -1
  726. package/dist/types/slash-command.d.ts.map +0 -1
  727. package/dist/types/spec.d.ts.map +0 -1
  728. package/dist/types/system-prompt-contributor.d.ts.map +0 -1
  729. package/dist/types/system-prompt.d.ts.map +0 -1
  730. package/dist/types/task-graph.d.ts.map +0 -1
  731. package/dist/types/token-counter.d.ts.map +0 -1
  732. package/dist/types/tool-executor.d.ts.map +0 -1
  733. package/dist/types/tool-markers.d.ts.map +0 -1
  734. package/dist/types/tool.d.ts.map +0 -1
  735. package/dist/types/utility-types.d.ts.map +0 -1
  736. package/dist/utils/assert-never.d.ts.map +0 -1
  737. package/dist/utils/atomic-write.d.ts.map +0 -1
  738. package/dist/utils/cache-key.d.ts.map +0 -1
  739. package/dist/utils/child-env.d.ts.map +0 -1
  740. package/dist/utils/color.d.ts.map +0 -1
  741. package/dist/utils/compaction-preview.d.ts.map +0 -1
  742. package/dist/utils/config-backup.d.ts.map +0 -1
  743. package/dist/utils/config-json.d.ts.map +0 -1
  744. package/dist/utils/connectivity.d.ts.map +0 -1
  745. package/dist/utils/context-breakdown.d.ts.map +0 -1
  746. package/dist/utils/context-evidence.d.ts.map +0 -1
  747. package/dist/utils/continuous-memory-profiler.d.ts.map +0 -1
  748. package/dist/utils/crash-shield.d.ts.map +0 -1
  749. package/dist/utils/deep-merge.d.ts.map +0 -1
  750. package/dist/utils/diff.d.ts.map +0 -1
  751. package/dist/utils/error.d.ts.map +0 -1
  752. package/dist/utils/error.js.map +0 -7
  753. package/dist/utils/expect-defined.d.ts.map +0 -1
  754. package/dist/utils/expect-defined.js.map +0 -7
  755. package/dist/utils/glob-expand.d.ts.map +0 -1
  756. package/dist/utils/glob-match.d.ts.map +0 -1
  757. package/dist/utils/heap-watchdog-types.d.ts.map +0 -1
  758. package/dist/utils/heap-watchdog.d.ts.map +0 -1
  759. package/dist/utils/heap-watchdog.js.map +0 -7
  760. package/dist/utils/incoming-images.d.ts.map +0 -1
  761. package/dist/utils/index.d.ts.map +0 -1
  762. package/dist/utils/index.js.map +0 -7
  763. package/dist/utils/instruction-file.d.ts.map +0 -1
  764. package/dist/utils/ip-guard.d.ts.map +0 -1
  765. package/dist/utils/json-repair.d.ts.map +0 -1
  766. package/dist/utils/json-schema-validate.d.ts.map +0 -1
  767. package/dist/utils/lru-cache.d.ts.map +0 -1
  768. package/dist/utils/memory-flight-recorder.d.ts.map +0 -1
  769. package/dist/utils/merge-custom-models.d.ts.map +0 -1
  770. package/dist/utils/merge-models-payload.d.ts.map +0 -1
  771. package/dist/utils/message-invariants.d.ts.map +0 -1
  772. package/dist/utils/newline-normalize.d.ts.map +0 -1
  773. package/dist/utils/perf-profile.d.ts.map +0 -1
  774. package/dist/utils/pid.d.ts.map +0 -1
  775. package/dist/utils/project-identity.d.ts.map +0 -1
  776. package/dist/utils/project-watch.d.ts.map +0 -1
  777. package/dist/utils/regex-guard.d.ts.map +0 -1
  778. package/dist/utils/safe-json.d.ts.map +0 -1
  779. package/dist/utils/sage-output-block.d.ts.map +0 -1
  780. package/dist/utils/session-scoped-path.d.ts.map +0 -1
  781. package/dist/utils/sleep.d.ts.map +0 -1
  782. package/dist/utils/slug.d.ts.map +0 -1
  783. package/dist/utils/socket-path.d.ts.map +0 -1
  784. package/dist/utils/sqlite-warning.d.ts.map +0 -1
  785. package/dist/utils/string.d.ts.map +0 -1
  786. package/dist/utils/task-format.d.ts.map +0 -1
  787. package/dist/utils/term.d.ts.map +0 -1
  788. package/dist/utils/todos-format.d.ts.map +0 -1
  789. package/dist/utils/token-estimate.d.ts.map +0 -1
  790. package/dist/utils/tool-description-mode.d.ts.map +0 -1
  791. package/dist/utils/tool-name.d.ts.map +0 -1
  792. package/dist/utils/tool-output-serializer.d.ts.map +0 -1
  793. package/dist/utils/tool-result-render-mode.d.ts.map +0 -1
  794. package/dist/utils/tool-subject.d.ts.map +0 -1
  795. package/dist/utils/tool-wire-compact.d.ts.map +0 -1
  796. package/dist/utils/tree-kill.d.ts.map +0 -1
  797. package/dist/utils/tree-kill.js.map +0 -7
  798. package/dist/utils/ulid.d.ts.map +0 -1
  799. package/dist/utils/walk-ignore.d.ts.map +0 -1
  800. package/dist/utils/wstack-paths.d.ts.map +0 -1
  801. package/dist/worktree/index.d.ts.map +0 -1
  802. package/dist/worktree/index.js.map +0 -7
  803. package/dist/worktree/worktree-git.d.ts.map +0 -1
  804. package/dist/worktree/worktree-managed-ops.d.ts.map +0 -1
  805. package/dist/worktree/worktree-manager.d.ts.map +0 -1
  806. package/dist/worktree/worktree-types.d.ts.map +0 -1
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/tasking/task-store.ts", "../../src/utils/error.ts", "../../src/types/errors.ts", "../../src/types/task-graph.ts", "../../src/tasking/task-tracker.ts", "../../src/goal/phase-graph-builder.ts", "../../src/infrastructure/logger.ts", "../../src/utils/term.ts", "../../src/utils/color.ts", "../../src/goal/phase-board-mutations.ts", "../../src/goal/phase-orchestrator-queries.ts", "../../src/goal/phase-orchestrator-integration.ts", "../../src/goal/phase-orchestrator-runtime.ts", "../../src/goal/phase-orchestrator.ts", "../../src/goal/goal-runner.ts", "../../src/utils/instruction-file.ts", "../../src/goal/goal-planner.ts", "../../src/goal/goal-assessor.ts", "../../src/goal/types.ts", "../../src/goal/phase-store.ts", "../../src/utils/atomic-write.ts", "../../src/storage/goal-store.ts", "../../src/utils/wstack-paths.ts", "../../src/goal/checkpoint.ts"],
4
- "sourcesContent": ["import type { TaskGraph } from '../types/task-graph.js';\nimport type { TaskStore } from './task-tracker.js';\n\n/**\n * In-memory task-graph store used by Goal and tests.\n *\n * The store clones the graph container on read/write so callers cannot replace\n * its Maps/arrays behind the store's back. Task nodes themselves intentionally\n * remain shared: TaskTracker owns node mutation and persists after each change.\n */\nexport class DefaultTaskStore implements TaskStore {\n private readonly graphs = new Map<string, TaskGraph>();\n\n async saveGraph(graph: TaskGraph): Promise<void> {\n this.graphs.set(graph.id, this.cloneGraph(graph));\n }\n\n async loadGraph(id: string): Promise<TaskGraph | null> {\n const graph = this.graphs.get(id);\n return graph ? this.cloneGraph(graph) : null;\n }\n\n async listGraphs(): Promise<Array<{ id: string; title: string; updatedAt: number }>> {\n return Array.from(this.graphs.values()).map((graph) => ({\n id: graph.id,\n title: graph.title,\n updatedAt: graph.updatedAt,\n }));\n }\n\n async deleteGraph(id: string): Promise<void> {\n this.graphs.delete(id);\n }\n\n private cloneGraph(graph: TaskGraph): TaskGraph {\n return {\n ...graph,\n nodes: new Map(graph.nodes),\n edges: [...graph.edges],\n rootNodes: [...graph.rootNodes],\n };\n }\n}\n", "/**\n * Converts an unknown error value to a human-readable string.\n * Used in 40+ files across the codebase to normalize error messaging.\n */\nexport function toErrorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n", "import { toErrorMessage } from '../utils/error.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// \u2500\u2500 Error codes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n PARSE_FAILED: 'PARSE_FAILED',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` \u2014 no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// \u2500\u2500 Base error class \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// \u2500\u2500 Specific error classes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Tool execution errors \u2014 thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors \u2014 thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors \u2014 spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n/**\n * HTTP fetch error \u2014 thrown when a network request returns a non-OK status.\n * Carries the response status so {@link classifyToolError} can branch on it\n * (429 \u2192 transient, 404 \u2192 not_found, 401 \u2192 permission) without duck-typing\n * the error via `'response' in err`.\n *\n * P3 #18 (before-release.md): the previous `'response' in err` check caught\n * any Error with a `response` property, including custom errors, proxy\n * objects, or mocked errors in tests. `instanceof FetchError` is reliable.\n *\n * Tools and providers that make HTTP requests and need the executor to\n * classify their failures should throw `new FetchError({ status, message })`\n * instead of a bare `Error` with an ad-hoc `response` field.\n */\nexport class FetchError extends WrongStackError {\n readonly status: number;\n\n constructor(opts: {\n message: string;\n status: number;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.VALIDATION_ERROR,\n subsystem: 'general',\n severity: 'error',\n recoverable: opts.status === 429 || opts.status >= 500,\n context: { status: opts.status, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FetchError';\n this.status = opts.status;\n }\n}\n\n/**\n * Tool input validation error \u2014 thrown when a tool's input fails a validation\n * check that the JSON Schema cannot express (e.g. `old_string === new_string`\n * in edit, or a cross-field invariant). Use this instead of a bare\n * `throw new Error('...validation...')` so {@link classifyToolError} can\n * match on `instanceof` rather than a locale-dependent message substring.\n *\n * P2 #6 (before-release.md): the previous `err.message.includes('validation')`\n * check misclassified any error whose message happened to contain \"validation\"\n * (e.g. a third-party \"input validation timeout\") as a VALIDATION error.\n *\n * Named `ToolValidationError` (not `ValidationError`) to avoid colliding with\n * the existing `ValidationError` interface exported by json-schema-validate.ts\n * (a validation-result shape, not an Error subclass).\n */\nexport class ToolValidationError extends WrongStackError {\n constructor(opts: {\n message: string;\n /** Field path or tool name that failed validation, for diagnostics. */\n field?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.VALIDATION_ERROR,\n subsystem: 'general',\n severity: 'error',\n recoverable: false,\n context: { field: opts.field, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolValidationError';\n }\n}\n\n/**\n * Response / payload parse error \u2014 thrown when an upstream HTTP response,\n * file, or data structure is well-formed at the transport layer (HTTP 200,\n * valid JSON) but is missing required fields or has an unexpected shape.\n *\n * Distinct from `ConfigError(CONFIG_PARSE_FAILED)` (which is specifically\n * for config-file parsing) and `FetchError` (which covers HTTP non-OK\n * responses). `ParseError` fills the gap: the request succeeded but the\n * response body couldn't be interpreted.\n *\n * Common sites: OAuth token responses missing `access_token`, device-code\n * responses missing `device_code`, registry responses with unexpected\n * schemas.\n */\nexport class ParseError extends WrongStackError {\n readonly source?: string | undefined;\n\n constructor(opts: {\n message: string;\n /**\n * What was being parsed \u2014 e.g. `'oauth-token-response'`,\n * `'device-code-response'`. Lets consumers distinguish parse failures\n * from different upstream APIs without parsing the message.\n */\n source?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.PARSE_FAILED,\n subsystem: 'general',\n severity: 'error',\n recoverable: false,\n context: { source: opts.source, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ParseError';\n this.source = opts.source;\n }\n}\n\n// \u2500\u2500 Type guards \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isToolValidationError(err: unknown): err is ToolValidationError {\n return err instanceof ToolValidationError;\n}\n\nexport function isFetchError(err: unknown): err is FetchError {\n return err instanceof FetchError;\n}\n\nexport function isParseError(err: unknown): err is ParseError {\n return err instanceof ParseError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n", "export type TaskStatus = 'pending' | 'in_progress' | 'blocked' | 'failed' | 'review' | 'completed';\nexport type TaskPriority = 'critical' | 'high' | 'medium' | 'low';\nexport type TaskType = 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'chore';\n\nexport interface TaskNode {\n id: string;\n title: string;\n description: string;\n type: TaskType;\n priority: TaskPriority;\n status: TaskStatus;\n assignee?: string | undefined;\n estimateHours?: number | undefined;\n actualHours?: number | undefined;\n tags?: string[] | undefined;\n specRequirementId?: string | undefined;\n parentId?: string | undefined;\n children?: string[] | undefined;\n createdAt: number;\n updatedAt: number;\n startedAt?: number | undefined; // set when status \u2192 in_progress\n completedAt?: number | undefined;\n metadata?: Record<string, unknown>;\n}\n\nexport interface TaskEdge {\n id: string;\n from: string;\n to: string;\n type: 'blocks' | 'depends_on' | 'relates_to' | 'implements';\n weight?: number | undefined;\n}\n\nexport interface TaskGraph {\n id: string;\n specId: string;\n title: string;\n nodes: Map<string, TaskNode>;\n edges: TaskEdge[];\n rootNodes: string[];\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface TaskDependency {\n taskId: string;\n blockedBy: string[];\n blocking: string[];\n}\n\nexport interface TaskAssignment {\n taskId: string;\n assignee: string;\n assignedAt: number;\n}\n\nexport interface TaskProgress {\n total: number;\n pending: number;\n inProgress: number;\n blocked: number;\n failed: number;\n review: number;\n completed: number;\n percentComplete: number;\n estimatedHours: number;\n actualHours: number;\n}\n\nexport interface TaskFilter {\n status?: TaskStatus[] | undefined;\n priority?: TaskPriority[] | undefined;\n type?: TaskType[] | undefined;\n assignee?: string[] | undefined;\n tags?: string[] | undefined;\n specRequirementId?: string | undefined;\n}\n\nexport interface TaskSort {\n field: 'priority' | 'createdAt' | 'updatedAt' | 'status';\n direction: 'asc' | 'desc';\n}\n\nexport interface CriticalPathResult {\n taskIds: string[];\n totalEstimateHours: number;\n bottleneckTasks: string[];\n}\n\nexport function computeTaskProgress(graph: TaskGraph): TaskProgress {\n let completed = 0;\n let pending = 0;\n let inProgress = 0;\n let blocked = 0;\n let failed = 0;\n let review = 0;\n let estimatedHours = 0;\n let actualHours = 0;\n for (const n of graph.nodes.values()) {\n switch (n.status) {\n case 'completed':\n completed++;\n break;\n case 'pending':\n pending++;\n break;\n case 'in_progress':\n inProgress++;\n break;\n case 'blocked':\n blocked++;\n break;\n case 'failed':\n failed++;\n break;\n case 'review':\n review++;\n break;\n }\n estimatedHours += n.estimateHours ?? 0;\n actualHours += n.actualHours ?? 0;\n }\n const total = graph.nodes.size;\n\n return {\n total,\n pending,\n inProgress,\n blocked,\n failed,\n review,\n completed,\n percentComplete: total > 0 ? Math.round((completed / total) * 100) : 0,\n estimatedHours,\n actualHours,\n };\n}\n\nexport function findCriticalPath(graph: TaskGraph): CriticalPathResult {\n const nodes = Array.from(graph.nodes.values());\n const criticalNodes = nodes.filter((n) => n.priority === 'critical');\n const bottleneckTasks = criticalNodes\n .filter((n) => graph.edges.some((e) => e.to === n.id && e.type === 'depends_on'))\n .map((n) => n.id);\n\n const totalEstimateHours = criticalNodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);\n\n return {\n taskIds: criticalNodes.map((n) => n.id),\n totalEstimateHours,\n bottleneckTasks,\n };\n}\n\nexport function topologicalSort(graph: TaskGraph): string[] {\n const visited = new Set<string>();\n const inStack = new Set<string>();\n const result: string[] = [];\n\n function visit(id: string): void {\n // Cycle: callers must detect cycles up-front if they care; we just stop recursing.\n if (inStack.has(id)) return;\n if (visited.has(id)) return;\n if (!graph.nodes.has(id)) return;\n\n visited.add(id);\n inStack.add(id);\n\n for (const edge of graph.edges) {\n if (edge.from === id) visit(edge.to);\n }\n\n inStack.delete(id);\n result.push(id);\n }\n\n for (const rootId of graph.rootNodes) {\n visit(rootId);\n }\n\n return result;\n}\n\nexport type SerializableTaskGraphNodes =\n | TaskNode[]\n | Array<[string, TaskNode]>\n | Record<string, TaskNode>;\n\nexport type SerializableTaskGraph = Omit<TaskGraph, 'nodes'> & {\n nodes: SerializableTaskGraphNodes;\n};\n\nexport type SerializedTaskGraph = Omit<TaskGraph, 'nodes'> & {\n nodes: TaskNode[];\n};\n\nexport function serializeTaskGraph(graph: TaskGraph): SerializedTaskGraph {\n return {\n ...graph,\n nodes: Array.from(graph.nodes.values()),\n };\n}\n\nexport function deserializeTaskGraph(input: SerializableTaskGraph): TaskGraph {\n const nodes = new Map<string, TaskNode>();\n if (Array.isArray(input.nodes)) {\n for (const entry of input.nodes) {\n if (Array.isArray(entry)) nodes.set(entry[0], { ...entry[1], id: entry[1].id || entry[0] });\n else nodes.set(entry.id, entry);\n }\n } else {\n for (const [id, node] of Object.entries(input.nodes)) {\n nodes.set(id, { ...node, id: node.id || id });\n }\n }\n return { ...input, nodes };\n}\n", "import { ERROR_CODES, SddError } from '../types/errors.js';\nimport type {\n TaskFilter,\n TaskGraph,\n TaskNode,\n TaskProgress,\n TaskSort,\n} from '../types/task-graph.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\nimport { toErrorMessage } from '../utils/error.js';\n\nexport interface TaskStore {\n saveGraph(graph: TaskGraph): Promise<void>;\n loadGraph(id: string): Promise<TaskGraph | null>;\n listGraphs(): Promise<{ id: string; title: string; updatedAt: number }[]>;\n deleteGraph(id: string): Promise<void>;\n}\n\nexport interface TaskTrackerOptions {\n store: TaskStore;\n /**\n * Called when an in-the-background persistence (`saveGraph`) rejects.\n * The synchronous TaskTracker methods (addNode/addEdge/updateNodeStatus)\n * fire-and-forget their writes; without this, a failing store silently\n * loses graph mutations. Defaults to a console.warn.\n */\n onPersistError?: ((err: unknown) => void) | undefined;\n}\n\nexport interface TaskTransition {\n from: TaskNode['status'];\n to: TaskNode['status'];\n timestamp: number;\n reason?: string | undefined;\n}\n\n/** A change notification emitted to `TaskTracker.subscribe` listeners. */\nexport interface TaskTrackerChange {\n type: 'node_added' | 'node_updated' | 'status_changed' | 'node_removed';\n nodeId: string;\n /** For `node_removed` this is the node as it was just before deletion. */\n node: TaskNode;\n transition?: TaskTransition | undefined;\n}\n\nexport type TaskTrackerListener = (change: TaskTrackerChange) => void;\n\nexport class TaskTracker {\n private graph: TaskGraph | null = null;\n private transitions: TaskTransition[] = [];\n private listeners: TaskTrackerListener[] = [];\n private static readonly MAX_TRANSITIONS = 10_000;\n\n constructor(private readonly opts: TaskTrackerOptions) {}\n\n /**\n * Subscribe to live task mutations (add / update / status change). Returns an\n * unsubscribe fn. This is the hook the board projector uses to stream a live\n * snapshot \u2014 the tracker was previously fire-and-forget with no observability.\n */\n subscribe(listener: TaskTrackerListener): () => void {\n this.listeners.push(listener);\n return () => {\n const i = this.listeners.indexOf(listener);\n if (i >= 0) this.listeners.splice(i, 1);\n };\n }\n\n private notifyChange(change: TaskTrackerChange): void {\n for (const l of this.listeners) {\n try {\n l(change);\n } catch {\n // A faulty listener must never break a tracker mutation.\n }\n }\n }\n\n /**\n * Attach an existing graph (used by PhaseOrchestrator to associate a tracker\n * with a phase's pre-built task graph without re-creating it).\n */\n setGraph(graph: TaskGraph): void {\n this.graph = graph;\n }\n\n async createGraph(specId: string, title: string): Promise<TaskGraph> {\n this.graph = {\n id: crypto.randomUUID(),\n specId,\n title,\n nodes: new Map(),\n edges: [],\n rootNodes: [],\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n await this.opts.store.saveGraph(this.graph);\n return this.graph;\n }\n\n async loadGraph(id: string): Promise<TaskGraph | null> {\n this.graph = await this.opts.store.loadGraph(id);\n return this.graph;\n }\n\n addNode(node: Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'>): TaskNode {\n if (!this.graph)\n throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const now = Date.now();\n const newNode: TaskNode = {\n ...node,\n id: crypto.randomUUID(),\n status: node.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n\n this.graph.nodes.set(newNode.id, newNode);\n\n if (!node.parentId) {\n this.graph.rootNodes.push(newNode.id);\n }\n\n this.graph.updatedAt = now;\n this.persist();\n this.notifyChange({ type: 'node_added', nodeId: newNode.id, node: newNode });\n\n return newNode;\n }\n\n addEdge(from: string, to: string, type: TaskGraph['edges'][0]['type'] = 'depends_on'): void {\n if (!this.graph)\n throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n this.graph.edges.push({\n id: crypto.randomUUID(),\n from,\n to,\n type,\n });\n this.graph.updatedAt = Date.now();\n this.persist();\n }\n\n /**\n * Declare that `taskId` depends on `depId` (a `depends_on` edge `depId \u2192 taskId`),\n * guarding against self-loops, duplicates, missing nodes, and cycles. Returns\n * true if the dependency now holds (added or already present), false if it was\n * rejected (would create a cycle / unknown node). This is the safe entry point\n * for wiring agent-declared `dependsOn` references into the graph.\n */\n addDependency(depId: string, taskId: string): boolean {\n if (!this.graph) return false;\n if (depId === taskId) return false;\n if (!this.graph.nodes.has(depId) || !this.graph.nodes.has(taskId)) return false;\n // Already a blocker \u2014 idempotent success.\n if (this.getBlockers(taskId).includes(depId)) return true;\n // Cycle guard: if `depId` already (transitively) depends on `taskId`, adding\n // `taskId \u2192 depId` would close a loop. Reject rather than deadlock the run.\n if (this.dependsOnTransitively(depId, taskId, new Set())) return false;\n this.addEdge(depId, taskId, 'depends_on');\n return true;\n }\n\n /** True when `taskId` transitively depends on `targetId` (follows depends_on blockers). */\n private dependsOnTransitively(taskId: string, targetId: string, seen: Set<string>): boolean {\n if (taskId === targetId) return true;\n if (seen.has(taskId)) return false;\n seen.add(taskId);\n for (const blocker of this.getBlockers(taskId)) {\n if (this.dependsOnTransitively(blocker, targetId, seen)) return true;\n }\n return false;\n }\n\n /**\n * Merge `patch` into a node's `metadata` (used for per-task model/provider/\n * fallback assignment and the cancel marker). Persists + notifies as a node\n * update. No-op if the node is missing.\n */\n patchMetadata(id: string, patch: Record<string, unknown>): void {\n if (!this.graph) return;\n const node = this.graph.nodes.get(id);\n if (!node) return;\n node.metadata = { ...node.metadata, ...patch };\n node.updatedAt = Date.now();\n this.graph.updatedAt = node.updatedAt;\n this.persist();\n this.notifyChange({ type: 'node_updated', nodeId: id, node });\n }\n\n /**\n * Remove a node and every edge touching it. Intended for deleting a task that\n * has not started yet \u2014 callers must gate on status (do not remove a running\n * task). Dependents simply lose this blocker (re-evaluated by `canStart`).\n * Returns true if a node was removed.\n */\n removeNode(id: string): boolean {\n if (!this.graph) return false;\n const node = this.graph.nodes.get(id);\n if (!node) return false;\n this.graph.nodes.delete(id);\n this.graph.edges = this.graph.edges.filter((e) => e.from !== id && e.to !== id);\n this.graph.rootNodes = this.graph.rootNodes.filter((r) => r !== id);\n // Detach from any parent's children list.\n for (const n of this.graph.nodes.values()) {\n if (n.children?.includes(id)) n.children = n.children.filter((c) => c !== id);\n }\n this.graph.updatedAt = Date.now();\n this.persist();\n this.notifyChange({ type: 'node_removed', nodeId: id, node });\n return true;\n }\n\n updateNodeStatus(id: string, status: TaskNode['status'], reason?: string): void {\n if (!this.graph)\n throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const node = this.graph.nodes.get(id);\n if (!node)\n throw new SddError({\n message: `Node ${id} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { nodeId: id },\n });\n\n const from = node.status;\n const now = Date.now();\n node.status = status;\n node.updatedAt = now;\n\n if (status === 'completed') {\n node.completedAt = now;\n node.startedAt = node.startedAt ?? now; // ensure startedAt is set\n }\n if (status === 'in_progress') {\n node.startedAt = now;\n }\n\n this.transitions.push({ from, to: status, timestamp: now, reason });\n if (this.transitions.length > TaskTracker.MAX_TRANSITIONS) {\n this.transitions.splice(0, this.transitions.length - TaskTracker.MAX_TRANSITIONS);\n }\n\n // Auto-unblock dependents\n if (status === 'completed') {\n this.unblockDependents(id);\n }\n\n // Auto-block blockers\n if (status === 'in_progress') {\n this.checkAndBlockIfNeeded(id);\n }\n\n this.graph.updatedAt = now;\n this.persist();\n this.notifyChange({\n type: 'status_changed',\n nodeId: id,\n node,\n transition: { from, to: status, timestamp: now, reason },\n });\n }\n\n updateNode(\n id: string,\n patch: Partial<\n Pick<TaskNode, 'title' | 'description' | 'priority' | 'estimateHours' | 'tags' | 'assignee'>\n >,\n ): void {\n if (!this.graph)\n throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const node = this.graph.nodes.get(id);\n if (!node)\n throw new SddError({\n message: `Node ${id} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { nodeId: id },\n });\n\n if (patch.title !== undefined) node.title = patch.title;\n if (patch.description !== undefined) node.description = patch.description;\n if (patch.priority !== undefined) node.priority = patch.priority;\n if (patch.estimateHours !== undefined) node.estimateHours = patch.estimateHours;\n if (patch.tags !== undefined) node.tags = patch.tags;\n if (patch.assignee !== undefined) node.assignee = patch.assignee;\n node.updatedAt = Date.now();\n this.graph.updatedAt = node.updatedAt;\n this.persist();\n this.notifyChange({ type: 'node_updated', nodeId: id, node });\n }\n\n getNode(id: string): TaskNode | undefined {\n return this.graph?.nodes.get(id);\n }\n\n getAllNodes(filter?: TaskFilter, sort?: TaskSort): TaskNode[] {\n if (!this.graph) return [];\n\n let nodes = Array.from(this.graph.nodes.values());\n\n if (filter) {\n nodes = nodes.filter((n) => {\n if (filter.status?.length && !filter.status.includes(n.status)) return false;\n if (filter.priority?.length && !filter.priority.includes(n.priority)) return false;\n if (filter.type?.length && !filter.type.includes(n.type)) return false;\n if (filter.assignee?.length && n.assignee && !filter.assignee.includes(n.assignee))\n return false;\n if (filter.tags?.length && n.tags && !n.tags.some((t) => filter.tags?.includes(t)))\n return false;\n if (filter.specRequirementId && n.specRequirementId !== filter.specRequirementId)\n return false;\n return true;\n });\n }\n\n if (sort) {\n nodes.sort((a, b) => {\n const cmp = compareByField(a, b, sort.field);\n return sort.direction === 'asc' ? cmp : -cmp;\n });\n }\n\n return nodes;\n }\n\n getChildren(parentId: string): TaskNode[] {\n if (!this.graph) return [];\n return Array.from(this.graph.nodes.values()).filter((n) => n.parentId === parentId);\n }\n\n getDependents(taskId: string): string[] {\n if (!this.graph) return [];\n return this.graph.edges\n .filter((e) => e.from === taskId && e.type === 'depends_on')\n .map((e) => e.to);\n }\n\n getBlockers(taskId: string): string[] {\n if (!this.graph) return [];\n return this.graph.edges\n .filter((e) => e.to === taskId && e.type === 'depends_on')\n .map((e) => e.from);\n }\n\n canStart(taskId: string): boolean {\n const blockers = this.getBlockers(taskId);\n return blockers.every((id) => {\n const node = this.graph?.nodes.get(id);\n // A task can start when all blockers are either completed or failed.\n // Failed blockers should not permanently deadlock dependent tasks.\n return node?.status === 'completed' || node?.status === 'failed';\n });\n }\n\n getProgress(): TaskProgress {\n if (!this.graph) {\n return {\n total: 0,\n pending: 0,\n inProgress: 0,\n blocked: 0,\n failed: 0,\n review: 0,\n completed: 0,\n percentComplete: 0,\n estimatedHours: 0,\n actualHours: 0,\n };\n }\n return computeTaskProgress(this.graph);\n }\n\n getTransitions(_taskId?: string): TaskTransition[] {\n return [...this.transitions];\n }\n\n private unblockDependents(completedId: string): void {\n if (!this.graph) return;\n const dependents = this.getDependents(completedId);\n for (const depId of dependents) {\n const dep = this.graph.nodes.get(depId);\n if (dep?.status === 'blocked') {\n // Check if all blockers are now completed\n const remainingBlockers = this.getBlockers(depId);\n const allUnblocked = remainingBlockers.every((id) => {\n const blocker = this.graph?.nodes.get(id);\n return blocker?.status === 'completed' || blocker?.status === 'failed';\n });\n if (allUnblocked) {\n dep.status = 'pending';\n dep.updatedAt = Date.now();\n }\n }\n }\n }\n\n private checkAndBlockIfNeeded(taskId: string): void {\n if (!this.graph) return;\n const blockers = this.getBlockers(taskId);\n const someBlocked = blockers.some((id) => {\n const blocker = this.graph?.nodes.get(id);\n // A task is only blocked by incomplete blockers that haven't failed.\n // Failed tasks should not block their dependents.\n return blocker?.status !== 'completed' && blocker?.status !== 'failed';\n });\n if (someBlocked) {\n const node = this.graph.nodes.get(taskId);\n if (node) {\n node.status = 'blocked';\n node.updatedAt = Date.now();\n }\n }\n }\n\n /**\n * Fire-and-forget persistence with attached error handler.\n * Synchronous mutators (addNode/addEdge/updateNodeStatus) use this to\n * avoid forcing an async cascade through every caller; if the store\n * is missing or throwing, the error is surfaced via onPersistError.\n */\n private persist(): void {\n if (!this.graph) return;\n this.opts.store.saveGraph(this.graph).catch((err) => {\n this.opts.onPersistError\n ? this.opts.onPersistError(err)\n : console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'task_tracker.save_graph_failed',\n message: toErrorMessage(err),\n timestamp: new Date().toISOString(),\n }),\n );\n });\n }\n}\n\n// Sort comparison helpers\nconst PRIORITY_RANK: Record<TaskNode['priority'], number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n};\nconst STATUS_RANK: Record<TaskNode['status'], number> = {\n in_progress: 0,\n pending: 1,\n review: 2,\n blocked: 3,\n failed: 4,\n completed: 5,\n};\n\nfunction compareByField(a: TaskNode, b: TaskNode, field: TaskSort['field']): number {\n switch (field) {\n case 'priority':\n return PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority];\n case 'status':\n return STATUS_RANK[a.status] - STATUS_RANK[b.status];\n case 'createdAt':\n return a.createdAt - b.createdAt;\n case 'updatedAt':\n return a.updatedAt - b.updatedAt;\n }\n}\n", "import { DefaultTaskStore, TaskTracker, type TaskStore } from '../tasking/index.js';\nimport type { TaskGraph, TaskPriority } from '../types/task-graph.js';\nimport type { PhaseGraph, PhaseNode, PhaseTemplate } from './types.js';\n\nexport interface PhaseGraphBuilderOptions {\n title: string;\n description?: string | undefined;\n /** Ordered phase templates. */\n phases: PhaseTemplate[];\n /** Autonomous mode. */\n autonomous?: boolean | undefined;\n /** Stop on failure. */\n stopOnFailure?: boolean | undefined;\n /** Optional external TaskStore. */\n externalTaskStore?: TaskStore | undefined;\n /** Split into separate kanban boards per phase. */\n multiBoard?: boolean | undefined;\n /** Run typecheck/lint verification after each task. */\n verifyTasks?: boolean | undefined;\n /** Enable chimera auto-review for this run. */\n chimeraReview?: boolean | undefined;\n}\n\n/**\n * PhaseGraphBuilder - builds project phases and a task graph for each phase.\n *\n * Usage:\n * const builder = new PhaseGraphBuilder({\n * title: 'Auth System Refactor',\n * phases: [\n * { name: 'Discovery', description: '...', priority: 'high', estimateHours: 2, parallelizable: false },\n * { name: 'Design', description: '...', priority: 'critical', estimateHours: 4, parallelizable: false },\n * { name: 'Implementation', description: '...', priority: 'critical', estimateHours: 12, parallelizable: false },\n * { name: 'Testing', description: '...', priority: 'high', estimateHours: 6, parallelizable: true },\n * { name: 'Deployment', description: '...', priority: 'medium', estimateHours: 2, parallelizable: false },\n * ]\n * });\n * const graph = await builder.build();\n */\nexport class PhaseGraphBuilder {\n constructor(private readonly opts: PhaseGraphBuilderOptions) {}\n\n async build(): Promise<PhaseGraph> {\n const graphId = crypto.randomUUID();\n const phases = new Map<string, PhaseNode>();\n const phaseIds: string[] = [];\n\n // Create a PhaseNode from each phase template.\n for (let i = 0; i < this.opts.phases.length; i++) {\n const tmpl = this.opts.phases[i] ?? { name: '', description: '', tasks: [], taskTemplates: [], parallelizable: false, priority: 'medium' as const, estimateHours: 0 };\n const phaseId = crypto.randomUUID();\n phaseIds.push(phaseId);\n\n // Use the external store or create a new in-memory task store.\n const store = this.opts.externalTaskStore ?? new DefaultTaskStore();\n const tracker = new TaskTracker({ store });\n const taskGraph = await tracker.createGraph(phaseId, `${tmpl.name} Tasks`);\n\n // Add task templates when present.\n if (tmpl.taskTemplates && tmpl.taskTemplates.length > 0) {\n for (const tt of tmpl.taskTemplates) {\n tracker.addNode({\n title: tt.title,\n description: tt.description,\n type: tt.type,\n priority: tt.priority,\n status: 'pending',\n estimateHours: tt.estimateHours,\n tags: tt.tags ?? [],\n });\n }\n }\n\n const phase: PhaseNode = {\n id: phaseId,\n name: tmpl.name,\n description: tmpl.description,\n status: 'pending',\n taskGraph,\n dependsOn: i > 0 ? [phaseIds[i - 1] ?? ''] : [],\n nextPhases: i < this.opts.phases.length - 1 ? [phaseIds[i + 1] ?? ''] : [],\n parallelizable: tmpl.parallelizable,\n priority: tmpl.priority,\n estimateHours: tmpl.estimateHours,\n assignedAgents: [],\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n\n phases.set(phaseId, phase);\n }\n\n // Second pass: fill in the forward `nextPhases` links \u2014 the next phase id was\n // not yet known while each phase was created. `dependsOn` (the backward link)\n // is already correct from the first pass (the previous id always exists), so\n // it is intentionally NOT recomputed here.\n const phaseArray = Array.from(phases.values());\n for (let i = 0; i < phaseArray.length; i++) {\n const phase = phaseArray[i];\n if (!phase) continue;\n phase.nextPhases = i < phaseArray.length - 1 ? [phaseArray[i + 1]?.id ?? ''] : [];\n }\n\n const graph: PhaseGraph = {\n id: graphId,\n title: this.opts.title,\n description: this.opts.description ?? '',\n phases,\n rootPhaseIds: phaseIds.length > 0 ? [phaseIds[0] ?? ''] : [],\n activePhaseIds: [],\n completedPhaseIds: [],\n failedPhaseIds: [],\n autonomous: this.opts.autonomous ?? true,\n stopOnComplete: true,\n multiBoard: this.opts.multiBoard,\n verifyTasks: this.opts.verifyTasks,\n chimeraReview: this.opts.chimeraReview,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n\n return graph;\n }\n\n /**\n * Create phases from an existing TaskGraph.\n * Groups tasks into phases using topological sort so dependencies\n * stay in the same phase wherever possible.\n */\n static fromTaskGraph(\n taskGraph: TaskGraph,\n options: Omit<PhaseGraphBuilderOptions, 'phases'> & {\n /** Number of tasks per phase. Defaults to 5. */\n tasksPerPhase?: number | undefined;\n },\n ): Promise<PhaseGraph> {\n const tasksPerPhase = options.tasksPerPhase ?? 5;\n const nodes = Array.from(taskGraph.nodes.values());\n\n // Build adjacency: for each node, which nodes depend on it.\n const dependents = new Map<string, string[]>();\n for (const edge of taskGraph.edges) {\n const list = dependents.get(edge.from) ?? [];\n list.push(edge.to);\n dependents.set(edge.from, list);\n }\n\n // Topological sort (Kahn's algorithm) \u2014 tasks that are depended-on come first.\n const inDegree = new Map<string, number>();\n for (const node of nodes) inDegree.set(node.id, 0);\n for (const edge of taskGraph.edges) {\n inDegree.set(edge.to, (inDegree.get(edge.to) ?? 0) + 1);\n }\n\n const queue: string[] = [];\n for (const [id, degree] of inDegree) {\n if (degree === 0) queue.push(id);\n }\n\n const prioOrder: Record<TaskPriority, number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n };\n\n const topoSorted: string[] = [];\n while (queue.length > 0) {\n // Prioritize by critical \u2192 high \u2192 medium \u2192 low within the same level.\n queue.sort((a, b) => {\n const na = taskGraph.nodes.get(a);\n const nb = taskGraph.nodes.get(b);\n const naPrio = na ? prioOrder[na.priority] : 4;\n const nbPrio = nb ? prioOrder[nb.priority] : 4;\n return naPrio - nbPrio;\n });\n const id = queue.shift()!;\n topoSorted.push(id);\n for (const depId of dependents.get(id) ?? []) {\n const deg = (inDegree.get(depId) ?? 1) - 1;\n inDegree.set(depId, deg);\n if (deg === 0) queue.push(depId);\n }\n }\n\n // Group topologically-sorted nodes into phases, keeping dependent\n // tasks close together.\n const groups: string[][] = [];\n let currentGroup: string[] = [];\n const assigned = new Set<string>();\n\n for (const id of topoSorted) {\n if (assigned.has(id)) continue;\n assigned.add(id);\n currentGroup.push(id);\n\n // Collect any direct dependents of this task into the same phase\n // as long as we haven't exceeded the size limit.\n const deps = dependents.get(id) ?? [];\n for (const depId of deps) {\n if (!assigned.has(depId) && currentGroup.length < tasksPerPhase) {\n assigned.add(depId);\n currentGroup.push(depId);\n }\n }\n\n if (currentGroup.length >= tasksPerPhase) {\n groups.push(currentGroup);\n currentGroup = [];\n }\n }\n if (currentGroup.length > 0) groups.push(currentGroup);\n\n const phaseTemplates: PhaseTemplate[] = groups.map((groupIds, idx) => {\n const group = groupIds\n .map((id) => taskGraph.nodes.get(id))\n .filter((n): n is NonNullable<typeof n> => n != null);\n const hasCritical = group.some((t) => t.priority === 'critical');\n const totalHours = group.reduce((sum, t) => sum + (t.estimateHours ?? 2), 0);\n\n return {\n name: `Phase ${idx + 1}: ${group[0]?.title.slice(0, 30) ?? 'Tasks'}`,\n description: group.map((t) => t.title).join(', '),\n priority: hasCritical ? 'critical' : 'high',\n estimateHours: totalHours,\n parallelizable: false,\n taskTemplates: group.map((t) => ({\n title: t.title,\n description: t.description,\n type: t.type,\n priority: t.priority,\n estimateHours: t.estimateHours ?? 2,\n tags: t.tags ?? [],\n })),\n };\n });\n\n const builder = new PhaseGraphBuilder({\n ...options,\n phases: phaseTemplates,\n });\n\n return builder.build();\n }\n}\n", "import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Logger, LogLevel } from '../types/logger.js';\nimport { color } from '../utils/color.js';\nimport { writeErr } from '../utils/term.js';\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4,\n};\n\nconst COLORS: Record<LogLevel, (s: string) => string> = {\n error: color.red,\n warn: color.yellow,\n info: color.cyan,\n debug: color.gray,\n trace: color.dim,\n};\n\nconst LOG_LEVELS = new Set<LogLevel>(['error', 'warn', 'info', 'debug', 'trace']);\nconst LOG_FORMATS = new Set<string>(['pretty', 'json']);\n\nexport type LogFormat = 'pretty' | 'json';\n\nexport interface DefaultLoggerOptions {\n level?: LogLevel | undefined;\n file?: string | undefined;\n /**\n * @deprecated Use `format: 'json'` instead. Kept for backward compat\n * with existing callers but has no effect on output \u2014 the `format`\n * option controls whether stderr receives pretty-printed or JSON lines.\n */\n pretty?: boolean | undefined;\n /** Output format for stderr. `pretty` (colored, human-readable) or `json` (machine-parseable). Defaults to `WRONGSTACK_LOG_FORMAT` env var, falling back to `pretty`. */\n format?: LogFormat | undefined;\n bindings?: Record<string, unknown>;\n /**\n * When false, suppress stderr output entirely \u2014 only write to the log\n * file (if configured). Use this in TUI mode so plugin/library log\n * messages don't interleave with Ink's terminal rendering.\n * Default: true (stderr output is enabled).\n */\n stderr?: boolean | undefined;\n /**\n * Rotate the log file once it exceeds this many bytes: the current file is\n * renamed to `<file>.1` (replacing any previous one) and a fresh file\n * starts. Bounds total disk to ~2\u00D7 this value. Default 10 MB.\n */\n maxFileBytes?: number | undefined;\n}\n\nexport class DefaultLogger implements Logger {\n /** How many file writes between rotation size checks (statSync is not free). */\n private static readonly ROTATE_CHECK_EVERY = 100;\n private static readonly MAX_PENDING_FILE_WRITES = 2_000;\n private static readonly MAX_PENDING_FILE_BYTES = 8 * 1024 * 1024;\n\n level: LogLevel;\n private file?: string | undefined;\n private bindings: Record<string, unknown>;\n private format: LogFormat;\n private stderr: boolean;\n private maxFileBytes: number;\n private writesSinceRotateCheck = 0;\n /**\n * Serialized async tail for file writes. Every appendFile (and any\n * chained rotation) is awaited through this promise so file I/O\n * never overlaps itself \u2014 preserving the per-line ordering the\n * sync version had, but without blocking the caller thread. Any\n * rejection is swallowed (`catch(() => {})`) because logging must\n * never crash the host.\n *\n * Children share the parent's tail: `child.tail === parent.tail`\n * for the lifetime of the chain. Read/write access goes through\n * `_tail` so that, when a child has been wired to a parent, both\n * `enqueueRotate` and `log` always observe the parent's current tail\n * rather than a stale snapshot taken at `child()` time.\n */\n private tail: Promise<void> = Promise.resolve();\n private parent: DefaultLogger | null = null;\n private pendingFileWrites = 0;\n private pendingFileBytes = 0;\n\n private get root(): DefaultLogger {\n return this.parent ? this.parent.root : this;\n }\n\n /**\n * Resolve the current tail. For the root logger this is the field;\n * for a child logger we always read through the parent so that a\n * child's appends land on the parent's most recent tail, and a\n * parent's `flush()` waits for everything the child chained.\n */\n private get _tail(): Promise<void> {\n return this.parent ? this.parent._tail : this.tail;\n }\n private set _tail(next: Promise<void>) {\n if (this.parent) this.parent.tail = next;\n else this.tail = next;\n }\n\n constructor(opts: DefaultLoggerOptions = {}) {\n this.level = opts.level ?? parseLogLevel(process.env.WRONGSTACK_LOG_LEVEL);\n this.file = opts.file;\n this.bindings = opts.bindings ?? {};\n this.format = opts.format ?? parseLogFormat(process.env.WRONGSTACK_LOG_FORMAT);\n this.stderr = opts.stderr !== false; // default true\n this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024;\n if (this.file) {\n // Chain mkdir onto the file-write tail so the first append can't\n // race a still-pending mkdir (especially under tests that call\n // `flush()` immediately after `info()`). mkdir is best-effort;\n // a rejection only blocks subsequent appends in the chain that\n // observed it via the rejected promise, which would skip the\n // append \u2014 that is acceptable because ENOENT/EEXIST/EPERM all\n // either are no-ops or indicate an unrecoverable environment.\n const dir = path.dirname(this.file);\n this._tail = this._tail\n .then(async () => {\n await fsp.mkdir(dir, { recursive: true });\n })\n .catch(() => undefined);\n }\n }\n\n error(msg: string, ctx?: unknown): void {\n this.log('error', msg, ctx);\n }\n warn(msg: string, ctx?: unknown): void {\n this.log('warn', msg, ctx);\n }\n info(msg: string, ctx?: unknown): void {\n this.log('info', msg, ctx);\n }\n debug(msg: string, ctx?: unknown): void {\n this.log('debug', msg, ctx);\n }\n trace(msg: string, ctx?: unknown): void {\n this.log('trace', msg, ctx);\n }\n\n child(bindings: Record<string, unknown>): Logger {\n // Construct without invoking the class constructor (which would mkdir\n // again and create a separate file-write tail). The parent and child\n // must share the same tail so `parent.flush()` waits for child\n // appends too \u2014 otherwise a test that flushes the parent after\n // `child.info(...)` would race the child append and observe an empty\n // file. Sharing the tail preserves the order the parent originally\n // had via its serialised file-write queue.\n const child = Object.create(DefaultLogger.prototype) as DefaultLogger;\n child.level = this.level;\n child.file = this.file;\n child.bindings = { ...this.bindings, ...bindings };\n child.format = this.format;\n child.stderr = this.stderr;\n child.maxFileBytes = this.maxFileBytes;\n child.parent = this;\n child.writesSinceRotateCheck = this.writesSinceRotateCheck;\n return child;\n }\n\n /**\n * Wait until all queued file writes (and any pending rotation) have\n * completed. `log()` is fire-and-forget by design \u2014 the caller never\n * blocks on disk \u2014 so tests, shutdown handlers, and processes that\n * need a deterministic \"everything is on disk now\" guarantee should\n * `await logger.flush()` before reading the file or exiting.\n */\n flush(): Promise<void> {\n return this._tail;\n }\n\n /**\n * Size-based rotation: when the file outgrows `maxFileBytes`, rename it to\n * `<file>.1` (dropping the previous `.1`) so the live file restarts empty.\n * Checked on the first write and every ROTATE_CHECK_EVERY writes after.\n * Best-effort: a rename can fail on Windows while another process holds\n * the file \u2014 the next check retries. Multiple processes appending to the\n * same log all run this check; whoever crosses the threshold first wins.\n *\n * Async: the rotation runs on the file-write tail (so its writes don't\n * interleave with the next append), and the caller never blocks on a\n * statSync / renameSync syscall on the hot log path.\n */\n private enqueueRotate(file: string): void {\n if (this.writesSinceRotateCheck++ % DefaultLogger.ROTATE_CHECK_EVERY !== 0) return;\n this._tail = this._tail\n .then(async () => {\n let st;\n try {\n st = await fsp.stat(file);\n } catch {\n return; // file missing \u2014 nothing to rotate\n }\n if (st.size < this.maxFileBytes) return;\n try {\n await fsp.rm(`${file}.1`, { force: true });\n await fsp.rename(file, `${file}.1`);\n } catch {\n // file locked, or raced by another process \u2014 ignore\n }\n })\n .catch(() => undefined);\n }\n\n private log(level: LogLevel, msg: string, ctx?: unknown): void {\n const r = LEVEL_RANK[level];\n const allowed = LEVEL_RANK[this.level];\n if (r > allowed) return;\n const ts = new Date().toISOString();\n const entry: Record<string, unknown> = { ts, level, msg, ...this.bindings };\n if (ctx !== undefined) {\n entry.ctx = ctx instanceof Error ? { message: ctx.message, stack: ctx.stack } : ctx;\n }\n // Disk: JSON line. Serialized through `_tail` so concurrent log\n // calls preserve per-line order without blocking the caller on\n // sync file I/O. Children route through their parent's tail, so\n // a parent's `flush()` waits for every chained child append.\n if (this.file) {\n const line = `${JSON.stringify(entry)}\\n`;\n const bytes = Buffer.byteLength(line, 'utf8');\n const root = this.root;\n if (\n root.pendingFileWrites < DefaultLogger.MAX_PENDING_FILE_WRITES &&\n bytes <= DefaultLogger.MAX_PENDING_FILE_BYTES &&\n root.pendingFileBytes + bytes <= DefaultLogger.MAX_PENDING_FILE_BYTES\n ) {\n root.pendingFileWrites += 1;\n root.pendingFileBytes += bytes;\n this.enqueueRotate(this.file);\n this._tail = this._tail\n .then(() => fsp.appendFile(this.file!, line))\n .catch(() => undefined)\n .finally(() => {\n root.pendingFileWrites = Math.max(0, root.pendingFileWrites - 1);\n root.pendingFileBytes = Math.max(0, root.pendingFileBytes - bytes);\n });\n }\n }\n // Stderr: pretty or json. Suppressed when this.stderr is false (TUI mode)\n // so plugin/library log messages don't interleave with Ink's rendering.\n if (!this.stderr) return;\n if (this.format === 'json') {\n writeErr(`${JSON.stringify(entry)}\\n`);\n } else {\n const head = `${color.dim(ts)} ${COLORS[level](level.toUpperCase().padEnd(5))} ${msg}`;\n if (ctx !== undefined) {\n writeErr(`${head} ${formatCtx(ctx)}\\n`);\n } else {\n writeErr(`${head}\\n`);\n }\n }\n }\n}\n\nfunction parseLogLevel(raw: string | undefined): LogLevel {\n return raw && LOG_LEVELS.has(raw as LogLevel) ? (raw as LogLevel) : 'info';\n}\n\nfunction parseLogFormat(raw: string | undefined): LogFormat {\n return raw && LOG_FORMATS.has(raw) ? (raw as LogFormat) : 'pretty';\n}\n\nfunction formatCtx(ctx: unknown): string {\n if (ctx instanceof Error) return color.dim(ctx.message);\n if (typeof ctx === 'string') return color.dim(ctx);\n try {\n return color.dim(JSON.stringify(ctx));\n } catch {\n return color.dim(String(ctx));\n }\n}\n\n/**\n * A logger that silently discards all messages. Used during boot before\n * the real logger is configured, and in test contexts where logging\n * would be noise.\n */\nexport const noOpLogger: Logger = {\n // 'error' is the quietest level the Logger contract offers; the methods\n // discard everything regardless, this only matters to level checks.\n level: 'error',\n error: () => {},\n warn: () => {},\n info: () => {},\n debug: () => {},\n trace: () => {},\n child: () => noOpLogger,\n};\n", "/**\n * TTY detection helpers \u2014 the single source of truth for \"is this process\n * running against a real terminal?\". Replaces ad-hoc `process.stdin.isTTY`\n * / `process.stdout.isTTY` checks scattered across the codebase so that:\n *\n * 1. test code can mock a single module instead of stubbing `isTTY` on\n * every ReadStream/WriteStream the test happens to touch;\n * 2. a future TTY-detection source (an env var override, a Windows\n * ConPTY workaround, \u2026) lands in one place;\n * 3. `isInteractive()` encodes the rule the project already used inline\n * (\"both streams are TTYs AND we're not running under CI\") in one\n * testable helper instead of the same 3-condition check in two\n * different files.\n *\n * Scope: detection only. Raw-mode control (`setRawMode`), resize\n * subscriptions, and write-injection belong to a future, larger TTY\n * abstraction; this module is the smallest pull that gives us a\n * testable seam and dedups 20+ call sites.\n */\n\nconst hasStdout = (): boolean => typeof process !== 'undefined' && !!process.stdout;\nconst hasStdin = (): boolean => typeof process !== 'undefined' && !!process.stdin;\n\n/** True when `process.stdout` is attached to a terminal (not a pipe/file). */\nexport function isStdoutTTY(): boolean {\n return hasStdout() && Boolean(process.stdout.isTTY);\n}\n\n/** True when `process.stdin` is attached to a terminal (not a pipe/file). */\nexport function isStdinTTY(): boolean {\n return hasStdin() && Boolean(process.stdin.isTTY);\n}\n\n/**\n * True when the current process is an interactive session: both stdin and\n * stdout are TTYs. Callers that also need a \"not a single-shot invocation\"\n * or \"not under CI\" check should layer that on top \u2014 keeping this helper\n * minimal preserves the original inline checks it replaces.\n */\nexport function isInteractive(): boolean {\n return isStdinTTY() && isStdoutTTY();\n}\n\n/** Current terminal size in characters, with a 24\u00D780 fallback for non-TTYs. */\nexport function getTermSize(): { rows: number; cols: number } {\n if (!hasStdout()) return { rows: 24, cols: 80 };\n return {\n rows: process.stdout.rows ?? 24,\n cols: process.stdout.columns ?? 80,\n };\n}\n\n/**\n * Subscribe to terminal resize events. `cb` is called with the new size each\n * time the underlying stream emits `resize`. Returns a cleanup function the\n * caller MUST call on dispose to remove the listener \u2014 leaving a stale\n * `resize` listener on a disposed component leaks the closure (and the\n * component itself, transitively) until the process exits.\n *\n * The stream argument defaults to `process.stdout`. Pass an explicit\n * `NodeJS.WriteStream` when the caller already owns one (e.g. a status line\n * that targets an injected `out` for testability). For non-TTY streams no\n * listener is registered and the returned cleanup is a no-op.\n */\nexport function onResize(\n cb: (size: { rows: number; cols: number }) => void,\n stream: NodeJS.WriteStream = process.stdout,\n): () => void {\n if (!stream || typeof stream.on !== 'function') return () => {};\n const handler = (): void => {\n cb({\n rows: stream.rows ?? 24,\n cols: stream.columns ?? 80,\n });\n };\n stream.on('resize', handler);\n return () => {\n stream.off('resize', handler);\n };\n}\n\n/**\n * Toggle raw mode on a TTY stdin stream. Returns `true` when the toggle was\n * applied, `false` when the stream is null, not a TTY, or doesn't expose\n * `setRawMode` (pipes, file descriptors, Windows ConPTY edge cases). Callers\n * that need to restore the previous mode should snapshot `input.isRaw`\n * BEFORE the call and pass the value to a second call to flip back.\n *\n * Use this helper to drop the now-redundant\n * `if (input.isTTY) input.setRawMode(...)` ceremony at every call site.\n */\nexport function setRawMode(input: NodeJS.ReadStream, mode: boolean): boolean {\n if (input?.isTTY !== true) return false;\n if (typeof input.setRawMode !== 'function') return false;\n input.setRawMode(mode);\n return true;\n}\n\n/**\n * Bracket installed by the interactive input reader while a `readline`\n * prompt is on screen. Out-of-band terminal writes \u2014 logger WARN/INFO\n * lines, async activity from the Telegram bridge, etc. \u2014 go to the same\n * physical terminal as the half-typed prompt but readline has no idea they\n * happened, so it never repaints. The result is the classic corruption the\n * user sees: every async line strands the in-progress draft as a fresh\n * scrollback row (sometimes with its cursor underline).\n *\n * The guard closes that gap. `suspend()` wipes the draft row so the message\n * prints clean; `resume()` repaints the prompt + draft (cursor preserved).\n * When no prompt is active the guard is `null` and writes pass straight\n * through \u2014 so agent-turn output (spinner, renderer) is untouched.\n */\nexport interface OutputLineGuard {\n /** Clear the current input row right before an out-of-band write. */\n suspend(): void;\n /** Repaint the prompt + in-progress draft right after the write. */\n resume(): void;\n}\n\nlet activeOutputGuard: OutputLineGuard | null = null;\n\n/**\n * Register (or clear, with `null`) the guard that brackets out-of-band\n * writes. Installed by {@link writeOut}/{@link writeErr} consumers \u2014 in\n * practice the CLI's readline input reader \u2014 only while a prompt is live.\n * Idempotent; the most recent caller wins.\n */\nexport function setOutputLineGuard(guard: OutputLineGuard | null): void {\n activeOutputGuard = guard;\n}\n\n/**\n * Stream-agnostic write primitive. Returns `false` when the stream is\n * missing or doesn't expose `write` so callers can degrade silently under\n * hostile host environments (closed pipe, mock injects `null`, test\n * replaces the stream with a stub).\n *\n * When an {@link OutputLineGuard} is installed (a readline prompt is on\n * screen) the write is bracketed by `suspend()`/`resume()` so the user's\n * half-typed input survives the interruption instead of being stranded in\n * scrollback. The guard's own redraw uses raw stream writes \u2014 never\n * `writeOut`/`writeErr` \u2014 so there is no re-entrancy here.\n *\n * **Not exported in the public API.** Exposed only inside `term.ts` for\n * `writeOut` / `writeErr` to share a single implementation. If a caller\n * needs to write to an arbitrary stream, they should call `writeOut` (or\n * `writeErr`) with an explicit `stream` argument \u2014 the named functions\n * are the public surface so the \"this is the standard error stream\"\n * intent stays visible at every call site.\n */\nfunction writeTo(\n s: string,\n stream: NodeJS.WriteStream | undefined,\n): boolean {\n if (!stream || typeof stream.write !== 'function') return false;\n const guard = activeOutputGuard;\n if (!guard) {\n stream.write(s);\n return true;\n }\n // A prompt is live \u2014 wipe the draft row, emit the message, repaint.\n guard.suspend();\n stream.write(s);\n guard.resume();\n return true;\n}\n\n/**\n * Write `s` to `stream` (defaults to `process.stdout`). Returns `false`\n * when the stream is missing or doesn't expose `write` so callers can\n * degrade silently under hostile host environments (closed pipe, mock\n * injects `null`, test replaces the stream with a stub).\n *\n * Why a helper:\n * 1. **Single seam for output capture in tests** \u2014 stub `writeOut` once\n * and assert on what the rest of the codebase intended to print,\n * without spying on `process.stdout.write` (which is brittle and\n * leaks across parallel test files).\n * 2. **Stream swap without grep** \u2014 routing the CLI's output to a\n * logger or `out.log` becomes a one-line change at process boot.\n * 3. **Defensive default** \u2014 closes the \"what if `process.stdout` is\n * `null`\" gap that currently exists at ~50 call sites that just\n * call `process.stdout.write(s)` and crash on certain Windows\n * redirect invocations.\n *\n * Call-site migration is staged: this commit introduces the helper, a\n * follow-up commit replaces the 50+ `process.stdout.write(...)` sites\n * with `writeOut(...)`. Until that migration lands, both forms coexist\n * and `writeOut` is the preferred form for new code.\n */\nexport function writeOut(\n s: string,\n stream: NodeJS.WriteStream = process.stdout,\n): boolean {\n return writeTo(s, stream);\n}\n\n/**\n * Symmetric partner of `writeOut` for the standard error stream. Same shape,\n * same defensive contract, same single-seam-for-tests story \u2014 just defaults to\n * `process.stderr` instead of `process.stdout`.\n *\n * Use this in code paths that emit error/diagnostic/warning text. Keeping\n * these two helpers split (rather than a single `writeTo(s, stream)`) means\n * the call site reads as a clear intent signal: \"I am writing an error\" vs.\n * \"I am writing a result\" \u2014 which matters for callers that decide between\n * stdout/stderr routing (e.g. `--quiet` flags, log-level filtering,\n * structured-log rewriters that fork on stream).\n *\n * Stderr writes from the core logger (see `infrastructure/logger.ts`) and from\n * the TUI guard (see `tui/run-tui.ts`) used to call `process.stderr.write`\n * directly. Routing them through this helper lets tests stub the stream at\n * one boundary and lets future logging middleware (e.g. a JSON-line rewriter)\n * swap the destination for the entire process in one place.\n */\nexport function writeErr(\n s: string,\n stream: NodeJS.WriteStream = process.stderr,\n): boolean {\n return writeTo(s, stream);\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// TerminalCapability \u2014 startup capability profile\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Color depth the terminal can render.\n *\n * 0 = no color (dumb, redirected, `TERM=dumb`)\n * 1 = 16 colors (basic ANSI)\n * 2 = 256 colors (ANSI 256 + bright variants)\n * 3 = 16.7M / 24-bit truecolor\n */\nexport type ColorDepth = 0 | 1 | 2 | 3;\n\n/**\n * Mouse tracking protocol the terminal speaks.\n *\n * 'none' \u2014 no mouse reporting\n * 'x10' \u2014 basic button press/release, capped at 223 columns\n * 'urxvt'\u2014 URXVT extension, supports >223 cols\n * 'sgr' \u2014 SGR extended mode, modern standard, no column cap\n */\nexport type MouseProtocol = 'none' | 'x10' | 'urxvt' | 'sgr';\n\n/**\n * A snapshot of the terminal's capabilities and identity, computed once at\n * startup. Call {@link detectTerminal} once and pass the result through your\n * app \u2014 never re-detect mid-session.\n *\n * Query once \u2192 adapt once. Re-querying on every render is wrong because\n * `$TERM` is static for the process lifetime and stdout.isTTY can only go\n * from true\u2192false (never the reverse), so a mid-session change means the\n * process was started in a terminal and then something went wrong.\n */\nexport interface TerminalCapability {\n /** True when both stdin and stdout are attached to a terminal. */\n isRealTTY: boolean;\n /**\n * Whether the terminal speaks color.\n *\n * Uses the industry-standard precedence:\n * `FORCE_COLOR=0` \u2192 0 (disabled)\n * `FORCE_COLOR` \u2192 3 (force truecolor)\n * `NO_COLOR=\u2026` \u2192 0 (opted out)\n * `COLORTERM=truecolor|24bit` \u2192 3\n * `TERM=\u2026truecolor|24bit` \u2192 3 (some emulators advertise it)\n * `TERM=\u2026256color` \u2192 2\n * fallback \u2192 1\n *\n * Note: `TERM=dumb` always produces 0 even if `COLORTERM=truecolor` is set \u2014\n * `dumb` terminals are non-interactive by definition.\n */\n colorDepth: ColorDepth;\n /**\n * Whether `stdout` can be written to. Determined once at startup from\n * `stdout?.isTTY ?? false`. Even when `isRealTTY` is true, `stdout` may be\n * writable=false (e.g. the terminal was closed mid-session).\n */\n stdoutWritable: boolean;\n /**\n * Best mouse protocol the terminal speaks. Progressive enhancement:\n * attempt SGR first, fall back to URXVT, then X10, then 'none'.\n *\n * The caller (typically the App component) decides whether to enable\n * tracking at all \u2014 this only reports what the terminal CAN understand.\n */\n mouseProtocol: MouseProtocol;\n /**\n * Whether the terminal title can be set via OSC 0 / OSC 2.\n * True when stdout is a TTY and `$TERM` is not `dumb`.\n */\n canSetTitle: boolean;\n /**\n * Whether the terminal understands the tmux DCS passthrough prefix.\n * Detected by seeing `$TERM=tmux*`. When true, escape sequences should be\n * wrapped: `\\x1bPtmux;\\x1b${seq}\\x1b\\\\`.\n */\n isTmux: boolean;\n /**\n * Whether the terminal is on Windows using the legacy conhost backend\n * (cmd.exe, PowerShell non-ConPTY) rather than ConPTY (Windows Terminal,\n * VS Code Integrated Terminal). Used to apply Windows-specific raw-mode\n * handoff logic.\n *\n * Detected by: platform === 'win32' AND `!process.stdout.getColorDepth?.()`\n * (ConPTY exposes color depth; conhost does not). Also false on non-Windows.\n */\n isWindowsConhost: boolean;\n}\n\n/**\n * Parse `process.env.TERM` into a color-depth guess.\n *\n * We intentionally do NOT use the `supports-color` npm package here because\n * (a) it adds a dependency, (b) it resolves at module-import time, and (c) we\n * need to factor in `FORCE_COLOR` / `NO_COLOR` which may be set after import.\n * This pure function is trivial to test and predictable regardless of import\n * order.\n */\nfunction parseColorDepth(env: { FORCE_COLOR?: string; NO_COLOR?: string; COLORTERM?: string; TERM?: string; }): ColorDepth {\n // `FORCE_COLOR=0` is an explicit opt-out, even when `COLORTERM=truecolor`.\n if (env.FORCE_COLOR === '0') return 0;\n // `FORCE_COLOR` with no value or any truthy value forces truecolor.\n if (env.FORCE_COLOR !== undefined) return 3;\n // Explicit user opt-out.\n if (typeof env.NO_COLOR === 'string' && env.NO_COLOR !== '') return 0;\n // Explicit terminal advertisement.\n const colorterm = (env.COLORTERM ?? '').toLowerCase();\n if (colorterm === 'truecolor' || colorterm === '24bit') return 3;\n // TERM strings that advertise rich color.\n const term = (env.TERM ?? '').toLowerCase();\n if (term.includes('truecolor') || term.includes('24bit')) return 3;\n if (term.includes('256color')) return 2;\n // TERM=dumb = no interactive capability at all.\n if (term === 'dumb') return 0;\n // Default to 16-color \u2014 the safest floor. Modern terminals all override this.\n return 1;\n}\n\n/**\n * Detect the best mouse protocol the terminal speaks.\n *\n * Uses the `$TERM` string as a proxy since Node.js has no runtime query for\n * mouse capability (DECSET 1000/1002/1003 responses are not standardized for\n * programmatic use). The approximation is:\n * - `tmux` + `screen` = SGR (they proxy it)\n * - `xterm*`, `rxvt*`, `konsole`, `gnome*` = SGR (post-2013)\n * - `linux`, `vt100`, `dumb` = none\n * - Everything else = URXVT / X10 (try SGR, fall back gracefully in mouse.ts)\n *\n * This is advisory only. The App component gates mouse tracking behind an\n * explicit user/setting opt-in; false positives just mean the tracking enable\n * sequence is ignored harmlessly.\n */\nfunction parseMouseProtocol(term: string): MouseProtocol {\n const t = term.toLowerCase();\n // Terminals that reliably support SGR (1006) mode.\n if (\n t.startsWith('xterm') ||\n t.startsWith('tmux') ||\n t.startsWith('screen') ||\n t.includes('rxvt-unicode') ||\n t.includes('urxvt') ||\n t.includes('konsole') ||\n t.includes('gnome') ||\n t.includes('foot') ||\n t.includes('alacritty') ||\n t.includes('wezterm') ||\n t.includes('kitty') ||\n t.includes('vscode') ||\n t.includes('Apple_Terminal')\n ) {\n return 'sgr';\n }\n // Known mouse-capable but older terminals.\n if (t.startsWith('rxvt') || t.startsWith('linux') || t.includes('Eterm')) {\n return 'urxvt';\n }\n // vt100 / dumb \u2014 no mouse.\n if (t === 'vt100' || t === 'dumb') return 'none';\n // Default: assume SGR is safe to try; mouse.ts falls back silently.\n return 'sgr';\n}\n\n/**\n * Detect the terminal's capabilities and identity at startup.\n *\n * Call once, early in process boot, before any event-loop async has had a\n * chance to corrupt the read of `process.stdout.isTTY`. Store the result and\n * pass it through the app \u2014 do NOT call this on every render.\n *\n * All `env` lookups default gracefully to safe values when the env var is\n * absent or empty, so the return value is deterministic regardless of what\n * the host's environment looks like.\n */\nexport function detectTerminal(\n opts: {\n stdin?: NodeJS.ReadStream | null;\n stdout?: NodeJS.WriteStream | null;\n env?: typeof process.env;\n } = {},\n): TerminalCapability {\n const stdin = opts.stdin ?? process.stdin;\n const stdout = opts.stdout ?? process.stdout;\n const env = opts.env ?? process.env;\n\n const isRealTTY = (stdin?.isTTY ?? false) && (stdout?.isTTY ?? false);\n const stdoutWritable = isRealTTY && typeof stdout?.write === 'function';\n const term = env.TERM ?? '';\n const isTmux = term.toLowerCase().startsWith('tmux');\n const isWindowsConhost = isRealTTY\n && process.platform === 'win32'\n && typeof (stdout as NodeJS.WriteStream & { getColorDepth?: unknown }).getColorDepth !== 'function';\n\n return {\n isRealTTY,\n colorDepth: isRealTTY ? parseColorDepth(env) : 0,\n stdoutWritable,\n mouseProtocol: parseMouseProtocol(term),\n canSetTitle: isRealTTY && term !== 'dumb',\n isTmux,\n isWindowsConhost,\n };\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// TerminalLifecycle \u2014 raw-mode lifecycle manager\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Lifecycle owner for the TTY stdin raw-mode state machine.\n *\n * Raw mode is the most dangerous primitive in TUI code. Getting it wrong leaves\n * the user's terminal in a broken state (line-buffered, no echo) that requires\n * closing and reopening the terminal to recover. This class enforces a strict\n * acquire \u2192 hold \u2192 release lifecycle:\n *\n * - `acquire()` may be called only once (idempotent \u2014 subsequent calls no-op).\n * - `release()` restores the previous mode exactly once.\n * - `release()` is called automatically on process `exit` and `beforeExit`.\n * - Any signal handler (SIGINT, SIGTERM, SIGHUP) that calls `release()` clears\n * its own registration so double-signals don't double-restore.\n *\n * Use this instead of calling `setRawMode()` directly at every call site. The\n * single instance lives at module scope in `run-tui.ts`; components that need\n * to signal \"TUI is shutting down\" call `terminalLifecycle.requestExit()` rather\n * than calling `release()` directly.\n */\nexport class TerminalLifecycle {\n private _active = false;\n\n /**\n * The stdin stream we took raw mode on. Set by `acquire()`; undefined before\n * first call. Used by `release()` and by the ConPTY race-closer in\n * `acquire()`.\n */\n private _stdin: NodeJS.ReadStream | undefined;\n\n /**\n * The `isRaw` snapshot captured before the first `acquire()` call, so\n * `release()` restores to the pre-TUI state rather than blindly disabling\n * raw mode. Null when `acquire()` has never been called.\n */\n private _wasRaw: boolean | null = null;\n\n /**\n * Whether stdin was paused before the TUI took ownership. Readline closes\n * its interface by pausing the shared process stream, so raw mode alone is\n * not enough to make Ink receive bytes during the boot-prompt -> TUI handoff.\n */\n private _wasPaused: boolean | null = null;\n\n /**\n * Request the process to exit. Set the flag, trigger any registered\n * `onRequestExit` callback (typically Ink's `unmount()`), and arm a\n * deadline timer. When the timer fires the process is hard-exited.\n *\n * Safe to call multiple times: subsequent calls no-op after the first.\n */\n requestExit: (exitCode?: number) => void;\n\n /**\n * Callback invoked when `requestExit` is called. Registered by the Ink\n * mount point so unmount() runs before the deadline timer fires.\n */\n onRequestExit: (() => void | Promise<void>) | null = null;\n\n constructor() {\n // Build the requestExit closure here so subclasses / tests can override\n // `requestExit` before calling `acquire()`.\n let exitCode = 0;\n let requested = false;\n this.requestExit = (code = 0) => {\n exitCode = code;\n if (requested) return;\n requested = true;\n // Let the Ink unmount handler run (if registered).\n try {\n this.onRequestExit?.();\n } catch {\n // unmount handler threw \u2014 proceed to hard exit.\n }\n // Hard-exit deadline. `unref()` so the timer doesn't keep the event\n // loop alive if everything else has settled.\n setTimeout(() => process.exit(exitCode), 5_000).unref();\n };\n }\n\n /** True while raw mode is held. */\n get active(): boolean {\n return this._active;\n }\n\n /**\n * Acquire raw mode on `stdin`. Idempotent \u2014 calling twice is safe; only the\n * first call has any effect.\n *\n * On Windows ConPTY, calls `setRawMode` twice: once immediately, then again\n * after the next event-loop tick. This closes the ConPTY race where\n * `readline`'s cleanup (registered before this class is constructed) can\n * restore the original cooked mode after we set raw mode but before Ink's\n * render loop takes over the stdin fd. The double-call ensures the last\n * writer wins.\n *\n * @param stdin - The stdin stream (defaults to `process.stdin`).\n * @returns `true` if raw mode was acquired; `false` if stdin is not a TTY\n * or already shut down.\n */\n acquire(stdin: NodeJS.ReadStream = process.stdin): boolean {\n if (this._active) return false;\n\n // Guard: must be a real TTY, must have setRawMode.\n if (stdin?.isTTY !== true) return false;\n if (typeof stdin.setRawMode !== 'function') return false;\n\n // Snapshot the pre-TUI raw state so release() restores correctly.\n this._wasRaw = stdin.isRaw ?? false;\n this._wasPaused = stdin.isPaused();\n this._stdin = stdin;\n\n stdin.setRawMode(true);\n // A preceding readline prompt normally leaves process.stdin paused.\n // Explicitly start the stream before Ink installs its input listener;\n // otherwise the UI can render perfectly while every key appears dead.\n stdin.resume();\n this._active = true;\n\n // Windows ConPTY double-acquire: schedule a second setRawMode on the next\n // tick so we win the race against readline's \"restore original mode\".\n // Safe on non-Windows (no-op: process.platform !== 'win32').\n if (process.platform === 'win32') {\n setImmediate(() => {\n if (this._active && this._stdin?.isTTY) {\n this._stdin.setRawMode?.(true);\n }\n });\n }\n\n return true;\n }\n\n /**\n * Release raw mode and restore the terminal to the state it was in before\n * `acquire()` was called. Idempotent \u2014 subsequent calls are no-ops.\n *\n * Call this on: SIGINT, SIGTERM, SIGHUP, SIGBREAK, and `process.exit`.\n *\n * \u26A0 **Windows caveat**: `setRawMode(false)` on ConPTY restores the original\n * console mode captured when the process started \u2014 not the mode captured by\n * `acquire()`. On ConPTY, the original mode was already raw (ConPTY starts\n * raw), so this call is typically a no-op on Windows Terminal. On conhost.exe\n * it may restore cooked mode, which is correct for that backend.\n */\n release(): void {\n if (!this._active) return;\n this._active = false;\n\n const stdin = this._stdin;\n if (stdin?.isTTY === true) {\n // Restore to pre-TUI state rather than blindly disabling raw mode.\n stdin.setRawMode?.(this._wasRaw ?? false);\n if (this._wasPaused) stdin.pause();\n }\n this._stdin = undefined;\n this._wasRaw = null;\n this._wasPaused = null;\n }\n\n /**\n * Synchronously reset all terminal state written by the TUI layer:\n * raw mode, SGR attributes, cursor visibility, and mouse tracking.\n *\n * Intended for the final `process.on('exit')` handler where async is\n * impossible. Uses `\\x1b[0m` (SGR reset), `\\x1b[?25h` (cursor show),\n * and `\\x1b[?9l` (mouse off) \u2014 all safe to emit even if the terminal does\n * not understand them (unknown CSI sequences are silently ignored).\n *\n * Safe to call multiple times from multiple exit paths because each write\n * is a constant-time synchronous stream write.\n *\n * @param stdout - Stream to reset (defaults to `process.stdout`).\n */\n reset(stdout: NodeJS.WriteStream = process.stdout): void {\n if (typeof stdout?.write !== 'function') return;\n // SGR reset \u2014 clears bold, color, underline, etc.\n stdout.write('\\x1b[0m');\n // Cursor show (in case Ink's unmount left it hidden).\n stdout.write('\\x1b[?25h');\n // Mouse tracking off (all three DECRST sequences \u2014 safe no-ops if never set).\n stdout.write('\\x1b[?1003l\\x1b[?1002l\\x1b[?1000l');\n }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// safeEscape \u2014 guarded escape-sequence emitter\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Result of emitting an escape sequence. Distinguishes the three distinct\n * failure modes so callers can degrade gracefully.\n */\nexport interface EscapeEmitResult {\n /** `true` when the sequence was written to the stream. */\n ok: boolean;\n /**\n * Human-readable reason when `ok` is `false`. One of:\n * `'not_a_tty'` \u2014 stdout is not a terminal (pipe / redirect / CI)\n * `'unwritable'` \u2014 stdout.write is missing or threw\n * `'empty'` \u2014 `sequence` was the empty string\n */\n reason: 'not_a_tty' | 'unwritable' | 'empty';\n}\n\n/**\n * A terminal escape sequence with its optional string terminator.\n *\n * OSC (title, color palette) sequences MUST be terminated with `BEL (\\x07)`\n * or `ST (\\x1b\\\\)` or the terminal stays in command mode and corrupts\n * subsequent output. CSI sequences (colors, cursor movement) are\n * self-terminating and do not need a terminator byte.\n */\nexport interface EscapeSequence {\n /** The raw sequence, e.g. `\\x1b[38;2;255;0;0m`. */\n raw: string;\n /**\n * Optional terminator byte required by OSC/DCS families.\n * `undefined` for CSI sequences; `\\x07` (BEL) for OSC; `\\x1b\\\\` (ST) for DCS.\n */\n terminator?: string;\n}\n\n/**\n * Shared OSC/DCS terminator bytes.\n *\n * BEL (`\\x07`) is understood by iTerm2, Konsole, mintty, foot, and\n * Windows Terminal. ST (`\\x1b\\\\`) is the strict DEC standard equivalent.\n * Prefer BEL for compatibility; fall back to ST if the terminal's response\n * to BEL is observed to be garbled.\n */\nexport const ESCAPE_TERMINATOR = Object.freeze({\n BEL: '\\x07', // OSC 0 / OSC 2 (title)\n ST: '\\x1b\\\\', // DCS / strict OSC\n});\n\n/**\n * Emit a terminal escape sequence safely.\n *\n * Rules enforced:\n * 1. Empty string \u2192 returns `ok: false, reason: 'empty'`, no write.\n * 2. Not a TTY \u2192 returns `ok: false, reason: 'not_a_tty'`, no write.\n * 3. Stream write throws \u2192 returns `ok: false, reason: 'unwritable'`.\n * 4. OSC/DCS sequences MUST have a terminator byte (guarded assertion).\n * A missing terminator on an OSC sequence corrupts output on terminals\n * that don't understand the sequence \u2014 this function refuses to emit it.\n *\n * @param sequence - The sequence to emit. CSI sequences need no terminator.\n * OSC/DCS sequences must carry `terminator: '\\x07'` or `'\\x1b\\\\'`.\n * @param stdout - Stream to write to (defaults to `process.stdout`).\n * @returns Result indicating success or the specific failure mode.\n */\nexport function safeEmit(\n sequence: EscapeSequence | string,\n stdout: NodeJS.WriteStream = process.stdout,\n): EscapeEmitResult {\n const raw = typeof sequence === 'string' ? sequence : sequence.raw;\n const term = typeof sequence === 'string' ? undefined : sequence.terminator;\n\n if (!raw) {\n return { ok: false, reason: 'empty' };\n }\n if (stdout?.isTTY !== true) {\n return { ok: false, reason: 'not_a_tty' };\n }\n\n // For OSC/DCS sequences (which include `[` or `]` in the body), verify a\n // terminator is present. CSI sequences start with `\\x1b[` and are\n // self-terminating; we treat any sequence that is not a known OSC/DCS\n // as CSI and allow through. OSC starts with `\\x1b]`; DCS with `\\x1bP`.\n if (raw.startsWith('\\x1b]') || raw.startsWith('\\x1bP')) {\n // Assertion: terminator must be provided. Belt-and-suspenders against\n // callers that forget to append `\\x07` \u2014 this prevents corrupted output.\n if (!term) {\n // Defensive: append BEL rather than crashing. This is the only case\n // where we mutate the sequence. The assert-then-fallback pattern is\n // intentional: we catch programmer error in development but degrade\n // safely in production rather than throwing.\n void term; // suppress unused-variable warning\n const safe = `${raw}\\x07`;\n try {\n stdout.write(safe);\n } catch {\n return { ok: false, reason: 'unwritable' };\n }\n return { ok: true, reason: 'empty' }; // reason field is ignored when ok=true\n }\n try {\n stdout.write(`${raw}${term}`);\n } catch {\n return { ok: false, reason: 'unwritable' };\n }\n return { ok: true, reason: 'empty' };\n }\n\n // CSI sequence \u2014 self-terminating.\n try {\n stdout.write(raw);\n } catch {\n return { ok: false, reason: 'unwritable' };\n }\n return { ok: true, reason: 'empty' };\n}\n\n/**\n * Build an OSC 0 / OSC 2 (window/tab title) sequence with a safe terminator.\n *\n * The terminator defaults to `BEL (\\x07)` for broad terminal compatibility.\n * Use `terminator: ESCAPE_TERMINATOR.ST` for stricter terminals that interpret\n * BEL as a beep.\n *\n * @param title - The title string. Embedded BEL bytes are stripped.\n * @param terminator - Defaults to `ESCAPE_TERMINATOR.BEL`.\n */\nexport function buildTitleSequence(\n title: string,\n terminator: string = ESCAPE_TERMINATOR.BEL,\n): EscapeSequence {\n return {\n raw: `\\x1b]0;${title.replace(/\\x07/g, '')}`,\n terminator,\n };\n}\n\n/**\n * Build an SGR (Select Graphic Rendition) color/style sequence.\n *\n * @param codes - SGR parameter list, e.g. `[31]` (red foreground),\n * `[1;32]` (bold green), `[38;2;255;128;0]` (truecolor orange).\n */\nexport function buildSgrSequence(...codes: number[]): EscapeSequence {\n return { raw: `\\x1b[${codes.join(';')}m` };\n}\n\n/**\n * Emit a title sequence. Convenience wrapper around `safeEmit` + `buildTitleSequence`.\n *\n * @param title - The title string.\n * @param stdout - Target stream.\n */\nexport function setTitle(\n title: string,\n stdout: NodeJS.WriteStream = process.stdout,\n): boolean {\n return safeEmit(buildTitleSequence(title), stdout).ok;\n}\n", "import { isStdoutTTY } from './term.js';\n\nconst isColorTty = (): boolean => {\n if (envFlag(process.env.NO_COLOR)) return false;\n if (envFlag(process.env.FORCE_COLOR)) return true;\n return isStdoutTTY();\n};\n\nfunction envFlag(value: string | undefined): boolean {\n if (value === undefined) return false;\n if (value.trim() === '') return false;\n return !/^(0|false|no|off)$/i.test(value.trim());\n}\n\nconst COLOR = isColorTty();\n\nconst wrap =\n (open: string, close: string) =>\n (s: string): string =>\n COLOR ? `\\x1b[${open}m${s}\\x1b[${close}m` : s;\n\nexport const color = {\n reset: wrap('0', '0'),\n bold: wrap('1', '22'),\n dim: wrap('2', '22'),\n italic: wrap('3', '23'),\n underline: wrap('4', '24'),\n red: wrap('31', '39'),\n green: wrap('32', '39'),\n yellow: wrap('33', '39'),\n blue: wrap('34', '39'),\n magenta: wrap('35', '39'),\n cyan: wrap('36', '39'),\n gray: wrap('90', '39'),\n amber: wrap('38;5;214', '39'),\n pink: wrap('38;5;205', '39'),\n bgRed: wrap('41', '49'),\n bgGreen: wrap('42', '49'),\n};\n\nexport function stripAnsi(s: string): string {\n return s.replace(/\\x1b\\[[0-9;]*[A-Za-z]/g, '');\n}\n", "import type { TaskTracker } from '../tasking/index.js';\nimport type { TaskNode } from '../types/task-graph.js';\nimport type { PhaseGraph, PhaseNode, PhaseStatus } from './types.js';\n\ntype PhaseBoardEmit =\n | {\n event: 'phase.taskMoved';\n payload: { taskId: string; fromPhaseId: string; toPhaseId: string };\n }\n | {\n event: 'phase.taskAssigned';\n payload: { phaseId: string; taskId: string; agentId?: string; agentName?: string };\n }\n | {\n event: 'phase.taskAdded';\n payload: { phaseId: string; taskId: string; taskTitle: string };\n };\n\nexport interface PhaseBoardMutationContext {\n graph: PhaseGraph;\n trackerCache: Map<string, TaskTracker>;\n taskRetryCounts: Map<string, number>;\n phaseWorktrees: Map<string, unknown>;\n getTrackerForPhase: (phase: PhaseNode) => TaskTracker;\n updatePhaseStatus: (phase: PhaseNode, status: PhaseStatus) => void;\n emit: (event: PhaseBoardEmit['event'], payload: PhaseBoardEmit['payload']) => void;\n}\n\nexport function findPhaseOfTaskInGraph(\n graph: PhaseGraph,\n taskId: string,\n): PhaseNode | undefined {\n for (const phase of graph.phases.values()) {\n if (phase.taskGraph.nodes.has(taskId)) return phase;\n }\n return undefined;\n}\n\nexport function movePhaseTask(\n ctx: PhaseBoardMutationContext,\n taskId: string,\n toPhaseId: string,\n): boolean {\n const from = findPhaseOfTaskInGraph(ctx.graph, taskId);\n const to = ctx.graph.phases.get(toPhaseId);\n if (!from || !to || from.id === toPhaseId) return false;\n\n const node = from.taskGraph.nodes.get(taskId);\n if (!node) return false;\n\n const dependents = from.taskGraph.edges.filter((e) => e.from === taskId).map((e) => e.to);\n for (const depId of dependents) {\n const depNode = from.taskGraph.nodes.get(depId);\n if (depNode) {\n depNode.parentId = undefined;\n depNode.children = undefined;\n }\n from.taskGraph.edges = from.taskGraph.edges.filter(\n (e) => !(e.from === taskId && e.to === depId),\n );\n if (!from.taskGraph.rootNodes.includes(depId)) {\n from.taskGraph.rootNodes.push(depId);\n }\n }\n\n from.taskGraph.nodes.delete(taskId);\n from.taskGraph.rootNodes = from.taskGraph.rootNodes.filter((id) => id !== taskId);\n from.taskGraph.edges = from.taskGraph.edges.filter((e) => e.from !== taskId && e.to !== taskId);\n from.taskGraph.updatedAt = Date.now();\n\n node.parentId = undefined;\n node.children = undefined;\n node.updatedAt = Date.now();\n to.taskGraph.nodes.set(taskId, node);\n to.taskGraph.rootNodes.push(taskId);\n to.taskGraph.updatedAt = Date.now();\n\n ctx.trackerCache.delete(from.id);\n ctx.trackerCache.delete(to.id);\n ctx.graph.updatedAt = Date.now();\n ctx.emit('phase.taskMoved', { taskId, fromPhaseId: from.id, toPhaseId });\n return true;\n}\n\nexport function setPhaseTaskAssignee(\n ctx: PhaseBoardMutationContext,\n taskId: string,\n agentId?: string,\n agentName?: string,\n): boolean {\n const phase = findPhaseOfTaskInGraph(ctx.graph, taskId);\n if (!phase) return false;\n const tracker = ctx.getTrackerForPhase(phase);\n tracker.updateNode(taskId, { assignee: agentName ?? agentId ?? '' });\n ctx.graph.updatedAt = Date.now();\n ctx.emit('phase.taskAssigned', {\n phaseId: phase.id,\n taskId,\n ...(agentId !== undefined ? { agentId } : {}),\n ...(agentName !== undefined ? { agentName } : {}),\n });\n return true;\n}\n\nexport function addPhaseTask(\n ctx: PhaseBoardMutationContext,\n phaseId: string,\n spec: {\n title: string;\n description?: string | undefined;\n type?: TaskNode['type'] | undefined;\n priority?: TaskNode['priority'] | undefined;\n },\n): string | null {\n const phase = ctx.graph.phases.get(phaseId);\n if (!phase) return null;\n const tracker = ctx.getTrackerForPhase(phase);\n const node = tracker.addNode({\n title: spec.title,\n description: spec.description ?? '',\n type: spec.type ?? 'feature',\n priority: spec.priority ?? 'medium',\n status: 'pending',\n });\n ctx.graph.updatedAt = Date.now();\n ctx.emit('phase.taskAdded', { phaseId, taskId: node.id, taskTitle: node.title });\n return node.id;\n}\n\nexport function requeuePhaseTask(ctx: PhaseBoardMutationContext, taskId: string): boolean {\n const phase = findPhaseOfTaskInGraph(ctx.graph, taskId);\n if (!phase) return false;\n const tracker = ctx.getTrackerForPhase(phase);\n tracker.updateNodeStatus(taskId, 'pending');\n ctx.taskRetryCounts.delete(`${phase.id}:${taskId}`);\n if (phase.status === 'completed' || phase.status === 'failed' || phase.status === 'paused') {\n ctx.graph.failedPhaseIds = ctx.graph.failedPhaseIds.filter((id) => id !== phase.id);\n ctx.graph.completedPhaseIds = ctx.graph.completedPhaseIds.filter((id) => id !== phase.id);\n ctx.graph.activePhaseIds = ctx.graph.activePhaseIds.filter((id) => id !== phase.id);\n ctx.phaseWorktrees.delete(phase.id);\n ctx.updatePhaseStatus(phase, 'pending');\n }\n ctx.graph.updatedAt = Date.now();\n return true;\n}\n", "/**\n * Read-only queries over a phase graph, plus the two leaf helpers that only\n * touch a phase's own record.\n *\n * Split out of `phase-orchestrator.ts`. Nothing here schedules, emits, or\n * mutates orchestrator state \u2014 each function derives its answer from the graph\n * (and, where task counts are involved, the orchestrator's tracker lookup).\n *\n * @module goal/phase-orchestrator-queries\n */\nimport type { TaskTracker } from '../tasking/index.js';\nimport type { TaskNode } from '../types/task-graph.js';\nimport type { PhaseGraph, PhaseNode, PhaseProgress } from './types.js';\n\n/** Resolves (and memoizes) the TaskTracker backing a phase's task graph. */\nexport type TrackerLookup = (phase: PhaseNode) => TaskTracker;\n\nexport function getReadyPhases(graph: PhaseGraph): PhaseNode[] {\n const ready: PhaseNode[] = [];\n\n for (const phase of graph.phases.values()) {\n if (phase.status !== 'pending') continue;\n\n const depsDone = phase.dependsOn.every((depId) => {\n const dep = graph.phases.get(depId);\n return dep?.status === 'completed' || dep?.status === 'skipped' || dep?.status === 'failed';\n });\n\n // A phase is ready ONLY when its dependencies are resolved. `parallelizable`\n // governs whether ready phases may run CONCURRENTLY (the `maxConcurrentPhases`\n // batch in start()/tick() already enforces that) \u2014 it must NOT let a phase\n // start before its dependencies finish. (Previously this read\n // `depsDone || phase.parallelizable`, which let a dependent-but-parallelizable\n // phase, e.g. a Testing phase depending on Implementation, jump the gun.)\n if (depsDone) {\n ready.push(phase);\n }\n }\n\n const prioOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n ready.sort((a, b) => (prioOrder[a.priority] ?? 4) - (prioOrder[b.priority] ?? 4));\n\n return ready;\n}\n\nexport function getActivePhases(graph: PhaseGraph): PhaseNode[] {\n return Array.from(graph.phases.values()).filter((p) => p.status === 'running');\n}\n\nexport function getExecutableTasks(trackerFor: TrackerLookup, phase: PhaseNode): TaskNode[] {\n const tracker = trackerFor(phase);\n return tracker\n .getAllNodes({ status: ['pending', 'blocked'] })\n .filter(\n (n: { id: string; status: string; priority: string }) =>\n n.status === 'pending' && tracker.canStart(n.id),\n )\n .sort((a: { priority: TaskNode['priority'] }, b: { priority: TaskNode['priority'] }) => {\n const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n return (priorityOrder[a.priority] ?? 4) - (priorityOrder[b.priority] ?? 4);\n });\n}\n\nexport function getFailedTaskCount(trackerFor: TrackerLookup, phase: PhaseNode): number {\n return trackerFor(phase).getAllNodes({ status: ['failed'] }).length;\n}\n\nexport function getCompletedTaskCount(trackerFor: TrackerLookup, phase: PhaseNode): number {\n return trackerFor(phase).getAllNodes({ status: ['completed'] }).length;\n}\n\nexport function isGraphComplete(graph: PhaseGraph): boolean {\n const allPhases = Array.from(graph.phases.values());\n return allPhases.every(\n (p) => p.status === 'completed' || p.status === 'skipped' || p.status === 'failed',\n );\n}\n\nexport function getProgress(graph: PhaseGraph, trackerFor: TrackerLookup): PhaseProgress {\n const phases = Array.from(graph.phases.values());\n let pending = 0;\n let ready = 0;\n let running = 0;\n let paused = 0;\n let completed = 0;\n let failed = 0;\n let skipped = 0;\n let totalTasks = 0;\n let completedTasks = 0;\n let failedTasks = 0;\n let estimatedHours = 0;\n let actualHours = 0;\n\n for (const p of phases) {\n switch (p.status) {\n case 'pending':\n pending++;\n break;\n case 'ready':\n ready++;\n break;\n case 'running':\n running++;\n break;\n case 'paused':\n paused++;\n break;\n case 'completed':\n completed++;\n break;\n case 'failed':\n failed++;\n break;\n case 'skipped':\n skipped++;\n break;\n default:\n // Unknown phase status \u2014 log and skip in counter\n break;\n }\n estimatedHours += p.estimateHours;\n if (p.actualDurationMs) actualHours += p.actualDurationMs / 3600000;\n\n const tracker = trackerFor(p);\n const progress = tracker.getProgress();\n totalTasks += progress.total;\n completedTasks += progress.completed;\n failedTasks += progress.failed;\n }\n\n const totalPhases = phases.length;\n const done = completed + skipped;\n\n return {\n totalPhases,\n pending,\n ready,\n running,\n paused,\n completed,\n failed,\n skipped,\n percentComplete: totalPhases > 0 ? Math.min(100, Math.round((done / totalPhases) * 100)) : 0,\n totalTasks,\n completedTasks,\n failedTasks,\n estimatedHours,\n actualHours,\n };\n}\n\nexport function setIntegrationMetadata(\n graph: PhaseGraph,\n phase: PhaseNode,\n status: 'merged' | 'needs_review' | 'merge_failed' | 'not_merged_failed_phase',\n details: {\n branch?: string | undefined;\n worktreeDir?: string | undefined;\n conflictFiles?: string[] | undefined;\n error?: string | undefined;\n } = {},\n): void {\n phase.metadata = {\n ...phase.metadata,\n integrationStatus: status,\n integrationBranch: details.branch,\n integrationWorktreeDir: details.worktreeDir,\n integrationConflictFiles: details.conflictFiles,\n integrationError: details.error,\n integrationUpdatedAt: Date.now(),\n };\n phase.updatedAt = Date.now();\n graph.updatedAt = Date.now();\n}\n\nexport function truncate(text: string, max = 500): string {\n const t = text.trim();\n return t.length <= max ? t : `${t.slice(0, max)}\u2026 (+${t.length - max} chars)`;\n}\n", "/**\n * Worktree integration for phases: commit, dependency-ordered squash-merge back\n * into the base branch, conflict arbitration, and the failure bookkeeping that\n * keeps the graph honest when a merge does not land.\n *\n * Split out of `phase-orchestrator.ts`. The orchestrator passes an\n * {@link IntegrationContext} holding the state these steps read and mutate \u2014\n * the same fields the private methods reached through `this`.\n *\n * @module goal/phase-orchestrator-integration\n */\nimport type { Logger } from '../types/logger.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport type { WorktreeHandle, WorktreeManager } from '../worktree/worktree-manager.js';\nimport { setIntegrationMetadata } from './phase-orchestrator-queries.js';\nimport type { PhaseEventMap, PhaseEventName, PhaseExecutionContext, PhaseGraph, PhaseNode, PhaseStatus } from './types.js';\n\n/** Orchestrator state the integration steps operate on. */\nexport interface IntegrationContext {\n graph: PhaseGraph;\n ctx: PhaseExecutionContext;\n logger: Logger;\n worktrees: WorktreeManager | undefined;\n /** phaseId \u2192 allocated worktree handle. */\n phaseWorktrees: Map<string, WorktreeHandle>;\n /** phaseId \u2192 promise settling when that phase's merge finished. */\n phaseMergePromise: Map<string, Promise<void>>;\n runningPhases: Set<string>;\n /** Global serialization chain \u2014 read and replaced by `commitAndEnqueueMerge`. */\n getMergeQueue: () => Promise<void>;\n setMergeQueue: (queue: Promise<void>) => void;\n emit: <E extends PhaseEventName>(event: E, payload: PhaseEventMap[E]) => void;\n updatePhaseStatus: (phase: PhaseNode, status: PhaseStatus) => void;\n}\n\nexport function worktreeEnv(\n int: IntegrationContext,\n phase: PhaseNode,\n): { cwd?: string | undefined; branch?: string | undefined } | undefined {\n const handle = int.phaseWorktrees.get(phase.id);\n return handle ? { cwd: handle.dir, branch: handle.branch } : undefined;\n}\n\n/** Shared failure bookkeeping for a phase whose tasks ran but the phase failed. */\nexport async function failPhaseAfterTasks(\n int: IntegrationContext,\n phase: PhaseNode,\n error: string,\n): Promise<void> {\n int.updatePhaseStatus(phase, 'failed');\n phase.completedAt = Date.now();\n phase.actualDurationMs = Date.now() - (phase.startedAt ?? Date.now());\n int.runningPhases.delete(phase.id);\n int.graph.activePhaseIds = int.graph.activePhaseIds.filter((id) => id !== phase.id);\n int.emit('phase.failed', { phaseId: phase.id, name: phase.name, error });\n int.ctx.onPhaseFail?.(phase, new Error(error));\n await keepWorktreeForReview(int, phase);\n}\n\n/**\n * A phase whose tasks all succeeded was marked `completed` and queued for\n * merge, but the merge back into the base branch failed. Its work is NOT\n * integrated, so correct the graph: move the phase out of `completedPhaseIds`\n * into `failedPhaseIds` and flip its status to `failed`. Without this the\n * persisted graph (and the board) would claim the phase succeeded while a\n * `phase.failed` event fired \u2014 an inconsistency that hides un-merged work.\n * Idempotent: safe to call more than once for the same phase.\n */\nexport function markPhaseMergeFailed(\n int: IntegrationContext,\n phase: PhaseNode,\n error: string,\n): void {\n if (phase.status !== 'failed') {\n int.graph.completedPhaseIds = int.graph.completedPhaseIds.filter((id) => id !== phase.id);\n int.updatePhaseStatus(phase, 'failed');\n }\n if (!int.graph.failedPhaseIds.includes(phase.id)) int.graph.failedPhaseIds.push(phase.id);\n int.emit('phase.failed', { phaseId: phase.id, name: phase.name, error });\n int.ctx.onPhaseFail?.(phase, new Error(error));\n}\n\n/**\n * Commit the phase's worktree changes, then enqueue the merge back into the\n * base branch. Merges run dependency-ordered (a phase merges only after its\n * `dependsOn` phases) and globally serialized (one at a time) to avoid\n * concurrent writes to the base tree.\n */\nexport async function commitAndEnqueueMerge(\n int: IntegrationContext,\n phase: PhaseNode,\n): Promise<void> {\n const handle = int.phaseWorktrees.get(phase.id);\n if (!int.worktrees || !handle) return;\n\n try {\n await int.worktrees.commitAll(handle, `goal(${phase.name}): ${phase.id}`);\n } catch {\n // commit failure is non-fatal; the merge step will report a clean tree.\n }\n\n const depPromises = phase.dependsOn\n .map((d) => int.phaseMergePromise.get(d))\n .filter((p): p is Promise<void> => Boolean(p));\n\n const merged = (async () => {\n await Promise.allSettled(depPromises); // dependency-ordered\n // Chain onto the global queue so only one merge touches base at a time.\n int.setMergeQueue(\n int\n .getMergeQueue()\n .then(() => mergeOne(int, phase, handle))\n .catch((err) => {\n // Defensive backstop: mergeOne handles its own errors, so this only\n // fires if it throws unexpectedly. Keep the queue alive (a failed\n // merge must not poison the chain) and correct the graph state.\n const msg = toErrorMessage(err);\n int.logger.error(msg, { event: 'orchestrator.merge_failed', phaseId: phase.id });\n markPhaseMergeFailed(int, phase, msg);\n }),\n );\n await int.getMergeQueue();\n })();\n int.phaseMergePromise.set(phase.id, merged);\n}\n\n/**\n * Squash-merge one phase. When a `resolveConflict` callback is wired, a merge\n * conflict is handed to it (a resolver subagent) before giving up; only if\n * that fails does the worktree fall to needs-review and the run continues.\n */\nasync function mergeOne(\n int: IntegrationContext,\n phase: PhaseNode,\n handle: WorktreeHandle,\n): Promise<void> {\n if (!int.worktrees) return;\n try {\n const resolve = int.ctx.resolveConflict\n ? async (info: { conflictFiles: string[]; cwd: string }) => {\n const shouldResolve = await shouldAttemptConflictResolution(int, phase, info);\n if (!shouldResolve) return false;\n int.emit('phase.conflictResolving', {\n phaseId: phase.id,\n name: phase.name,\n files: info.conflictFiles,\n });\n const resolved = await int.ctx.resolveConflict?.(phase, info);\n return resolved ?? false;\n }\n : undefined;\n const mergeOpts: {\n squash: true;\n resolve?: (info: { conflictFiles: string[]; cwd: string }) => Promise<boolean>;\n } = {\n squash: true,\n };\n if (resolve !== undefined) mergeOpts.resolve = resolve;\n const result = await int.worktrees.merge(handle, mergeOpts);\n if (result.resolved) {\n int.emit('phase.conflictResolved', { phaseId: phase.id, name: phase.name });\n }\n setIntegrationMetadata(int.graph, phase, result.ok ? 'merged' : 'needs_review', {\n branch: handle.branch,\n worktreeDir: handle.dir,\n conflictFiles: result.conflictFiles,\n });\n // merge() already emitted worktree.merged / worktree.conflict and set status.\n // Clean (or resolved) merge \u2192 remove the worktree; conflict \u2192 release(keep).\n await int.worktrees.release(handle, { keep: !result.ok });\n } catch (err) {\n setIntegrationMetadata(int.graph, phase, 'merge_failed', {\n branch: handle.branch,\n worktreeDir: handle.dir,\n error: toErrorMessage(err),\n });\n // The merge failed \u2192 the phase's work never reached base. Reflect that in\n // the graph, not just in metadata + a stray event (see markPhaseMergeFailed).\n markPhaseMergeFailed(int, phase, `worktree merge failed: ${toErrorMessage(err)}`);\n }\n}\n\nasync function shouldAttemptConflictResolution(\n int: IntegrationContext,\n phase: PhaseNode,\n info: { conflictFiles: string[]; cwd: string },\n): Promise<boolean> {\n if (!int.ctx.brain) return true;\n\n const decision = await int.ctx.brain.decide({\n id: `goal-conflict-${phase.id}`,\n source: 'goal',\n question: `Should Goal try to resolve merge conflicts for phase \"${phase.name}\" automatically?`,\n context: [\n `Phase id: ${phase.id}`,\n `Conflicted files: ${info.conflictFiles.join(', ') || '(unknown)'}`,\n `Base working tree: ${info.cwd}`,\n ].join('\\n'),\n // 'critical', not 'high': choosing `resolve` lets a resolver agent EDIT\n // FILES IN THE BASE WORKING TREE. That is the one Brain decision in the\n // system whose wrong answer is not recoverable by simply continuing \u2014\n // unlike a budget grant (bounded, capped) or a goal-done verdict (the\n // run can be restarted).\n //\n // Consequences of the level, both intended:\n // - it is at or above the council floor, so a multi-LLM panel decides\n // it whenever one can convene;\n // - with no council (a single-model install resolves the autonomy\n // ceiling to 'high'), it exceeds the ceiling and never reaches an\n // unchecked single model. The policy tier's `ask_human` then routes\n // to the terminal policy, which refuses a recommended option at\n // critical risk and denies \u2014 i.e. the worktree is kept for human\n // review, which is exactly the safe outcome.\n risk: 'critical',\n fallback: 'ask_human',\n options: [\n {\n id: 'resolve',\n label: 'Try the configured conflict resolver',\n consequence: 'A resolver agent may edit conflicted files in the base working tree.',\n risk: 'critical',\n },\n {\n id: 'review',\n label: 'Keep the worktree for human review',\n consequence: 'No automatic conflict resolution is attempted.',\n risk: 'low',\n recommended: true,\n },\n ],\n });\n\n phase.metadata = {\n ...phase.metadata,\n brainConflictDecision: decision.type,\n brainConflictDecisionAt: Date.now(),\n };\n\n if (decision.type !== 'answer') return false;\n // Control-plane check: automatic conflict resolution runs ONLY on the\n // exact option id. Prose mentioning \"resolve\" is not authorization.\n return decision.optionId === 'resolve';\n}\n\n/** A failed phase keeps its worktree on disk for inspection (no merge). */\nexport async function keepWorktreeForReview(\n int: IntegrationContext,\n phase: PhaseNode,\n): Promise<void> {\n const handle = int.phaseWorktrees.get(phase.id);\n if (!int.worktrees || !handle) return;\n try {\n await int.worktrees.commitAll(handle, `goal(${phase.name}) [failed]: ${phase.id}`);\n } catch {\n // best effort\n }\n setIntegrationMetadata(int.graph, phase, 'not_merged_failed_phase', {\n branch: handle.branch,\n worktreeDir: handle.dir,\n });\n await int.worktrees.release(handle, { keep: true }).catch(() => {});\n}\n", "import type { EventBus } from '../kernel/events.js';\nimport type { PhaseGraph } from './types.js';\n\nexport function normalizePhaseGraphForResume(graph: PhaseGraph): void {\n graph.activePhaseIds = [];\n for (const phase of graph.phases.values()) {\n if (phase.status === 'running') {\n phase.status = 'pending';\n phase.updatedAt = Date.now();\n }\n if (phase.status === 'pending') {\n for (const task of phase.taskGraph.nodes.values()) {\n if (task.status === 'in_progress') task.status = 'pending';\n }\n }\n }\n}\n\nexport function createNoopEventBus(): EventBus {\n return {\n emit: () => {},\n on: () => () => {},\n off: () => {},\n once: () => () => {},\n listeners: new Map(),\n wildcards: [],\n setLogger: () => {},\n onAny: () => () => {},\n offAny: () => {},\n emitAsync: async () => [],\n waitFor: async () => {},\n } as never as EventBus;\n}\n", "import type { EventBus } from '../kernel/events.js';\nimport type { Logger } from '../types/logger.js';\nimport { noOpLogger } from '../infrastructure/logger.js';\nimport { DefaultTaskStore, TaskTracker } from '../tasking/index.js';\nimport type { TaskNode } from '../types/task-graph.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport type { WorktreeHandle, WorktreeManager } from '../worktree/worktree-manager.js';\nimport {\n addPhaseTask,\n findPhaseOfTaskInGraph,\n movePhaseTask,\n requeuePhaseTask,\n setPhaseTaskAssignee,\n} from './phase-board-mutations.js';\nimport {\n commitAndEnqueueMerge,\n failPhaseAfterTasks,\n type IntegrationContext,\n keepWorktreeForReview,\n worktreeEnv,\n} from './phase-orchestrator-integration.js';\nimport {\n getActivePhases,\n getCompletedTaskCount,\n getExecutableTasks,\n getFailedTaskCount,\n getProgress,\n getReadyPhases,\n isGraphComplete,\n truncate,\n} from './phase-orchestrator-queries.js';\nimport { createNoopEventBus, normalizePhaseGraphForResume } from './phase-orchestrator-runtime.js';\nimport type {\n NormalizedGoalOptions,\n PhaseOrchestratorOptions,\n} from './phase-orchestrator-types.js';\nimport type {\n PhaseEventMap,\n PhaseEventName,\n PhaseExecutionContext,\n PhaseGraph,\n PhaseNode,\n PhaseProgress,\n PhaseStatus,\n} from './types.js';\nexport type { PhaseOrchestratorOptions } from './phase-orchestrator-types.js';\n\n/**\n * PhaseOrchestrator - dependency-aware engine for running phases autonomously.\n *\n * Features:\n * - Automatically starts the next phase as each phase completes in autonomous mode\n * - Supports parallel phases with parallelizable=true\n * - Assigns and releases agents\n * - Integrates with the event bus\n * - Supports pause and resume\n */\nexport class PhaseOrchestrator {\n private graph: PhaseGraph;\n private ctx: PhaseExecutionContext;\n private opts: NormalizedGoalOptions;\n private events: EventBus;\n private stopped = false;\n private paused = false;\n private runningPhases = new Set<string>();\n private tickInterval: ReturnType<typeof setInterval> | null = null;\n private trackerCache = new Map<string, TaskTracker>();\n private taskRetryCounts = new Map<string, number>();\n\n // \u2500\u2500 Git-worktree isolation (optional) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n private readonly worktrees?: WorktreeManager | undefined;\n private readonly logger: Logger;\n /** Per-phase worktree handles, keyed by phase id. */\n private readonly phaseWorktrees = new Map<string, WorktreeHandle>();\n /** Serializes all merges back to the base branch (one at a time). */\n private mergeQueue: Promise<void> = Promise.resolve();\n /** Per-phase merge promise, so a phase merges only after its deps do. */\n private readonly phaseMergePromise = new Map<string, Promise<void>>();\n\n constructor(opts: PhaseOrchestratorOptions) {\n this.graph = opts.graph;\n this.ctx = opts.ctx;\n this.events = opts.events ?? createNoopEventBus();\n this.worktrees = opts.worktrees;\n this.logger = opts.logger ?? noOpLogger;\n this.opts = {\n maxConcurrentPhases: opts.maxConcurrentPhases ?? 1,\n maxConcurrentTasks: opts.maxConcurrentTasks ?? 2,\n maxRetries: opts.maxRetries ?? 2,\n maxVerifyAttempts: opts.maxVerifyAttempts ?? 2,\n autonomous: opts.autonomous ?? true,\n phaseDelayMs: opts.phaseDelayMs ?? 0,\n stopOnFailure: opts.stopOnFailure ?? false,\n taskTimeoutMs: opts.taskTimeoutMs ?? 600_000,\n events: this.events,\n };\n }\n\n // \u2500\u2500\u2500 Lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Start the full phase flow.\n * In autonomous mode, starts root phases and automatically starts the next phase when they finish.\n */\n async start(): Promise<void> {\n this.stopped = false;\n this.paused = false;\n this.normalizeForResume();\n this.graph.startedAt = Date.now();\n this.graph.updatedAt = Date.now();\n\n // Run phases in order; later phases still start when autonomous=false.\n let readyPhases = this.getReadyPhases();\n while (readyPhases.length > 0 && !this.stopped) {\n await this.waitWhilePaused();\n if (this.stopped) break;\n\n const batch = readyPhases.slice(0, this.opts.maxConcurrentPhases);\n await Promise.all(batch.map((p) => this.startPhase(p)));\n\n // Apply phase delay.\n if (this.opts.phaseDelayMs > 0) {\n await this.delay(this.opts.phaseDelayMs);\n }\n\n await this.waitWhilePaused();\n if (this.stopped) break;\n\n // Check for newly ready phases after a phase completes.\n readyPhases = this.getReadyPhases().filter(\n (p) => !this.runningPhases.has(p.id) && p.status !== 'completed' && p.status !== 'failed',\n );\n }\n\n // Wait for all queued worktree merges to finish in the background so\n // changes reach the base branch before the graph is declared completed.\n await this.drainMerges();\n\n // Autonomous tick loop for real-time monitoring.\n if (this.opts.autonomous) {\n this.tickInterval = setInterval(() => this.tick(), 1000);\n }\n }\n\n /**\n * Make a (possibly resumed) graph runnable. A graph loaded from disk after an\n * interrupted run can carry transient state from the dead process: phases left\n * `running` and tasks left `in_progress`. The scheduler only starts `pending`\n * phases (getReadyPhases) and only runs `pending` tasks (getExecutableTasks),\n * so without this a resumed phase/task would stall forever. Reset that\n * transient state to `pending`; terminal phases (completed/failed/skipped) and\n * already-completed tasks are untouched, so completed work is never re-run.\n * For a freshly built graph this is a no-op.\n */\n private normalizeForResume(): void {\n normalizePhaseGraphForResume(this.graph);\n }\n\n /** Wait for all pending phase merges, dependency-ordered and globally serialized. */\n private async drainMerges(): Promise<void> {\n await Promise.allSettled([...this.phaseMergePromise.values()]);\n await this.mergeQueue.catch((err) => {\n const msg = toErrorMessage(err);\n this.logger.warn(msg, { event: 'orchestrator.merge_queue_failed' });\n });\n }\n\n /** Pause: active phases continue, but no new phase starts. */\n pause(): void {\n this.paused = true;\n }\n\n /** Resume: new phases may start again. */\n resume(): void {\n this.paused = false;\n this.tick().catch((err) => {\n const msg = toErrorMessage(err);\n this.logger.error(msg, { event: 'orchestrator.tick_failed' });\n });\n }\n\n /** Stop completely, including active phases. */\n stop(): void {\n this.stopped = true;\n if (this.tickInterval) {\n clearInterval(this.tickInterval);\n this.tickInterval = null;\n }\n for (const phaseId of this.runningPhases) {\n const phase = this.graph.phases.get(phaseId);\n if (phase) {\n this.updatePhaseStatus(phase, 'paused');\n }\n }\n // Preserve any live worktrees for inspection rather than discarding work.\n if (this.worktrees) {\n for (const handle of this.worktrees.list()) {\n void this.worktrees.release(handle, { keep: true }).catch(() => {});\n }\n }\n }\n\n // \u2500\u2500\u2500 Tick Loop (Autonomous) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async tick(): Promise<void> {\n if (this.stopped || this.paused) return;\n\n const active = this.getActivePhases();\n const queued = this.getReadyPhases();\n\n this.emit('autonomous.tick', {\n activePhases: active.map((p) => p.id),\n queuedPhases: queued.map((p) => p.id),\n });\n\n this.ctx.onTick?.({ activePhases: active, readyPhases: queued });\n\n // Is there a slot to start a new phase?\n const availableSlots = this.opts.maxConcurrentPhases - active.length;\n if (availableSlots > 0 && queued.length > 0) {\n for (const phase of queued.slice(0, availableSlots)) {\n if (phase.status === 'pending') {\n await this.startPhase(phase);\n }\n }\n }\n\n // Are all phases complete?\n if (this.isComplete()) {\n this.onGraphComplete();\n return;\n }\n\n // Did a phase fail while stopOnFailure is enabled?\n if (this.opts.stopOnFailure && this.graph.failedPhaseIds.length > 0) {\n const failedPhase = this.graph.phases.get(this.graph.failedPhaseIds[0] ?? '');\n if (failedPhase) {\n this.onGraphFailed(failedPhase);\n }\n return;\n }\n }\n\n // \u2500\u2500\u2500 Phase Execution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async startPhase(phase: PhaseNode): Promise<void> {\n if (phase.status !== 'pending' && phase.status !== 'ready') return;\n\n this.updatePhaseStatus(phase, 'running');\n phase.startedAt = Date.now();\n this.runningPhases.add(phase.id);\n this.graph.activePhaseIds.push(phase.id);\n\n // Allocate an isolated git worktree for this phase, if a manager is wired.\n // Allocation failure degrades gracefully to the shared working tree.\n if (this.worktrees && !this.phaseWorktrees.has(phase.id)) {\n try {\n const handle = await this.worktrees.allocate(phase.id, {\n slugHint: phase.name,\n ownerLabel: phase.name,\n });\n if (handle.status === 'active') this.phaseWorktrees.set(phase.id, handle);\n } catch {\n // Manager already emitted worktree.failed; run on the shared tree.\n }\n }\n\n this.emit('phase.started', { phaseId: phase.id, name: phase.name });\n\n try {\n await this.executePhaseTasks(phase);\n\n const failedTasks = this.getFailedTaskCount(phase);\n const completedTasks = this.getCompletedTaskCount(phase);\n\n this.emit('phase.allTasksDone', {\n phaseId: phase.id,\n completed: completedTasks,\n failed: failedTasks,\n });\n\n if (failedTasks > 0 && this.opts.stopOnFailure) {\n await this.failPhaseAfterTasks(phase, `${failedTasks} task(s) failed`);\n return;\n }\n\n // Verification gate: all tasks succeeded, but the produced code must still\n // pass (typecheck/test/\u2026) before we mark the phase done and merge it back.\n // Skipped entirely when no verifyPhase callback is wired (back-compat).\n const verdict = await this.runVerifyGate(phase);\n if (!verdict.ok) {\n await this.failPhaseAfterTasks(\n phase,\n `verification failed${verdict.output ? `: ${this.truncate(verdict.output)}` : ''}`,\n );\n return;\n }\n\n this.updatePhaseStatus(phase, 'completed');\n phase.completedAt = Date.now();\n phase.actualDurationMs = Date.now() - (phase.startedAt ?? Date.now());\n this.runningPhases.delete(phase.id);\n this.graph.activePhaseIds = this.graph.activePhaseIds.filter((id) => id !== phase.id);\n this.graph.completedPhaseIds.push(phase.id);\n this.emit('phase.completed', {\n phaseId: phase.id,\n name: phase.name,\n durationMs: phase.actualDurationMs,\n });\n this.ctx.onPhaseComplete?.(phase);\n // Commit the phase's work in its worktree and queue the merge back into\n // the base branch (dependency-ordered + globally serialized).\n await this.commitAndEnqueueMerge(phase);\n } catch (error) {\n this.updatePhaseStatus(phase, 'failed');\n phase.completedAt = Date.now();\n phase.actualDurationMs = Date.now() - (phase.startedAt ?? Date.now());\n this.runningPhases.delete(phase.id);\n this.graph.activePhaseIds = this.graph.activePhaseIds.filter((id) => id !== phase.id);\n this.graph.failedPhaseIds.push(phase.id);\n this.emit('phase.failed', {\n phaseId: phase.id,\n name: phase.name,\n error: error instanceof Error ? error.message : String(error),\n });\n this.ctx.onPhaseFail?.(phase, error instanceof Error ? error : new Error(String(error)));\n await this.keepWorktreeForReview(phase);\n }\n }\n\n // \u2500\u2500\u2500 Verification gate \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Run the verification gate for a phase whose tasks all succeeded. Verifies in\n * the phase's worktree; on failure, runs the repair pass and re-verifies, up to\n * `maxVerifyAttempts` repairs. Returns the final verdict. When no `verifyPhase`\n * callback is wired the gate is a no-op and always passes.\n */\n private async runVerifyGate(phase: PhaseNode): Promise<{ ok: boolean; output?: string | undefined }> {\n if (!this.ctx.verifyPhase) return { ok: true };\n const env = this.worktreeEnv(phase);\n\n for (let attempt = 0; attempt <= this.opts.maxVerifyAttempts; attempt++) {\n if (this.stopped) return { ok: false, output: 'stopped before verification completed' };\n\n this.emit('phase.verifying', { phaseId: phase.id, name: phase.name, attempt });\n let verdict: { ok: boolean; output?: string | undefined };\n try {\n verdict = await this.ctx.verifyPhase(phase, env);\n } catch (err) {\n verdict = { ok: false, output: toErrorMessage(err) };\n }\n if (verdict.ok) return { ok: true };\n\n this.emit('phase.verifyFailed', {\n phaseId: phase.id,\n name: phase.name,\n attempt,\n error: verdict.output,\n });\n\n // Out of attempts, no repair pass available, or aborted \u2192 give up.\n if (attempt >= this.opts.maxVerifyAttempts || !this.ctx.repairPhase || this.stopped) {\n return { ok: false, output: verdict.output };\n }\n\n this.emit('phase.repairing', { phaseId: phase.id, name: phase.name, attempt: attempt + 1 });\n try {\n await this.ctx.repairPhase(\n phase,\n verdict.output ?? 'verification failed',\n attempt + 1,\n env,\n );\n } catch {\n // A failed repair is non-fatal: the next verifyPhase run will observe the\n // still-broken tree and the loop will exit with ok:false.\n }\n }\n return { ok: false };\n }\n\n /** Worktree env (cwd/branch) for a phase, or undefined if it runs on the shared tree. */\n /** Bundle of orchestrator state the worktree-integration steps drive. */\n private integrationCtx(): IntegrationContext {\n return {\n graph: this.graph,\n ctx: this.ctx,\n logger: this.logger,\n worktrees: this.worktrees,\n phaseWorktrees: this.phaseWorktrees,\n phaseMergePromise: this.phaseMergePromise,\n runningPhases: this.runningPhases,\n getMergeQueue: () => this.mergeQueue,\n setMergeQueue: (queue) => {\n this.mergeQueue = queue;\n },\n emit: (event, payload) => this.emit(event, payload),\n updatePhaseStatus: (phase, status) => this.updatePhaseStatus(phase, status),\n };\n }\n\n private worktreeEnv(phase: PhaseNode): { cwd?: string | undefined; branch?: string | undefined } | undefined {\n return worktreeEnv(this.integrationCtx(), phase);\n }\n\n private async failPhaseAfterTasks(phase: PhaseNode, error: string): Promise<void> {\n await failPhaseAfterTasks(this.integrationCtx(), phase, error);\n }\n\n /** Trim long verifier output so it fits cleanly in an event/error message. */\n private truncate(text: string, max = 500): string {\n return truncate(text, max);\n }\n\n // \u2500\u2500\u2500 Worktree integration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async commitAndEnqueueMerge(phase: PhaseNode): Promise<void> {\n await commitAndEnqueueMerge(this.integrationCtx(), phase);\n }\n /** A failed phase keeps its worktree on disk for inspection (no merge). */\n private async keepWorktreeForReview(phase: PhaseNode): Promise<void> {\n await keepWorktreeForReview(this.integrationCtx(), phase);\n }\n\n private async executePhaseTasks(phase: PhaseNode): Promise<void> {\n const pendingTasks = this.getExecutableTasks(phase);\n\n while (pendingTasks.length > 0 && !this.stopped) {\n const batch = pendingTasks.splice(0, this.opts.maxConcurrentTasks);\n\n const results = await Promise.allSettled(\n batch.map((task) => this.executeSingleTask(task, phase)),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const task = batch[i];\n if (!result || !task) continue;\n\n if (result.status === 'fulfilled') {\n this.markTaskCompleted(phase, task);\n } else {\n this.markTaskFailed(phase, task, result.reason);\n }\n }\n\n const newReady = this.getExecutableTasks(phase);\n pendingTasks.length = 0;\n pendingTasks.push(...newReady);\n }\n }\n\n private async executeSingleTask(task: TaskNode, phase: PhaseNode): Promise<unknown> {\n const tracker = this.getTrackerForPhase(phase);\n tracker.updateNodeStatus(task.id, 'in_progress');\n // Signal the start so boards can move the card to \"in progress\" and show the\n // worker. `executeTask` may assign/refine the agent right after (taskAssigned).\n this.emit('phase.taskStarted', {\n phaseId: phase.id,\n taskId: task.id,\n taskTitle: task.title,\n agentName: task.assignee,\n });\n const handle = this.phaseWorktrees.get(phase.id);\n const taskPromise = this.ctx.executeTask(task, phase.id, {\n cwd: handle?.dir,\n branch: handle?.branch,\n });\n // Apply per-task timeout when configured (taskTimeoutMs > 0).\n if (this.opts.taskTimeoutMs > 0) {\n const timeoutMs = this.opts.taskTimeoutMs;\n const timedOut = Symbol('timed_out');\n const result = await Promise.race([\n taskPromise,\n new Promise<typeof timedOut>((resolve) => {\n const timer = setTimeout(() => resolve(timedOut), timeoutMs);\n // Let the timer be freed if the task finishes first.\n taskPromise.then(() => clearTimeout(timer)).catch(() => clearTimeout(timer));\n }),\n ]);\n if (result === timedOut) {\n this.emit('phase.taskTimedOut', {\n phaseId: phase.id,\n taskId: task.id,\n taskTitle: task.title,\n timeoutMs,\n });\n throw new Error(\n `Task \"${task.title}\" (${task.id}) exceeded timeout of ${timeoutMs} ms`,\n );\n }\n return result;\n }\n return taskPromise;\n }\n\n private markTaskCompleted(phase: PhaseNode, task: TaskNode): void {\n const tracker = this.getTrackerForPhase(phase);\n tracker.updateNodeStatus(task.id, 'completed');\n this.emit('phase.taskCompleted', {\n phaseId: phase.id,\n taskId: task.id,\n taskTitle: task.title,\n });\n }\n\n private markTaskFailed(phase: PhaseNode, task: TaskNode, error: unknown): void {\n const tracker = this.getTrackerForPhase(phase);\n const taskKey = `${phase.id}:${task.id}`;\n const currentRetries = this.taskRetryCounts.get(taskKey) ?? 0;\n\n if (currentRetries < this.opts.maxRetries) {\n this.taskRetryCounts.set(taskKey, currentRetries + 1);\n tracker.updateNodeStatus(\n task.id,\n 'pending',\n `Retry ${currentRetries + 1}/${this.opts.maxRetries}`,\n );\n this.emit('phase.taskRetrying', {\n phaseId: phase.id,\n taskId: task.id,\n taskTitle: task.title,\n attempt: currentRetries + 1,\n maxRetries: this.opts.maxRetries,\n });\n } else {\n tracker.updateNodeStatus(\n task.id,\n 'failed',\n error instanceof Error ? error.message : String(error),\n );\n this.emit('phase.taskFailed', {\n phaseId: phase.id,\n taskId: task.id,\n taskTitle: task.title,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // \u2500\u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private getReadyPhases(): PhaseNode[] {\n return getReadyPhases(this.graph);\n }\n\n private getActivePhases(): PhaseNode[] {\n return getActivePhases(this.graph);\n }\n\n private getExecutableTasks(phase: PhaseNode): TaskNode[] {\n return getExecutableTasks((p) => this.getTrackerForPhase(p), phase);\n }\n\n private getTrackerForPhase(phase: PhaseNode): TaskTracker {\n const cached = this.trackerCache.get(phase.id);\n if (cached) return cached;\n\n const tracker = new TaskTracker({ store: new DefaultTaskStore() });\n tracker.setGraph(phase.taskGraph);\n this.trackerCache.set(phase.id, tracker);\n return tracker;\n }\n\n private getFailedTaskCount(phase: PhaseNode): number {\n return getFailedTaskCount((p) => this.getTrackerForPhase(p), phase);\n }\n\n private getCompletedTaskCount(phase: PhaseNode): number {\n return getCompletedTaskCount((p) => this.getTrackerForPhase(p), phase);\n }\n\n private updatePhaseStatus(phase: PhaseNode, status: PhaseStatus): void {\n const from = phase.status;\n phase.status = status;\n phase.updatedAt = Date.now();\n this.graph.updatedAt = Date.now();\n this.emit('phase.statusChange', { phaseId: phase.id, from, to: status });\n }\n\n private isComplete(): boolean {\n return isGraphComplete(this.graph);\n }\n\n private onGraphComplete(): void {\n this.graph.completedAt = Date.now();\n const durationMs = this.graph.completedAt - (this.graph.startedAt ?? this.graph.completedAt);\n this.emit('graph.completed', { graphId: this.graph.id, durationMs });\n this.stop();\n }\n\n private onGraphFailed(failedPhase: PhaseNode): void {\n this.emit('graph.failed', {\n graphId: this.graph.id,\n failedPhaseId: failedPhase.id,\n error: `Phase \"${failedPhase.name}\" failed`,\n });\n this.stop();\n }\n\n // \u2500\u2500\u2500 Progress \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getProgress(): PhaseProgress {\n return getProgress(this.graph, (p) => this.getTrackerForPhase(p));\n }\n\n getGraph(): PhaseGraph {\n return this.graph;\n }\n\n isRunning(): boolean {\n return !this.stopped && this.runningPhases.size > 0;\n }\n\n isPaused(): boolean {\n return this.paused;\n }\n\n // \u2500\u2500\u2500 Agent Assignment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n assignAgent(phaseId: string, agentId: string): void {\n const phase = this.graph.phases.get(phaseId);\n if (!phase) return;\n if (!phase.assignedAgents.includes(agentId)) {\n phase.assignedAgents.push(agentId);\n this.emit('agent.assigned', { phaseId, agentId });\n }\n }\n\n releaseAgent(phaseId: string, agentId: string): void {\n const phase = this.graph.phases.get(phaseId);\n if (!phase) return;\n phase.assignedAgents = phase.assignedAgents.filter((id) => id !== agentId);\n this.emit('agent.released', { phaseId, agentId });\n }\n\n // \u2500\u2500\u2500 Interactive board mutations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // These are driven by an interactive board (WebUI/TUI), not the autonomous\n // loop. Each mutates the live graph, emits a typed event so every surface\n // stays in sync, and bumps updatedAt so the host re-persists.\n\n /** Find the phase whose task graph currently holds `taskId`. */\n findPhaseOfTask(taskId: string): PhaseNode | undefined {\n return findPhaseOfTaskInGraph(this.graph, taskId);\n }\n\n /**\n * Move a task to another phase's task graph. Edges that referenced the task\n * are dropped (cross-phase dependencies are not modeled). No-op when the task\n * or target phase is missing, or it is already in the target phase.\n */\n moveTask(taskId: string, toPhaseId: string): boolean {\n return movePhaseTask(this.boardMutationContext(), taskId, toPhaseId);\n }\n\n /** (Re)assign a task to a specific agent (or clear with agentName/agentId omitted). */\n setTaskAssignee(taskId: string, agentId?: string, agentName?: string): boolean {\n return setPhaseTaskAssignee(this.boardMutationContext(), taskId, agentId, agentName);\n }\n\n /** Add a new task to a phase. Returns the created task id, or null if the phase is missing. */\n addTask(\n phaseId: string,\n spec: {\n title: string;\n description?: string | undefined;\n type?: TaskNode['type'] | undefined;\n priority?: TaskNode['priority'] | undefined;\n },\n ): string | null {\n return addPhaseTask(this.boardMutationContext(), phaseId, spec);\n }\n\n /**\n * Requeue a task to `pending` (clearing its retry counter) and nudge a\n * terminal/paused phase back to `ready` so the loop re-runs it. Backs both the\n * board's \"retry\" and \"start\" affordances.\n */\n requeueTask(taskId: string): boolean {\n return requeuePhaseTask(this.boardMutationContext(), taskId);\n }\n\n private boardMutationContext() {\n return {\n graph: this.graph,\n trackerCache: this.trackerCache,\n taskRetryCounts: this.taskRetryCounts,\n phaseWorktrees: this.phaseWorktrees,\n getTrackerForPhase: (phase: PhaseNode) => this.getTrackerForPhase(phase),\n updatePhaseStatus: (phase: PhaseNode, status: PhaseStatus) =>\n this.updatePhaseStatus(phase, status),\n emit: (event: string, payload: unknown) =>\n this.emit(event as PhaseEventName, payload as PhaseEventMap[PhaseEventName]),\n };\n }\n\n // \u2500\u2500\u2500 Events \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private emit<K extends PhaseEventName>(event: K, payload: PhaseEventMap[K]): void {\n (this.events.emit as (event: string, payload: unknown) => void)(event, payload);\n }\n\n private async waitWhilePaused(): Promise<void> {\n while (this.paused && !this.stopped) {\n await this.delay(100);\n }\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n", "import { PhaseGraphBuilder } from './phase-graph-builder.js';\nimport { PhaseOrchestrator } from './phase-orchestrator.js';\nimport type {\n GoalOptions,\n PhaseExecutionContext,\n PhaseGraph,\n PhaseNode,\n PhaseProgress,\n PhaseTemplate,\n} from './types.js';\n\nexport interface GoalRunnerOptions extends GoalOptions {\n /** Project title. */\n title: string;\n description?: string | undefined;\n /** Phase templates. */\n phases: PhaseTemplate[];\n /** Function that executes a task. */\n executeTask: PhaseExecutionContext['executeTask'];\n /** Optional verification gate. */\n verifyPhase?: PhaseExecutionContext['verifyPhase'] | undefined;\n /** Optional repair pass after verification failure. */\n repairPhase?: PhaseExecutionContext['repairPhase'] | undefined;\n /** Optional resolver for worktree merge conflicts. */\n resolveConflict?: PhaseExecutionContext['resolveConflict'] | undefined;\n /** Optional Brain arbiter. */\n brain?: PhaseExecutionContext['brain'] | undefined;\n /** Called when a phase completes. */\n onPhaseComplete?: ((phase: PhaseNode) => void) | undefined;\n /** Called when a phase fails. */\n onPhaseFail?: (phase: PhaseNode, error: Error) => void;\n /** Called on every orchestrator tick. */\n onTick?: (ctx: { activePhases: PhaseNode[]; readyPhases: PhaseNode[] }) => void;\n /** Called when progress changes. */\n onProgress?: ((progress: PhaseProgress) => void) | undefined;\n /** Safety net that stops a phase graph if cleanup is bypassed. Default: 24h. */\n maxRunDurationMs?: number | undefined;\n /** Called when the graph completes. */\n onComplete?: ((graph: PhaseGraph) => void) | undefined;\n /** Called when the graph fails. */\n onFail?: (graph: PhaseGraph, failedPhase: PhaseNode, error: Error) => void;\n}\n\n/**\n * GoalRunner - high-level API for managing the whole autonomous phase flow from one entry point.\n *\n * Usage:\n * const runner = new GoalRunner({\n * title: 'Auth Refactor',\n * phases: [...],\n * executeTask: async (task, phaseId) => { ... },\n * onProgress: (p) => console.log(`${p.percentComplete}% done`),\n * });\n * await runner.start();\n */\nexport class GoalRunner {\n private graph: PhaseGraph | null = null;\n private orchestrator: PhaseOrchestrator | null = null;\n private opts: GoalRunnerOptions;\n private progressInterval: ReturnType<typeof setInterval> | null = null;\n private maxRunTimer: ReturnType<typeof setTimeout> | null = null;\n\n private readonly graphCompletedHandler = (payload: unknown) => {\n const p = payload as { graphId: string; durationMs: number };\n if (this.graph && p.graphId === this.graph.id) {\n this.opts.onComplete?.(this.graph);\n this.cleanup();\n }\n };\n\n private readonly graphFailedHandler = (payload: unknown) => {\n const p = payload as { graphId: string; failedPhaseId: string; error: string };\n if (this.graph && p.graphId === this.graph.id) {\n const failedPhase = this.graph.phases.get(p.failedPhaseId);\n if (failedPhase) {\n this.opts.onFail?.(this.graph, failedPhase, new Error(p.error));\n }\n // Only cleanup on failure when stopOnFailure is explicitly true.\n // When false (default), the orchestrator continues with remaining phases.\n if (this.opts.stopOnFailure) {\n this.cleanup();\n }\n }\n };\n\n /** Stores the unsubscribe function returned by EventBus.on() */\n private unsubscribeCompleted: (() => void) | null = null;\n private unsubscribeFailed: (() => void) | null = null;\n\n constructor(opts: GoalRunnerOptions) {\n this.opts = opts;\n }\n\n async start(): Promise<PhaseGraph> {\n // Create the phase graph.\n const builder = new PhaseGraphBuilder({\n title: this.opts.title,\n description: this.opts.description,\n phases: this.opts.phases,\n autonomous: this.opts.autonomous,\n stopOnFailure: this.opts.stopOnFailure,\n });\n\n this.graph = await builder.build();\n\n // Execution context\n const ctx: PhaseExecutionContext = {\n executeTask: this.opts.executeTask,\n brain: this.opts.brain,\n onPhaseComplete: (phase) => {\n this.opts.onPhaseComplete?.(phase);\n },\n onPhaseFail: (phase, error) => {\n this.opts.onPhaseFail?.(phase, error);\n },\n onTick: (tickCtx) => {\n this.opts.onTick?.(tickCtx);\n },\n };\n if (this.opts.verifyPhase !== undefined) ctx.verifyPhase = this.opts.verifyPhase;\n if (this.opts.repairPhase !== undefined) ctx.repairPhase = this.opts.repairPhase;\n if (this.opts.resolveConflict !== undefined) ctx.resolveConflict = this.opts.resolveConflict;\n\n // Create and start the orchestrator.\n this.orchestrator = new PhaseOrchestrator({\n graph: this.graph,\n ctx,\n maxConcurrentPhases: this.opts.maxConcurrentPhases,\n maxConcurrentTasks: this.opts.maxConcurrentTasks,\n maxRetries: this.opts.maxRetries,\n maxVerifyAttempts: this.opts.maxVerifyAttempts,\n autonomous: this.opts.autonomous,\n phaseDelayMs: this.opts.phaseDelayMs,\n stopOnFailure: this.opts.stopOnFailure,\n events: this.opts.events,\n worktrees: this.opts.worktrees,\n });\n\n // Register event listeners using the untyped surface to handle custom events.\n // Call through the bus as the receiver \u2014 detaching the method (`const f =\n // events.on`) loses `this`, and EventBus.on is a plain prototype method, so\n // the detached call throws on `this.listeners`. The arrow wrapper keeps it\n // bound to the bus.\n if (this.opts.events) {\n const bus = this.opts.events as unknown as {\n on(event: string, handler: (payload: unknown) => void): () => void;\n };\n const onUntyped = (event: string, handler: (payload: unknown) => void): (() => void) =>\n bus.on(event, handler);\n // Store the unsubscribe functions for proper cleanup\n this.unsubscribeCompleted = onUntyped('graph.completed', this.graphCompletedHandler);\n this.unsubscribeFailed = onUntyped('graph.failed', this.graphFailedHandler);\n }\n\n await this.orchestrator.start();\n\n // Arm the max-run-duration timeout only AFTER orchestrator.start() settles,\n // so the timer cannot fire mid-start and race with this.orchestrator.stop().\n this.maxRunTimer = setTimeout(\n () => {\n this.opts.onProgress?.({\n totalPhases: 0, pending: 0, ready: 0, running: 0, paused: 0,\n completed: 0, failed: 0, skipped: 0, percentComplete: 0,\n totalTasks: 0, completedTasks: 0, failedTasks: 0,\n estimatedHours: 0, actualHours: 0,\n });\n this.stop();\n },\n this.opts.maxRunDurationMs ?? 7 * 24 * 60 * 60_000,\n );\n if (this.opts.maxRunDurationMs !== undefined && this.opts.maxRunDurationMs <= 0) {\n clearTimeout(this.maxRunTimer);\n this.maxRunTimer = null;\n }\n this.maxRunTimer?.unref?.();\n\n // Progress reporting \u2014 start after orchestrator is running.\n if (this.opts.onProgress) {\n this.progressInterval = setInterval(() => {\n const progress = this.orchestrator?.getProgress();\n if (progress) this.opts.onProgress?.(progress);\n }, 2000);\n }\n\n return this.graph;\n }\n\n pause(): void {\n this.orchestrator?.pause();\n }\n\n resume(): void {\n this.orchestrator?.resume();\n }\n\n stop(): void {\n this.orchestrator?.stop();\n this.cleanup();\n }\n\n getProgress(): PhaseProgress | null {\n return this.orchestrator?.getProgress() ?? null;\n }\n\n getGraph(): PhaseGraph | null {\n return this.graph;\n }\n\n isRunning(): boolean {\n return this.orchestrator?.isRunning() ?? false;\n }\n\n isPaused(): boolean {\n return this.orchestrator?.isPaused() ?? false;\n }\n\n assignAgent(phaseId: string, agentId: string): void {\n this.orchestrator?.assignAgent(phaseId, agentId);\n }\n\n releaseAgent(phaseId: string, agentId: string): void {\n this.orchestrator?.releaseAgent(phaseId, agentId);\n }\n\n private cleanup(): void {\n if (this.progressInterval) {\n clearInterval(this.progressInterval);\n this.progressInterval = null;\n }\n if (this.maxRunTimer) {\n clearTimeout(this.maxRunTimer);\n this.maxRunTimer = null;\n }\n // Use the unsubscribe functions returned by EventBus.on() instead of .off()\n this.unsubscribeCompleted?.();\n this.unsubscribeCompleted = null;\n this.unsubscribeFailed?.();\n this.unsubscribeFailed = null;\n }\n}\n\n/**\n * Quick-start helper: create an GoalRunner from an existing TaskGraph.\n */\nexport async function createGoalRunnerFromTaskGraph(\n taskGraph: import('../types/task-graph.js').TaskGraph,\n options: Omit<GoalRunnerOptions, 'phases' | 'title'> & {\n title?: string | undefined;\n tasksPerPhase?: number | undefined;\n },\n): Promise<GoalRunner> {\n const graph = await PhaseGraphBuilder.fromTaskGraph(taskGraph, {\n title: options.title ?? taskGraph.title,\n tasksPerPhase: options.tasksPerPhase,\n });\n\n // Extract phase templates from the PhaseGraph.\n const phases: PhaseTemplate[] = Array.from(graph.phases.values()).map((p) => ({\n name: p.name,\n description: p.description,\n priority: p.priority,\n estimateHours: p.estimateHours,\n parallelizable: p.parallelizable,\n }));\n\n return new GoalRunner({\n ...options,\n title: options.title ?? taskGraph.title,\n phases,\n });\n}\n", "import { readFileSync, statSync } from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Cache of resolved instruction text, keyed by the relative path. Bundled\n * instruction files are immutable for the process lifetime, so re-reading them\n * on every call (some callers do so per LLM request) is wasted disk I/O.\n */\nconst textCache = new Map<string, string>();\n\n/** Resolved once \u2014 the candidate roots only depend on this module's location. */\nlet rootCandidates: string[] | undefined;\n\nexport function readBundledInstructionText(relativePath: string): string {\n const cached = textCache.get(relativePath);\n if (cached !== undefined) return cached;\n\n let resolved = '';\n for (const root of instructionRootCandidates()) {\n try {\n resolved = readFileSync(path.join(root, relativePath), 'utf8').trimEnd();\n break;\n } catch {\n // try next candidate\n }\n }\n textCache.set(relativePath, resolved);\n return resolved;\n}\n\nexport function renderInstructionTemplate(\n template: string,\n values: Record<string, string>,\n): string {\n return template.replace(/\\{\\{\\s*([a-zA-Z0-9_.-]+)\\s*\\}\\}/g, (match, key: string) =>\n Object.hasOwn(values, key) ? (values[key] ?? '') : match,\n );\n}\n\nfunction instructionRootCandidates(): string[] {\n if (rootCandidates !== undefined) return rootCandidates;\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidates = [\n path.resolve(here, '../../instructions'),\n path.resolve(here, '../instructions'),\n path.resolve(here, 'instructions'),\n ];\n rootCandidates = candidates.sort((a, b) => Number(!isDirectory(a)) - Number(!isDirectory(b)));\n return rootCandidates;\n}\n\nfunction isDirectory(candidate: string): boolean {\n try {\n return statSync(candidate).isDirectory();\n } catch {\n return false;\n }\n}\n", "/**\n * GoalPlanner - converts a goal into phases using a real LLM call,\n * producing a large task list with todos under each phase.\n *\n * Similar to SDD's spec-to-task flow, but different: the output is directly\n * `PhaseTemplate[]`; each phase carries `taskTemplates`, so\n * `PhaseGraphBuilder` produces a populated `PhaseGraph` and `PhaseOrchestrator`\n * runs each task through a real agent execution.\n *\n * The planner is not tied to a specific LLM: callers provide a `runOnce(prompt)` function\n * (a subagent run in the CLI, or a deterministic stub in tests).\n */\n\nimport type { TaskPriority, TaskType } from '../types/task-graph.js';\nimport {\n readBundledInstructionText,\n renderInstructionTemplate,\n} from '../utils/instruction-file.js';\nimport type { PhaseNode, PhaseTemplate } from './types.js';\n\n/** Single todo template, the element type of PhaseTemplate.taskTemplates. */\ntype PhaseTaskTemplate = NonNullable<PhaseTemplate['taskTemplates']>[number];\n\nexport interface GoalPlannerOptions {\n /**\n * One-shot LLM call: receives a prompt and returns the model text output.\n * In the CLI this wraps subagent.run; in tests it can be a deterministic stub.\n */\n runOnce: (prompt: string) => Promise<string>;\n /** Goal or project title. */\n goal: string;\n /** Optional project context such as package.json or directory structure. */\n projectContext?: string | undefined;\n /** Requested minimum phase count. Defaults to 3. */\n minPhases?: number | undefined;\n /** Requested maximum phase count. Defaults to 8. */\n maxPhases?: number | undefined;\n /** Target todo count per phase. Defaults to 6. */\n todosPerPhase?: number | undefined;\n /**\n * Maximum total tasks across all phases. When set, plans exceeding\n * this limit will have `budgetExceeded: true` and `warnings` will\n * describe the overage. Defaults to 0 (no limit).\n */\n maxTotalTasks?: number | undefined;\n}\n\nexport interface GoalPlanResult {\n /** Phase templates passed to PhaseGraphBuilder. */\n phases: PhaseTemplate[];\n /** Raw model output for debugging and logs. */\n raw: string;\n /** True when JSON could not be parsed; `phases` is empty in that case. */\n parseFailed: boolean;\n /** Validation warnings collected during coercion (e.g. invalid priority defaults). */\n warnings: string[];\n /**\n * Rough cost estimate (in tokens) for executing this plan.\n * Based on estimated task count \u00D7 average per-task LLM round-trip.\n */\n estimatedCostTokens?: number | undefined;\n /** True when the plan exceeds `maxTotalTasks` budget. */\n budgetExceeded?: boolean | undefined;\n}\n\nconst VALID_TASK_TYPES: ReadonlySet<TaskType> = new Set([\n 'feature',\n 'bugfix',\n 'refactor',\n 'docs',\n 'test',\n 'chore',\n]);\nconst VALID_PRIORITIES: ReadonlySet<TaskPriority> = new Set([\n 'critical',\n 'high',\n 'medium',\n 'low',\n]);\n\n/**\n * GoalPlanner drives the model through `plan()` and produces `PhaseTemplate[]`.\n */\nexport class GoalPlanner {\n constructor(private readonly opts: GoalPlannerOptions) {}\n\n /** Convert the goal into a phase-and-todo plan. */\n async plan(): Promise<GoalPlanResult> {\n const prompt = this.buildPrompt();\n const raw = await this.opts.runOnce(prompt);\n const { phases, warnings } = this.parse(raw);\n // Rough cost estimate: each task runs ~5 LLM round-trips at ~2k tokens each.\n const totalTasks = phases.reduce((s, p) => s + (p.taskTemplates?.length ?? 0), 0);\n const estimatedCostTokens = totalTasks > 0 ? totalTasks * 5 * 2000 : undefined;\n // Budget check: reject plans that exceed maxTotalTasks.\n const maxTotal = this.opts.maxTotalTasks ?? 0;\n let budgetExceeded = false;\n if (maxTotal > 0 && totalTasks > maxTotal) {\n warnings.push(\n `Plan has ${totalTasks} total tasks, exceeding the limit of ${maxTotal}. ` +\n `Consider narrowing the scope or increasing the limit.`,\n );\n budgetExceeded = true;\n }\n return { phases, raw, parseFailed: phases.length === 0, warnings, estimatedCostTokens, budgetExceeded };\n }\n\n /** Instruction prompt for the plan the model should produce. */\n buildPrompt(): string {\n const minP = this.opts.minPhases ?? 3;\n const maxP = this.opts.maxPhases ?? 8;\n const todos = this.opts.todosPerPhase ?? 6;\n const ctx = this.opts.projectContext?.trim();\n\n return renderInstructionTemplate(readBundledInstructionText('goal/phase-planner.md'), {\n minPhases: String(minP),\n maxPhases: String(maxP),\n todosPerPhase: String(todos),\n goal: this.opts.goal,\n projectContext: ctx ? `\\nPROJECT CONTEXT:\\n${ctx}\\n` : '',\n });\n }\n\n /** Extract JSON from raw output, validate it, and convert it to PhaseTemplate[].\n * Returns `{ phases, warnings }` where warnings describe coerced defaults. */\n parse(raw: string): { phases: PhaseTemplate[]; warnings: string[] } {\n const json = extractJSONArray(raw);\n if (!json) return { phases: [], warnings: ['No JSON array found in model output'] };\n let data: unknown;\n try {\n data = JSON.parse(json);\n } catch {\n return { phases: [], warnings: ['Failed to parse JSON from model output'] };\n }\n if (!Array.isArray(data)) return { phases: [], warnings: ['Model output is not a JSON array'] };\n const warnings: string[] = [];\n const phases: PhaseTemplate[] = [];\n for (const entry of data) {\n const result = this.coercePhase(entry);\n if (result) {\n phases.push(result.phase);\n warnings.push(...result.warnings);\n }\n }\n return { phases, warnings };\n }\n\n private coercePhase(entry: unknown): { phase: PhaseTemplate; warnings: string[] } | null {\n if (!entry || typeof entry !== 'object') return null;\n const e = entry as Record<string, unknown>;\n const name = typeof e.name === 'string' ? e.name.trim() : '';\n if (!name) return null;\n const w: string[] = [];\n const rawTasks = Array.isArray(e.tasks)\n ? e.tasks\n : Array.isArray(e.taskTemplates)\n ? e.taskTemplates\n : [];\n\n const taskTemplates: PhaseTaskTemplate[] = [];\n for (const t of rawTasks) {\n const result = this.coerceTask(t);\n if (result) {\n taskTemplates.push(result.task);\n w.push(...result.warnings);\n }\n }\n\n const coercedPriority = coercePriority(e.priority);\n if (typeof e.priority === 'string' && coercedPriority !== e.priority) {\n w.push('Phase \"' + name + '\": invalid priority \"' + String(e.priority) + '\", defaulting to \"' + coercedPriority + '\"');\n }\n return {\n phase: {\n name,\n description: typeof e.description === 'string' ? e.description : '',\n priority: coercedPriority as PhaseNode['priority'],\n estimateHours: coerceHours(e.estimateHours, 4),\n parallelizable: e.parallelizable === true,\n taskTemplates,\n },\n warnings: w,\n };\n }\n\n private coerceTask(t: unknown): { task: PhaseTaskTemplate; warnings: string[] } | null {\n if (!t || typeof t !== 'object') return null;\n const o = t as Record<string, unknown>;\n const title = typeof o.title === 'string' ? o.title.trim() : '';\n if (!title) return null;\n\n const w: string[] = [];\n let type: TaskType = 'feature';\n if (typeof o.type === 'string') {\n if (VALID_TASK_TYPES.has(o.type as TaskType)) {\n type = o.type as TaskType;\n } else {\n w.push('Task \"' + title + '\": invalid type \"' + o.type + '\", defaulting to \"feature\"');\n }\n }\n const coercedPriority = coercePriority(o.priority);\n if (typeof o.priority === 'string' && coercedPriority !== o.priority) {\n w.push('Task \"' + title + '\": invalid priority \"' + String(o.priority) + '\", defaulting to \"' + coercedPriority + '\"');\n }\n\n return {\n task: {\n title,\n description: typeof o.description === 'string' ? o.description : '',\n type,\n priority: coercedPriority,\n estimateHours: coerceHours(o.estimateHours, 2),\n tags: Array.isArray(o.tags) ? o.tags.map(String) : [],\n },\n warnings: w,\n };\n }\n}\n\n// \u2500\u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction coercePriority(value: unknown): TaskPriority {\n return VALID_PRIORITIES.has(value as TaskPriority) ? (value as TaskPriority) : 'medium';\n}\n\nfunction coerceHours(value: unknown, fallback: number): number {\n const n = Number(value);\n return Number.isFinite(n) && n > 0 ? n : fallback;\n}\n\n/**\n * Extract the first JSON array from text. Tries, in order:\n * 1. The first [ ... ] inside a ```json ... ``` or bare ``` code block\n * 2. The first balanced [ ... ] block in the text, aware of strings and escapes\n */\nexport function extractJSONArray(text: string): string | null {\n // 1) Fenced code block\n const fence = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n const candidates: string[] = [];\n if (fence?.[1]) candidates.push(fence[1]);\n candidates.push(text);\n\n for (const candidate of candidates) {\n const balanced = firstBalancedArray(candidate);\n if (balanced) return balanced;\n }\n return null;\n}\n\n/** Return the first balanced `[ ... ]` block, aware of strings and escapes. */\nfunction firstBalancedArray(text: string): string | null {\n const start = text.indexOf('[');\n if (start === -1) return null;\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < text.length; i++) {\n const ch = text[i] ?? '';\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '[') {\n depth++;\n } else if (ch === ']') {\n depth--;\n if (depth === 0) {\n return text.slice(start, i + 1);\n }\n }\n }\n return null;\n}\n", "/**\n * GoalAssessor \u2014 analyzes a goal prompt for duration realism.\n *\n * Takes a goal description, runs it through an LLM with a structured\n * prompt, and returns an assessment: whether any claimed duration is\n * realistic, what concerns exist, and a suggested alternate duration.\n *\n * Uses the same `runOnce(prompt)` pattern as GoalPlanner so it works\n * with any LLM provider (subagent in CLI, deterministic stub in tests).\n */\n\nimport {\n readBundledInstructionText,\n renderInstructionTemplate,\n} from '../utils/instruction-file.js';\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface GoalAssessResult {\n /** True when the goal's duration claim is realistic, or when none is claimed. */\n realistic: boolean;\n /** The exact duration text extracted from the goal, or null. */\n durationClaimed: string | null;\n /** Human-readable explanation of the realism assessment. */\n explanation: string;\n /** Suggested more-reasonable duration when the claim is unrealistic, else null. */\n recommendedDuration: string | null;\n /** 1\u20133 concrete risk/concern items. */\n concerns: string[];\n /** Raw model output for debugging. */\n raw: string;\n /** True when the JSON response could not be parsed. */\n parseFailed: boolean;\n /** Parser warning, if any. */\n parseError?: string | undefined;\n}\n\nexport interface GoalAssessorOptions {\n /** One-shot LLM call: receives a prompt and returns model text. */\n runOnce: (prompt: string) => Promise<string>;\n /** Goal or project description to assess. */\n goal: string;\n}\n\n// \u2500\u2500 Assessor \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class GoalAssessor {\n constructor(private readonly opts: GoalAssessorOptions) {}\n\n /** Analyze the goal and return a structured realism assessment. */\n async assess(): Promise<GoalAssessResult> {\n const prompt = this.buildPrompt();\n const raw = await this.opts.runOnce(prompt);\n return this.parse(raw);\n }\n\n /** Build the instruction prompt for the LLM. */\n buildPrompt(): string {\n return renderInstructionTemplate(\n readBundledInstructionText('goal/goal-assessor.md'),\n { goal: this.opts.goal },\n );\n }\n\n /** Extract and validate the JSON object from the raw LLM output. */\n parse(raw: string): GoalAssessResult {\n const json = extractJSONObject(raw);\n if (!json) {\n return {\n realistic: true,\n durationClaimed: null,\n explanation: '',\n recommendedDuration: null,\n concerns: [],\n raw,\n parseFailed: true,\n parseError: 'No JSON object found in model output',\n };\n }\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(json) as Record<string, unknown>;\n } catch {\n return {\n realistic: true,\n durationClaimed: null,\n explanation: '',\n recommendedDuration: null,\n concerns: [],\n raw,\n parseFailed: true,\n parseError: 'Failed to parse JSON from model output',\n };\n }\n\n return {\n realistic: data.realistic === true,\n durationClaimed: typeof data.durationClaimed === 'string' ? data.durationClaimed : null,\n explanation: typeof data.explanation === 'string' ? data.explanation : '',\n recommendedDuration:\n typeof data.recommendedDuration === 'string' ? data.recommendedDuration : null,\n concerns: Array.isArray(data.concerns)\n ? data.concerns.filter((c: unknown): c is string => typeof c === 'string')\n : [],\n raw,\n parseFailed: false,\n };\n }\n}\n\n// \u2500\u2500 Helper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Extract the first JSON object `{ ... }` from text, aware of strings and\n * escape characters. Tries fenced code blocks first, then balanced-brace\n * extraction on the raw text.\n */\nfunction extractJSONObject(text: string): string | null {\n // 1) Fenced code block\n const fence = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n const candidates: string[] = [];\n if (fence?.[1]) candidates.push(fence[1]);\n candidates.push(text);\n\n for (const candidate of candidates) {\n const balanced = firstBalancedObject(candidate);\n if (balanced) return balanced;\n }\n return null;\n}\n\n/** Return the first balanced `{ ... }` block, aware of strings and escapes. */\nfunction firstBalancedObject(text: string): string | null {\n const start = text.indexOf('{');\n if (start === -1) return null;\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < text.length; i++) {\n const ch = text[i] ?? '';\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === '\\\\') {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '{') {\n depth++;\n } else if (ch === '}') {\n depth--;\n if (depth === 0) {\n return text.slice(start, i + 1);\n }\n }\n }\n return null;\n}\n", "/**\n * Goal - types for autonomous phase-based workflows.\n *\n * A project is split into phases; each phase contains tasks.\n * Phases are dependency-aware: the next phase cannot start until all tasks\n * in the current phase complete. Parallel phases are optionally supported.\n */\n\nimport type { BrainArbiter } from '../coordination/brain.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\n\n// \u2500\u2500\u2500 Phase Status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type PhaseStatus =\n | 'pending' // Not started yet; waiting for a previous phase\n | 'ready' // Ready to start because previous phases completed\n | 'running' // Actively running\n | 'paused' // Paused by the user\n | 'completed' // All tasks finished\n | 'failed' // At least one task failed and retries are exhausted\n | 'skipped'; // Skipped\n\n// \u2500\u2500\u2500 Phase Node \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseNode {\n id: string;\n /** Phase name, e.g. \"Discovery\", \"Design\", \"Implementation\", \"Testing\". */\n name: string;\n description: string;\n status: PhaseStatus;\n /** Task graph for this phase. */\n taskGraph: TaskGraph;\n /** Previous phase IDs; this phase cannot start until they complete. */\n dependsOn: string[];\n /** Next phase IDs. */\n nextPhases: string[];\n /** Whether this phase can run in parallel before the previous phase finishes. */\n parallelizable: boolean;\n /** Phase priority. */\n priority: 'critical' | 'high' | 'medium' | 'low';\n /** Estimated duration in hours. */\n estimateHours: number;\n /** Actual duration in milliseconds. */\n actualDurationMs?: number | undefined;\n /** Start time. */\n startedAt?: number | undefined;\n /** Completion time. */\n completedAt?: number | undefined;\n /** Agents assigned to this phase. */\n assignedAgents: string[];\n /** Phase metadata. */\n metadata?: Record<string, unknown> | undefined;\n createdAt: number;\n updatedAt: number;\n}\n\n// \u2500\u2500\u2500 Phase Graph \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseGraph {\n id: string;\n /** Project title. */\n title: string;\n description: string;\n phases: Map<string, PhaseNode>;\n /** Starting phase IDs. */\n rootPhaseIds: string[];\n /** Active phase IDs with running status. */\n activePhaseIds: string[];\n /** Completed phase IDs. */\n completedPhaseIds: string[];\n /** Failed phase IDs. */\n failedPhaseIds: string[];\n /** Whether autonomous mode is active. */\n autonomous: boolean;\n /** Stop when all phases complete. */\n stopOnComplete: boolean;\n /** Split into separate kanban boards per phase. */\n multiBoard?: boolean | undefined;\n /** Run typecheck/lint verification after each task. */\n verifyTasks?: boolean | undefined;\n /** Enable chimera auto-review for this run. */\n chimeraReview?: boolean | undefined;\n createdAt: number;\n updatedAt: number;\n startedAt?: number | undefined;\n completedAt?: number | undefined;\n}\n\n// \u2500\u2500\u2500 Phase Progress \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseProgress {\n totalPhases: number;\n pending: number;\n ready: number;\n running: number;\n paused: number;\n completed: number;\n failed: number;\n skipped: number;\n percentComplete: number;\n totalTasks: number;\n completedTasks: number;\n failedTasks: number;\n estimatedHours: number;\n actualHours: number;\n}\n\n// \u2500\u2500\u2500 Phase Event Map \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseEventMap {\n 'phase.statusChange': { phaseId: string; from: PhaseStatus; to: PhaseStatus };\n 'phase.started': { phaseId: string; name: string };\n 'phase.completed': { phaseId: string; name: string; durationMs: number };\n 'phase.failed': { phaseId: string; name: string; error?: string | undefined };\n /** A task began executing \u2014 carries the worker agent so boards can show who is on it. */\n 'phase.taskStarted': {\n phaseId: string;\n taskId: string;\n taskTitle: string;\n agentId?: string | undefined;\n agentName?: string | undefined;\n };\n 'phase.taskCompleted': { phaseId: string; taskId: string; taskTitle: string };\n 'phase.taskFailed': { phaseId: string; taskId: string; taskTitle: string; error: string };\n 'phase.taskRetrying': {\n phaseId: string;\n taskId: string;\n taskTitle: string;\n attempt: number;\n maxRetries: number;\n };\n /** A task timed out \u2014 exceeded `taskTimeoutMs`. */\n 'phase.taskTimedOut': {\n phaseId: string;\n taskId: string;\n taskTitle: string;\n timeoutMs: number;\n };\n 'phase.allTasksDone': { phaseId: string; completed: number; failed: number };\n 'phase.verifying': { phaseId: string; name: string; attempt: number };\n 'phase.verifyFailed': { phaseId: string; name: string; attempt: number; error?: string | undefined };\n 'phase.repairing': { phaseId: string; name: string; attempt: number };\n 'phase.conflictResolving': { phaseId: string; name: string; files: string[] };\n 'phase.conflictResolved': { phaseId: string; name: string };\n 'graph.completed': { graphId: string; durationMs: number };\n 'graph.failed': { graphId: string; failedPhaseId: string; error: string };\n 'autonomous.tick': { activePhases: string[]; queuedPhases: string[] };\n 'agent.assigned': { phaseId: string; agentId: string };\n 'agent.released': { phaseId: string; agentId: string };\n /** A task was moved between phases from an interactive board. */\n 'phase.taskMoved': { taskId: string; fromPhaseId: string; toPhaseId: string };\n /** A task was (re)assigned to a specific agent from an interactive board. */\n 'phase.taskAssigned': {\n phaseId: string;\n taskId: string;\n agentId?: string | undefined;\n agentName?: string | undefined;\n };\n /** A task was added to a phase from an interactive board. */\n 'phase.taskAdded': { phaseId: string; taskId: string; taskTitle: string };\n}\n\nexport type PhaseEventName = keyof PhaseEventMap;\n\n/**\n * All phase event names as a const array. Consumers (TUI, WebUI) should\n * import this rather than hardcoding string literals, so the compiler\n * catches drift when events are added or renamed.\n */\nexport const PHASE_EVENT_NAMES: readonly PhaseEventName[] = [\n 'phase.statusChange',\n 'phase.started',\n 'phase.completed',\n 'phase.failed',\n 'phase.taskStarted',\n 'phase.taskCompleted',\n 'phase.taskFailed',\n 'phase.taskRetrying',\n 'phase.taskTimedOut',\n 'phase.allTasksDone',\n 'phase.verifying',\n 'phase.verifyFailed',\n 'phase.repairing',\n 'phase.conflictResolving',\n 'phase.conflictResolved',\n 'phase.taskMoved',\n 'phase.taskAssigned',\n 'phase.taskAdded',\n 'graph.completed',\n 'graph.failed',\n 'autonomous.tick',\n 'agent.assigned',\n 'agent.released',\n];\n\n// \u2500\u2500\u2500 Phase Execution Context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseExecutionContext {\n /**\n * Execute a task through an AI agent. `env` points to the phase git\n * worktree when available, so the agent runs in an isolated working directory.\n */\n executeTask: (\n task: TaskNode,\n phaseId: string,\n env?: { cwd?: string | undefined; branch?: string | undefined },\n ) => Promise<unknown>;\n /**\n * Optional verification gate. Called after all tasks in a phase finish,\n * but before the phase is marked \"completed\" and its worktree is merged\n * back to the base branch. `env` points to the phase worktree when available;\n * verification should run in that isolated directory, such as typecheck/test.\n * If `ok:false` is returned, merge is blocked and `repairPhase` is attempted when available.\n *\n * If undefined, the gate is skipped for backward compatibility.\n */\n verifyPhase?:\n | ((\n phase: PhaseNode,\n env?: { cwd?: string | undefined; branch?: string | undefined },\n ) => Promise<{ ok: boolean; output?: string | undefined }>)\n | undefined;\n /**\n * Optional repair pass. When `verifyPhase` fails, it is called with the\n * captured error output. It should try to fix the code in the worktree\n * for example, through a repair subagent. Its return value is ignored;\n * the orchestrator reruns `verifyPhase` afterward. It is never called when `verifyPhase` is undefined.\n */\n repairPhase?:\n | ((\n phase: PhaseNode,\n failure: string,\n attempt: number,\n env?: { cwd?: string | undefined; branch?: string | undefined },\n ) => Promise<void>)\n | undefined;\n /**\n * Optional merge-conflict resolver. Called when a phase worktree conflicts\n * during squash-merge into the base branch. `info.cwd` points to the base\n * working tree where conflict markers exist; the resolver should clean those\n * markers and return `true`. On success the merge is committed; otherwise\n * the merge is aborted and the worktree is kept in `needs-review`.\n * If undefined, conflicts keep the old parked-for-review behavior.\n */\n resolveConflict?:\n | ((\n phase: PhaseNode,\n info: { conflictFiles: string[]; cwd: string },\n ) => Promise<boolean>)\n | undefined;\n /** Optional global Brain arbiter for the policy, decision, and escalation layer. */\n brain?: BrainArbiter | undefined;\n /** Called when a phase completes. */\n onPhaseComplete?: ((phase: PhaseNode) => void) | undefined;\n /** Called when a phase fails. */\n onPhaseFail?: ((phase: PhaseNode, error: Error) => void) | undefined;\n /** Called on every tick in autonomous mode. */\n onTick?: ((ctx: { activePhases: PhaseNode[]; readyPhases: PhaseNode[] }) => void) | undefined;\n}\n\n// \u2500\u2500\u2500 Goal Options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface GoalOptions {\n /** Maximum number of parallel phases. */\n maxConcurrentPhases?: number | undefined;\n /** Maximum number of parallel tasks within a phase. */\n maxConcurrentTasks?: number | undefined;\n /** Retry count for failed tasks. */\n maxRetries?: number | undefined;\n /**\n * Maximum number of repair attempts after the verification gate fails.\n * Total verification runs = maxVerifyAttempts + 1: the first run plus one\n * rerun after each repair. Defaults to 2. Has no effect without `verifyPhase`.\n */\n maxVerifyAttempts?: number | undefined;\n /** Autonomous mode: automatically advance as phases complete. */\n autonomous?: boolean | undefined;\n /** Delay between phases in milliseconds. */\n phaseDelayMs?: number | undefined;\n /** Stop when a phase fails. */\n stopOnFailure?: boolean | undefined;\n /**\n * Per-task timeout in milliseconds. A single task exceeding this\n * is marked failed and `phase.taskTimedOut` is emitted.\n * Defaults to 600_000 (10 min). Set to 0 to disable.\n */\n taskTimeoutMs?: number | undefined;\n /** Event bus */\n events?: import('../kernel/events.js').EventBus | undefined;\n /**\n * Optional git-worktree manager. When provided, each phase runs in its own\n * isolated worktree and branch, then is squash-merged back into the base\n * branch in order. Without it, behavior is unchanged and uses the shared working tree.\n */\n worktrees?: import('../worktree/worktree-manager.js').WorktreeManager | undefined;\n}\n\n// \u2500\u2500\u2500 Phase Filter / Sort \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseFilter {\n status?: PhaseStatus[] | undefined;\n priority?: PhaseNode['priority'][] | undefined;\n}\n\nexport interface PhaseSort {\n field: 'priority' | 'createdAt' | 'startedAt' | 'completedAt';\n direction: 'asc' | 'desc';\n}\n\n// \u2500\u2500\u2500 Phase Template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PhaseTemplate {\n name: string;\n description: string;\n priority: PhaseNode['priority'];\n estimateHours: number;\n parallelizable: boolean;\n /** Task templates to create automatically. */\n taskTemplates?: Array<{\n title: string;\n description: string;\n type: import('../types/task-graph.js').TaskType;\n priority: import('../types/task-graph.js').TaskPriority;\n estimateHours: number;\n tags?: string[] | undefined;\n }>;\n}\n", "import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { TaskEdge, TaskGraph, TaskNode } from '../types/task-graph.js';\nimport { atomicWrite, withFileLock } from '../utils/atomic-write.js';\nimport type { PhaseGraph, PhaseNode } from './types.js';\n\nexport interface PhaseStoreOptions {\n baseDir: string;\n /** Previous directories read and migrated into baseDir on load/list. */\n legacyBaseDirs?: string[] | undefined;\n}\n\n/** Current schema version for SerializedPhaseGraph. Increment on breaking changes. */\nconst PHASE_STORE_VERSION = 1;\n\ninterface SerializedPhaseGraph {\n /** Schema version for forward-compatibility. Missing/0 means pre-v1. */\n version: number;\n id: string;\n title: string;\n description: string;\n phases: SerializedPhaseNode[];\n rootPhaseIds: string[];\n activePhaseIds: string[];\n completedPhaseIds: string[];\n failedPhaseIds: string[];\n autonomous: boolean;\n stopOnComplete: boolean;\n createdAt: number;\n updatedAt: number;\n startedAt?: number | undefined;\n completedAt?: number | undefined;\n}\n\ninterface SerializedPhaseNode {\n id: string;\n name: string;\n description: string;\n status: PhaseNode['status'];\n taskGraph: SerializedTaskGraph;\n dependsOn: string[];\n nextPhases: string[];\n parallelizable: boolean;\n priority: PhaseNode['priority'];\n estimateHours: number;\n actualDurationMs?: number | undefined;\n startedAt?: number | undefined;\n completedAt?: number | undefined;\n assignedAgents: string[];\n metadata?: Record<string, unknown> | undefined;\n createdAt: number;\n updatedAt: number;\n}\n\ninterface SerializedTaskGraph {\n id: string;\n specId: string;\n title: string;\n nodes: SerializedTaskNode[];\n edges: TaskEdge[];\n rootNodes: string[];\n createdAt: number;\n updatedAt: number;\n}\n\ninterface SerializedTaskNode {\n id: string;\n title: string;\n description: string;\n type: TaskNode['type'];\n priority: TaskNode['priority'];\n status: TaskNode['status'];\n assignee?: string | undefined;\n estimateHours?: number | undefined;\n actualHours?: number | undefined;\n tags?: string[] | undefined;\n specRequirementId?: string | undefined;\n parentId?: string | undefined;\n children?: string[] | undefined;\n createdAt: number;\n updatedAt: number;\n startedAt?: number | undefined;\n completedAt?: number | undefined;\n metadata?: Record<string, unknown> | undefined;\n}\n\n/**\n * PhaseStore - persistence layer for saving and loading PhaseGraph objects on disk.\n */\nexport class PhaseStore {\n readonly baseDir: string;\n private readonly legacyBaseDirs: string[];\n\n constructor(opts: PhaseStoreOptions) {\n this.baseDir = opts.baseDir;\n this.legacyBaseDirs = (opts.legacyBaseDirs ?? []).filter(\n (dir) => path.resolve(dir) !== path.resolve(this.baseDir),\n );\n }\n\n async save(graph: PhaseGraph): Promise<void> {\n const filePath = this.getFilePath(graph.id);\n const serialized = this.serializeGraph(graph);\n\n await withFileLock(filePath, async () => {\n await atomicWrite(filePath, JSON.stringify(serialized, null, 2), { mode: 0o600 });\n });\n }\n\n async load(graphId: string): Promise<PhaseGraph | null> {\n const filePath = this.getFilePath(graphId);\n const current = await this.loadFromPath(filePath);\n if (current) return current;\n for (const legacyDir of this.legacyBaseDirs) {\n const legacyPath = path.join(legacyDir, `${graphId}.json`);\n const legacy = await this.loadFromPath(legacyPath);\n if (!legacy) continue;\n try {\n await this.save(legacy);\n await this.removeMigratedLegacyFile(legacyDir, legacyPath);\n } catch {\n return null;\n }\n return legacy;\n }\n return null;\n }\n\n async delete(graphId: string): Promise<void> {\n const paths = [\n this.getFilePath(graphId),\n ...this.legacyBaseDirs.map((dir) => path.join(dir, `${graphId}.json`)),\n ];\n await Promise.all(paths.map((filePath) => fsp.unlink(filePath).catch(() => undefined)));\n }\n\n async list(): Promise<Array<{ id: string; title: string; updatedAt: number; status: string }>> {\n try {\n await this.migrateLegacyGraphs();\n const entries = await fsp.readdir(this.baseDir, { withFileTypes: true });\n const graphs: Array<{ id: string; title: string; updatedAt: number; status: string }> = [];\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith('.json')) continue;\n try {\n const raw = await fsp.readFile(path.join(this.baseDir, entry.name), 'utf8');\n const serialized = JSON.parse(raw) as SerializedPhaseGraph;\n const done = serialized.completedPhaseIds.length;\n const total = serialized.phases.length;\n graphs.push({\n id: serialized.id,\n title: serialized.title,\n updatedAt: serialized.updatedAt,\n status: done === total ? 'completed' : done > 0 ? 'in_progress' : 'pending',\n });\n } catch {\n // Skip invalid files\n }\n }\n\n return graphs.sort((a, b) => b.updatedAt - a.updatedAt);\n } catch {\n return [];\n }\n }\n\n private getFilePath(graphId: string): string {\n return path.join(this.baseDir, `${graphId}.json`);\n }\n\n private async loadFromPath(filePath: string): Promise<PhaseGraph | null> {\n try {\n const raw = await fsp.readFile(filePath, 'utf8');\n const serialized = JSON.parse(raw) as SerializedPhaseGraph;\n return this.deserializeGraph(serialized);\n } catch {\n return null;\n }\n }\n\n private async migrateLegacyGraphs(): Promise<void> {\n for (const legacyDir of this.legacyBaseDirs) {\n const entries = await fsp.readdir(legacyDir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith('.json')) continue;\n const legacyPath = path.join(legacyDir, entry.name);\n const currentPath = this.getFilePath(path.basename(entry.name, '.json'));\n if (await this.pathExists(currentPath)) {\n await this.removeMigratedLegacyFile(legacyDir, legacyPath);\n continue;\n }\n const graph = await this.loadFromPath(legacyPath);\n if (!graph) continue;\n await this.save(graph);\n await this.removeMigratedLegacyFile(legacyDir, legacyPath);\n }\n }\n }\n\n private async pathExists(filePath: string): Promise<boolean> {\n try {\n await fsp.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n private async removeMigratedLegacyFile(legacyDir: string, legacyPath: string): Promise<void> {\n await fsp.unlink(legacyPath).catch(() => undefined);\n await fsp.rmdir(legacyDir).catch(() => undefined);\n }\n\n private serializeGraph(graph: PhaseGraph): SerializedPhaseGraph {\n return {\n version: PHASE_STORE_VERSION,\n id: graph.id,\n title: graph.title,\n description: graph.description,\n phases: Array.from(graph.phases.values()).map((p) => this.serializePhase(p)),\n rootPhaseIds: graph.rootPhaseIds,\n activePhaseIds: graph.activePhaseIds,\n completedPhaseIds: graph.completedPhaseIds,\n failedPhaseIds: graph.failedPhaseIds,\n autonomous: graph.autonomous,\n stopOnComplete: graph.stopOnComplete,\n createdAt: graph.createdAt,\n updatedAt: graph.updatedAt,\n startedAt: graph.startedAt,\n completedAt: graph.completedAt,\n };\n }\n\n private serializePhase(phase: PhaseNode): SerializedPhaseNode {\n return {\n id: phase.id,\n name: phase.name,\n description: phase.description,\n status: phase.status,\n taskGraph: this.serializeTaskGraph(phase.taskGraph),\n dependsOn: phase.dependsOn,\n nextPhases: phase.nextPhases,\n parallelizable: phase.parallelizable,\n priority: phase.priority,\n estimateHours: phase.estimateHours,\n actualDurationMs: phase.actualDurationMs,\n startedAt: phase.startedAt,\n completedAt: phase.completedAt,\n assignedAgents: phase.assignedAgents,\n metadata: phase.metadata,\n createdAt: phase.createdAt,\n updatedAt: phase.updatedAt,\n };\n }\n\n private serializeTaskGraph(graph: TaskGraph): SerializedTaskGraph {\n return {\n id: graph.id,\n specId: graph.specId,\n title: graph.title,\n nodes: Array.from(graph.nodes.values()).map((n) => this.serializeTaskNode(n)),\n edges: graph.edges,\n rootNodes: graph.rootNodes,\n createdAt: graph.createdAt,\n updatedAt: graph.updatedAt,\n };\n }\n\n private serializeTaskNode(node: TaskNode): SerializedTaskNode {\n return { ...node };\n }\n\n private deserializeGraph(serialized: SerializedPhaseGraph): PhaseGraph {\n // Validate schema version for forward-compatibility.\n const fileVersion = serialized.version ?? 0;\n if (fileVersion > PHASE_STORE_VERSION) {\n throw new Error(\n `Cannot load phase graph: file version ${fileVersion} is newer than ` +\n `supported version ${PHASE_STORE_VERSION}. Upgrade WrongStack to load this file.`,\n );\n }\n // Future: add per-version migration logic here when fileVersion < PHASE_STORE_VERSION.\n const phases = new Map<string, PhaseNode>();\n for (const sp of serialized.phases) {\n phases.set(sp.id, this.deserializePhase(sp));\n }\n\n return {\n id: serialized.id,\n title: serialized.title,\n description: serialized.description,\n phases,\n rootPhaseIds: serialized.rootPhaseIds,\n activePhaseIds: serialized.activePhaseIds,\n completedPhaseIds: serialized.completedPhaseIds,\n failedPhaseIds: serialized.failedPhaseIds,\n autonomous: serialized.autonomous,\n stopOnComplete: serialized.stopOnComplete,\n createdAt: serialized.createdAt,\n updatedAt: serialized.updatedAt,\n startedAt: serialized.startedAt,\n completedAt: serialized.completedAt,\n };\n }\n\n private deserializePhase(serialized: SerializedPhaseNode): PhaseNode {\n return {\n id: serialized.id,\n name: serialized.name,\n description: serialized.description,\n status: serialized.status,\n taskGraph: this.deserializeTaskGraph(serialized.taskGraph),\n dependsOn: serialized.dependsOn,\n nextPhases: serialized.nextPhases,\n parallelizable: serialized.parallelizable,\n priority: serialized.priority,\n estimateHours: serialized.estimateHours,\n actualDurationMs: serialized.actualDurationMs,\n startedAt: serialized.startedAt,\n completedAt: serialized.completedAt,\n assignedAgents: serialized.assignedAgents,\n metadata: serialized.metadata,\n createdAt: serialized.createdAt,\n updatedAt: serialized.updatedAt,\n };\n }\n\n private deserializeTaskGraph(serialized: SerializedTaskGraph): TaskGraph {\n const nodes = new Map<string, TaskNode>();\n for (const sn of serialized.nodes) {\n nodes.set(sn.id, sn as TaskNode);\n }\n\n return {\n id: serialized.id,\n specId: serialized.specId,\n title: serialized.title,\n nodes,\n edges: serialized.edges ?? [],\n rootNodes: serialized.rootNodes ?? [],\n createdAt: serialized.createdAt,\n updatedAt: serialized.updatedAt,\n };\n }\n}\n", "import type { FileHandle } from 'node:fs/promises';\nimport {\n type AtomicWriteOptions,\n createPersistencePrimitives,\n type FileLockOptions,\n} from '@wrongstack/persistence';\nimport { FsError } from '../types/errors.js';\n\nexport type { AtomicWriteOptions, FileLockOptions } from '@wrongstack/persistence';\n\nconst primitives = createPersistencePrimitives({\n createLockTimeoutError: ({ targetPath, timeoutMs }) =>\n new FsError({\n message: `Timed out waiting for file lock: ${targetPath}`,\n code: 'FS_ATOMIC_WRITE_FAILED',\n path: targetPath,\n context: { timeoutMs },\n }),\n});\n\nexport const atomicWrite: (\n targetPath: string,\n content: string | Uint8Array,\n opts?: AtomicWriteOptions,\n) => Promise<void> = primitives.atomicWrite;\n/**\n * Atomic replace that streams its new contents instead of taking them as one\n * buffer. Use when the replacement is large enough that materializing it would\n * itself be the memory problem (log rotation, tail compaction).\n */\nexport const atomicReplaceWithWriter: <T>(\n targetPath: string,\n write: (handle: FileHandle) => Promise<T>,\n opts?: AtomicWriteOptions,\n) => Promise<T> = primitives.atomicReplaceWithWriter;\nexport const ensureDir: (dir: string) => Promise<void> = primitives.ensureDir;\nexport const withFileLock: <T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts?: FileLockOptions,\n) => Promise<T> = primitives.withFileLock;\n", "import * as fsp from 'node:fs/promises';\nimport type { EventBus } from '../kernel/events.js';\nimport { atomicWrite, withFileLock } from '../utils/atomic-write.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { color } from '../utils/color.js';\nimport { resolveWstackPaths } from '../utils/wstack-paths.js';\nimport { FsError, ERROR_CODES } from '../types/errors.js';\n\n/**\n * Long-running autonomous mission. A goal survives across sessions and\n * drives the EternalAutonomyEngine \u2014 every iteration of the engine\n * consults the goal to choose what to do next.\n *\n * Storage: `~/.wrongstack/projects/<hash>/goal.json`. Persistent and\n * project-scoped on purpose: the goal belongs to the codebase, not the\n * REPL session.\n */\n\nexport interface JournalEntry {\n /** ISO timestamp of the iteration. */\n at: string;\n /** Sequential iteration counter (1-based, monotonically increasing). */\n iteration: number;\n /** Source that produced the action ('todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel' | 'deliverable'). */\n source: 'todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel' | 'deliverable';\n /** Short one-line description of what the iteration set out to do. */\n task: string;\n /** Outcome status. */\n status: 'success' | 'failure' | 'aborted' | 'skipped';\n /** Optional free-form note (error message, summary, etc.). */\n note?: string | undefined;\n /** Optional token usage delta for this iteration. */\n tokens?: { input: number; output: number } | undefined;\n /** Optional USD cost delta for this iteration (provider-estimated). */\n costUsd?: number | undefined;\n}\n\nexport interface GoalFile {\n version: 1;\n /** The raw mission statement as entered by the user. */\n goal: string;\n /**\n * LLM-refined version of the goal \u2014 unambiguous, with concrete\n * deliverables and acceptance criteria.\n */\n refinedGoal?: string | undefined;\n /**\n * Concrete, verifiable deliverables extracted from the refined goal.\n */\n deliverables?: string[] | undefined;\n /**\n * Estimated completion 0-100. Updated by the engine after each\n * iteration. Null means \"not yet assessed\".\n */\n progress?: number | undefined;\n /** Human-readable note explaining the current progress estimate. */\n progressNote?: string | undefined;\n /**\n * Time-series of progress measurements for trend analysis.\n * Last 200 entries retained. Use `recordProgress()` to append.\n */\n progressHistory?: ProgressSnapshot[] | undefined;\n /**\n * Computed trend from recent progress measurements.\n * 'accelerating' | 'steady' | 'stalling' | undefined.\n */\n progressTrend?: 'accelerating' | 'steady' | 'stalling' | undefined;\n /** When the goal was first set or last replaced. */\n setAt: string;\n /** Updated on every iteration completion. */\n lastActivityAt: string;\n /** Total iterations the engine has run against this goal (cumulative). */\n iterations: number;\n /** Engine lifecycle state \u2014 'running' means another process owns this goal. */\n engineState: 'idle' | 'running' | 'stopped';\n /** Mission-level lifecycle. */\n goalState?: 'active' | 'paused' | 'completed' | 'abandoned' | undefined;\n /** Goal-linked Kanban board id. Optional for pre-Kanban goal files. */\n kanbanBoardId?: string | undefined;\n /** ISO timestamp recorded after Brain verifies that every deliverable is reached. */\n reachedAt?: string | undefined;\n /** Durable human-readable reach verdict; currently the literal `goal reached`. */\n reachedNote?: string | undefined;\n /**\n * Per-todo attempt counter.\n */\n todoAttempts?: Record<string, number>;\n /** Bounded ring buffer of recent iterations (newest last). */\n journal: JournalEntry[];\n}\n\n/** Cap on persisted journal entries \u2014 older entries are evicted FIFO. */\nexport const MAX_JOURNAL_ENTRIES = 500;\n\n/**\n * Resolve the goal file path for a given project root.\n *\n * SINGLE canonical location: the per-project directory that\n * `resolveWstackPaths()` uses for everything else (sessions, memory, specs) \u2014\n * `~/.wrongstack/projects/<slug>/goal.json`. This is the same path the `/goal`\n * slash command writes via `opts.paths.projectGoal`, so every reader/writer\n * (the eternal/parallel autonomy engines, the CLI autonomy commands, the TUI\n * F9 panel, and `/goal` itself) now agree on one file.\n *\n * Previously this returned a SEPARATE hash-based dir (`projects/<hash>/`), which\n * disagreed with `/goal` and littered the home dir with thousands of stray\n * `<hash>/goal.json` directories that held nothing else.\n */\nexport function goalFilePath(projectRoot: string): string {\n return resolveWstackPaths({ projectRoot }).projectGoal;\n}\n\nexport async function loadGoal(\n filePath: string,\n events?: EventBus,\n warn?: (msg: string) => void,\n): Promise<GoalFile | null> {\n const t0 = Date.now();\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n return null; // file doesn't exist \u2014 not an error\n }\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n error: toErrorMessage(err),\n recoverable: false,\n });\n throw err; // permission errors etc. should surface\n }\n try {\n const parsed = JSON.parse(raw) as GoalFile;\n if (parsed?.version !== 1 || typeof parsed.goal !== 'string' || !Array.isArray(parsed.journal)) {\n (warn ?? ((msg) => console.warn(JSON.stringify({ level: 'warn', event: 'goal_store.invalid_schema', path: filePath, message: msg, timestamp: new Date().toISOString() }))))(\n 'invalid schema \u2014 consider deleting and re-creating',\n );\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'failure',\n durationMs: Date.now() - t0,\n error: 'invalid_schema',\n });\n return null;\n }\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n return parsed;\n } catch {\n (warn ?? ((msg) => console.warn(JSON.stringify({ level: 'warn', event: 'goal_store.parse_failed', path: filePath, message: msg, timestamp: new Date().toISOString() }))))(\n 'JSON parse failed \u2014 consider deleting and re-creating',\n );\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'failure',\n durationMs: Date.now() - t0,\n error: 'parse_failed',\n });\n return null;\n }\n}\n\nexport async function saveGoal(filePath: string, goal: GoalFile, events?: EventBus): Promise<void> {\n const t0 = Date.now();\n try {\n await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 0o600 });\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'save',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n } catch (err) {\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'save',\n error: toErrorMessage(err),\n recoverable: false,\n });\n throw new FsError({\n message: toErrorMessage(err),\n code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,\n path: filePath,\n cause: err,\n });\n }\n}\n\n/**\n * Atomically load, modify, and save a goal file under a file lock.\n * Prevents lost-update races when the autonomy engine and CLI /goal commands\n * write concurrently (both eternal and parallel engines may run simultaneously).\n *\n * `fn` receives the current GoalFile (or `null` if no goal exists yet)\n * and must return the updated GoalFile (or `null` to delete).\n */\nexport async function updateGoal(\n filePath: string,\n fn: (current: GoalFile | null) => GoalFile | null,\n events?: EventBus,\n): Promise<void> {\n const t0 = Date.now();\n await withFileLock(filePath, async () => {\n const current = await loadGoal(filePath, events);\n const next = fn(current);\n if (next) {\n await saveGoal(filePath, next, events);\n } else {\n try {\n await fsp.unlink(filePath);\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'delete',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n } catch (err) {\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'delete',\n error: toErrorMessage(err),\n recoverable: true,\n });\n // best-effort \u2014 file may not exist\n }\n }\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'update',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n });\n}\n\nexport function emptyGoal(goal: string): GoalFile {\n const now = new Date().toISOString();\n return {\n version: 1,\n goal,\n setAt: now,\n lastActivityAt: now,\n iterations: 0,\n engineState: 'idle',\n goalState: 'active',\n todoAttempts: {},\n journal: [],\n };\n}\n\n/**\n * Set progress estimate on a goal. Returns a new GoalFile.\n * Clamps progress to 0-100.\n */\nexport function setProgress(\n goal: GoalFile,\n progress: number,\n note?: string,\n): GoalFile {\n const clamped = Math.min(100, Math.max(0, progress));\n return {\n ...goal,\n progress: clamped,\n progressNote: note ?? clamped + '% complete',\n };\n}\n\n/**\n * Append a journal entry, bumping iteration counters and trimming the\n * ring buffer. Returns a new GoalFile \u2014 does not mutate the argument.\n */\nexport function appendJournal(goal: GoalFile, entry: Omit<JournalEntry, 'iteration' | 'at'>): GoalFile {\n const iteration = goal.iterations + 1;\n const at = new Date().toISOString();\n const full: JournalEntry = { ...entry, iteration, at };\n const journal = [...goal.journal, full];\n const trimmed = journal.length > MAX_JOURNAL_ENTRIES\n ? journal.slice(journal.length - MAX_JOURNAL_ENTRIES)\n : journal;\n return {\n ...goal,\n iterations: iteration,\n lastActivityAt: at,\n journal: trimmed,\n };\n}\n\n/**\n * Aggregate cumulative cost + tokens across all journal entries.\n */\nexport function summarizeUsage(goal: GoalFile): {\n totalCostUsd: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n iterationsWithUsage: number;\n} {\n let totalCostUsd = 0;\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let iterationsWithUsage = 0;\n for (const e of goal.journal) {\n if (typeof e.costUsd === 'number') totalCostUsd += e.costUsd;\n if (e.tokens) {\n totalInputTokens += e.tokens.input;\n totalOutputTokens += e.tokens.output;\n }\n if (typeof e.costUsd === 'number' || e.tokens) iterationsWithUsage++;\n }\n return { totalCostUsd, totalInputTokens, totalOutputTokens, iterationsWithUsage };\n}\n\nconst DOLLAR = '\\u0024';\n\n/** Format the goal + recent journal as a human-readable status block. */\nexport function formatGoal(goal: GoalFile, journalLimit = 10): string {\n const lines: string[] = [];\n\n // Header \u2014 show refined goal, with original as annotation if different\n const displayGoal = goal.refinedGoal || goal.goal;\n lines.push(color.bold('Goal') + ': ' + displayGoal);\n if (goal.refinedGoal && goal.refinedGoal !== goal.goal) {\n const snippet = goal.goal.length > 60 ? goal.goal.slice(0, 60) + '\u2026' : goal.goal;\n lines.push(color.dim(' (original: \"' + snippet + '\")'));\n }\n\n // Progress bar (20-segment)\n if (typeof goal.progress === 'number') {\n const pct = Math.min(100, Math.max(0, Math.round(goal.progress)));\n const filled = Math.round(pct / 5);\n const empty = 20 - filled;\n const bar = color.green('\u2588'.repeat(filled)) + color.dim('\u2591'.repeat(empty));\n lines.push('Progress: ' + bar + ' ' + color.bold(pct + '%'));\n if (goal.progressNote) {\n lines.push(' ' + color.dim(goal.progressNote));\n }\n // Trend indicator\n if (goal.progressTrend) {\n const trendIcon = goal.progressTrend === 'accelerating' ? '\uD83D\uDE80'\n : goal.progressTrend === 'stalling' ? '\u26A0\uFE0F'\n : '\u27A1\uFE0F';\n lines.push(' Trend: ' + trendIcon + ' ' + goal.progressTrend);\n }\n }\n\n // Deliverables checklist\n if (goal.deliverables && goal.deliverables.length > 0) {\n lines.push('');\n lines.push(color.bold('Deliverables:'));\n for (const d of goal.deliverables) {\n const done = /^\\[[x\u2713]\\]|\u2705|\\(done\\)/i.test(d);\n const marker = done ? color.green('\u2713') : color.dim('\u25CB');\n lines.push(' ' + marker + ' ' + d);\n }\n }\n\n lines.push('');\n lines.push('Set: ' + goal.setAt);\n lines.push('Last activity: ' + goal.lastActivityAt);\n lines.push('Iterations: ' + goal.iterations);\n const stateLabel = goal.goalState ?? 'active';\n lines.push('State: ' + stateLabel + (goal.iterations > 0 ? ' (iteration #' + goal.iterations + ')' : ''));\n lines.push('Engine: ' + goal.engineState);\n const usage = summarizeUsage(goal);\n if (usage.iterationsWithUsage > 0) {\n const spent = 'Spent: ' + DOLLAR + usage.totalCostUsd.toFixed(4)\n + ' (in ' + usage.totalInputTokens + ' / out ' + usage.totalOutputTokens\n + ' tokens across ' + usage.iterationsWithUsage + ' iterations)';\n lines.push(spent);\n }\n if (goal.journal.length > 0) {\n lines.push('');\n lines.push('Recent journal (last ' + Math.min(journalLimit, goal.journal.length) + '):');\n const tail = goal.journal.slice(-journalLimit);\n for (const e of tail) {\n const mark = e.status === 'success' ? '\u2713' : e.status === 'failure' ? '\u2717' : e.status === 'aborted' ? '\u2298' : '\u00B7';\n const note = e.note ? ' \u2014 ' + e.note : '';\n const cost = typeof e.costUsd === 'number' ? ' (' + DOLLAR + e.costUsd.toFixed(4) + ')' : '';\n lines.push(' #' + e.iteration + ' ' + mark + ' [' + e.source + '] ' + e.task + cost + note);\n }\n }\n return lines.join('\\n');\n}\n\n/** A single progress measurement at a point in time. */\nexport interface ProgressSnapshot {\n at: string;\n progress: number;\n note?: string | undefined;\n}\n\n/**\n * Parse [PROGRESS: N%] from agent final text.\n * Supports formats:\n * [PROGRESS: 45%]\n * [PROGRESS: 45%] \u2014 3/5 deliverables done\n * [progress: 100%]\n * Returns null if no match.\n */\nexport function parseProgressFromText(text: string): { progress: number; note?: string } | null {\n const re = /\\[progress:\\s*(\\d{1,3})%\\]\\s*(?:[\u2014-]\\s*(.+))?/i;\n const m = text.match(re);\n if (!m) return null;\n // Regex match guarantees capture group 1 exists, but use ?? fallback to\n // satisfy noUncheckedIndexedAccess without a non-null assertion.\n const progress = Math.min(100, Math.max(0, Number.parseInt(m[1] ?? '0', 10)));\n const note = m[2]?.trim() || undefined;\n return note === undefined ? { progress } : { progress, note };\n}\n\n/**\n * Record a progress measurement. Returns a new GoalFile with:\n * - progress + progressNote updated\n * - progressHistory appended (last 200 entries kept)\n * - progress trend computed (accelerating/steady/stalling)\n */\nexport function recordProgress(\n goal: GoalFile,\n progress: number,\n note?: string,\n): GoalFile {\n const clamped = Math.min(100, Math.max(0, progress));\n const history = [...(goal.progressHistory ?? []), { at: new Date().toISOString(), progress: clamped, note }];\n // Keep last 200 snapshots\n const trimmed = history.length > 200 ? history.slice(-200) : history;\n\n return {\n ...goal,\n progress: clamped,\n progressNote: note ?? `${clamped}% complete`,\n progressHistory: trimmed,\n progressTrend: computeTrend(trimmed),\n };\n}\n\n/** Max progress history entries to retain. */\nexport const MAX_PROGRESS_HISTORY = 200;\n\nfunction computeTrend(history: ProgressSnapshot[]): 'accelerating' | 'steady' | 'stalling' | undefined {\n if (history.length < 3) return undefined;\n const recent = history.slice(-5);\n const deltas: number[] = [];\n for (let i = 1; i < recent.length; i++) {\n deltas.push((recent[i]?.progress ?? 0) - (recent[i - 1]?.progress ?? 0));\n }\n /* v8 ignore next -- unreachable: history.length>=3 guard above guarantees >=2 deltas */\n if (deltas.length < 2) return undefined;\n const avgDelta = deltas.reduce((a, b) => a + b, 0) / deltas.length;\n if (avgDelta > 2) return 'accelerating';\n if (avgDelta < -1) return 'stalling';\n return 'steady';\n}\n", "import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/**\n * Path layout. All developer-level state lives in ~/.wrongstack/.\n * Per-project state is keyed by the canonical project root under\n * ~/.wrongstack/projects/<slug>/. Linked Git worktrees resolve to their main\n * checkout so coordination and durable state are shared across worktrees.\n *\n * The ONLY thing inside the project tree is the optional\n * .wrongstack/AGENTS.md (committed) and .wrongstack/skills/ (committed).\n */\n\nexport interface WstackPaths {\n /** ~/.wrongstack \u2014 global root. */\n globalRoot: string;\n /** Active profile name resolved from the bootstrap config. */\n profileName: string;\n /** ~/.wrongstack/profiles/<activeProfile> \u2014 active user-profile root. */\n profileDir: string;\n /** Absolute project root. */\n projectRoot: string;\n /** Home directory (~) \u2014 base for foreign tool state (~/.codex, ~/.agents, \u2026). */\n homeDir: string;\n /**\n * ~/.wrongstack/profiles/<activeProfile> \u2014 directory for profile-scoped\n * user state (mode.json, statusline.json, custom-context-modes.json, \u2026).\n */\n configDir: string;\n /** ~/.wrongstack/config.json \u2014 bootstrap config (activeProfile + version). */\n globalConfig: string;\n /**\n * ~/.wrongstack/profiles \u2014 directory containing per-profile configs.\n * Each profile has its own subdirectory with a config.json.\n */\n profilesDir: string;\n /**\n * Resolve the config path for a named profile.\n * Returns ~/.wrongstack/profiles/<name>/config.json.\n */\n profileConfig: (name: string) => string;\n /** Resolve ~/.wrongstack/profiles/<name>/statusline.json */\n profileStatuslineConfig: (name: string) => string;\n /** Resolve ~/.wrongstack/profiles/<name>/mode.json */\n profileModeConfig: (name: string) => string;\n /** Resolve ~/.wrongstack/profiles/<name>/provider-status.json */\n profileProviderStatus: (name: string) => string;\n /** Resolve ~/.wrongstack/profiles/<name>/update-cache.json */\n profileUpdateCache: (name: string) => string;\n /** ~/.wrongstack/.key \u2014 32 random bytes, mode 0600, AES-GCM key for the secret vault. */\n secretsKey: string;\n /** ~/.wrongstack/profiles/<activeProfile>/memory.md \u2014 profile memory. */\n globalMemory: string;\n /** ~/.wrongstack/profiles/<activeProfile>/skills \u2014 profile skills. */\n globalSkills: string;\n /** ~/.claude/skills \u2014 user-global skills from foreign coding agents (Claude Code, Codex, \u2026). Read-only. */\n globalClaudeSkills: string;\n /** ~/.wrongstack/profiles/<activeProfile>/design-kits \u2014 profile Design Studio kits. */\n globalDesignKits: string;\n /** ~/.wrongstack/profiles/<activeProfile>/prompts \u2014 profile prompt library. */\n globalPrompts: string;\n /** ~/.wrongstack/profiles/<activeProfile>/instructions \u2014 profile instruction overrides. */\n globalInstructions: string;\n /** ~/.wrongstack/profiles/<activeProfile>/prompt-usage.json \u2014 prompt usage. */\n promptUsage: string;\n /** ~/.wrongstack/cache \u2014 fetched data (models.dev, etc.). */\n cacheDir: string;\n /** ~/.wrongstack/cache/models.dev.json */\n modelsCache: string;\n /** ~/.wrongstack/cache/models-overlay.json \u2014 cached curated overlay. */\n modelsOverlayCache: string;\n /**\n * Per-project codebase symbol index (SQLite). Lives under the global project\n * dir \u2014 NOT inside the repo \u2014 so it never clutters the working tree or needs\n * gitignoring. `~/.wrongstack/projects/<hash>/codebase-index`.\n */\n projectCodebaseIndex: string;\n /** ~/.wrongstack/profiles/<activeProfile>/history \u2014 REPL line history. */\n historyFile: string;\n /** ~/.wrongstack/logs/wrongstack.log */\n logFile: string;\n /** ~/.wrongstack/projects/<hash> */\n projectDir: string;\n /** ~/.wrongstack/projects/<hash>/memory.md */\n projectMemory: string;\n /** ~/.wrongstack/projects/<hash>/sessions */\n projectSessions: string;\n /** ~/.wrongstack/projects/<hash>/trust.json */\n projectTrust: string;\n /** ~/.wrongstack/projects/<hash>/meta.json */\n projectMeta: string;\n /** ~/.wrongstack/projects/<hash>/config.local.json \u2014 optional override */\n projectLocalConfig: string;\n /** <project>/.wrongstack/config.json \u2014 per-project settings (safe fields only).\n * This lives inside the project root so it can be gitignored or shared. */\n inProjectConfig: string;\n /** <project>/.wrongstack/AGENTS.md \u2014 committed project memory. */\n inProjectAgentsFile: string;\n /** <project>/.wrongstack/skills \u2014 committed project skills. */\n inProjectSkills: string;\n /** <project>/.claude/skills \u2014 project skills authored for foreign coding agents (Claude Code, \u2026). Read-only. */\n inProjectClaudeSkills: string;\n /** <project>/.wrongstack/prompts \u2014 committed project prompt library. */\n inProjectPrompts: string;\n /** <project>/.wrongstack/instructions \u2014 committed project instruction overrides. */\n inProjectInstructions: string;\n /** <project>/.wrongstack/design-kits \u2014 committed project Design Studio kits. */\n inProjectDesignKits: string;\n /** <project>/.wrongstack/worktrees \u2014 git worktrees for per-phase isolation (gitignored). */\n inProjectWorktrees: string;\n /** Stable hash for the canonical project root (shared by linked Git worktrees). */\n projectHash: string;\n /** Human-readable canonical project slug, shared by linked Git worktrees. */\n projectSlug: string;\n /** ~/.wrongstack/projects/<hash>/goal.json \u2014 goal persistence */\n projectGoal: string;\n /** ~/.wrongstack/projects/<hash>/input-history.json \u2014 TUI prompt input history */\n projectInputHistory: string;\n /** ~/.wrongstack/projects/<hash>/specs \u2014 SDD spec files */\n projectSpecs: string;\n /** ~/.wrongstack/projects/<hash>/task-graphs \u2014 SDD task graphs */\n projectTaskGraphs: string;\n /** ~/.wrongstack/projects/<hash>/sdd-session.json \u2014 SDD session state */\n projectSddSession: string;\n /** ~/.wrongstack/projects/<hash>/plan.json \u2014 plan persistence */\n projectPlan: string;\n /** ~/.wrongstack/projects/<hash>/autophase \u2014 Goal phase-graph JSON files (dir name kept for backward compat) */\n projectAutophase: string;\n /** ~/.wrongstack/projects/<hash>/sdd-boards \u2014 live SDD board snapshots + JSONL event logs */\n projectSddBoards: string;\n /** ~/.wrongstack/profiles/<activeProfile>/sync.json \u2014 CloudSync configuration */\n syncConfig: string;\n /** ~/.wrongstack/config-history \u2014 timestamped backups on every config write */\n configHistoryDir: string;\n /** Function to get the status.json path for a project given its hash. */\n projectStatus: (projectHash: string) => string;\n}\n\n/**\n * Resolve the stable project identity root used by global WrongStack state.\n *\n * A linked Git worktree has its own checkout path and a `.git` *file* that\n * points into `<main>/.git/worktrees/<name>`. Its `commondir` points back to\n * the main checkout's `.git` directory. Treating the linked checkout path as\n * the project identity would split one repository into multiple session,\n * registry, and mailbox directories \u2014 agents in different worktrees would be\n * unable to see or message each other.\n *\n * Project-local paths still use the caller's actual checkout. Only global\n * state identity is canonicalized. Non-Git projects, normal checkouts, Git\n * submodules, and separate-git-dir layouts keep their existing identity.\n */\nexport function canonicalProjectRoot(absRoot: string): string {\n const checkoutRoot = path.resolve(absRoot);\n const dotGit = path.join(checkoutRoot, '.git');\n\n try {\n if (!fs.statSync(dotGit).isFile()) return checkoutRoot;\n\n const gitDirLine = fs.readFileSync(dotGit, 'utf8').trim();\n const match = /^gitdir:\\s*(.+)$/i.exec(gitDirLine);\n if (!match?.[1]) return checkoutRoot;\n\n const gitDir = path.resolve(checkoutRoot, match[1].trim());\n const commonDirFile = path.join(gitDir, 'commondir');\n if (!fs.statSync(commonDirFile).isFile()) return checkoutRoot;\n\n const commonDir = path.resolve(gitDir, fs.readFileSync(commonDirFile, 'utf8').trim());\n // Linked worktrees created by Git share the main checkout's `.git` dir.\n // A submodule or --separate-git-dir layout may point elsewhere; do not\n // guess a working-tree root for those shapes.\n if (path.basename(commonDir).toLowerCase() !== '.git') return checkoutRoot;\n return path.dirname(commonDir);\n } catch {\n // Missing/malformed administrative files must never make path resolution\n // fail. Falling back preserves the pre-canonicalization behavior.\n return checkoutRoot;\n }\n}\n\nexport function projectHash(absRoot: string): string {\n return createHash('sha256').update(canonicalProjectRoot(absRoot)).digest('hex').slice(0, 12);\n}\n\n/**\n * Human-readable project directory name: slugified folder name + short hash\n * suffix for uniqueness. e.g. `wrongstack-a1b2c3` instead of `3024e5e6fa58`.\n */\nexport function projectSlug(absRoot: string): string {\n const identityRoot = canonicalProjectRoot(absRoot);\n const base = slugify(path.basename(identityRoot));\n const hash = createHash('sha256').update(identityRoot).digest('hex').slice(0, 6);\n return `${base}-${hash}`;\n}\n\n/** Turn a folder name into a filesystem-safe lowercase slug. */\nfunction slugify(name: string): string {\n return (\n name\n .toLowerCase()\n // Collapse any run of non-alphanumeric chars into a single hyphen.\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40) || 'project'\n );\n}\n\nexport interface WstackPathOptions {\n userHome?: string | undefined;\n projectRoot: string;\n /** Override the global root (e.g. for tests). Default: `${userHome}/.wrongstack`. */\n globalRoot?: string | undefined;\n /** Explicit profile override. Otherwise read from the root bootstrap config. */\n profileName?: string | undefined;\n}\n\n/** Make an untrusted profile name safe for use as one path segment. */\nexport function safeProfileName(name: string | undefined): string {\n const safe = (name ?? '').replace(/[/\\\\:]/g, '_').replace(/\\.\\./g, '_').trim();\n return safe || 'default';\n}\n\n/**\n * Resolve the selected profile from ~/.wrongstack/config.json. The root file\n * is bootstrap metadata only; a missing/corrupt bootstrap selects `default`.\n */\nexport function activeProfileName(globalRoot: string): string {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(globalRoot, 'config.json'), 'utf8')) as {\n activeProfile?: unknown;\n };\n return safeProfileName(typeof parsed.activeProfile === 'string' ? parsed.activeProfile : undefined);\n } catch {\n return 'default';\n }\n}\n\n/**\n * The global `~/.wrongstack` root, honoring the `WRONGSTACK_HOME` env\n * override. The override exists so tests (and sandboxed runs) can redirect\n * ALL global state \u2014 config, secrets, logs, projects/, mailboxes \u2014 away from\n * the real user home. Before it existed, `pnpm test` booted runtimes against\n * the real `~/.wrongstack`: it read the user's real config.json (starting a\n * second live Telegram poller), appended to the real wrongstack.log, and left\n * ~20k orphaned fixture dirs under projects/.\n *\n * Every code path that wants the global dir must come through here (or\n * through `resolveWstackPaths`) instead of `path.join(os.homedir(), '.wrongstack')`.\n */\nexport function wstackGlobalRoot(): string {\n const fromEnv = process.env['WRONGSTACK_HOME'];\n if (fromEnv && fromEnv.trim().length > 0) return path.resolve(fromEnv);\n return path.join(os.homedir(), '.wrongstack');\n}\n\nexport function resolveWstackPaths(opts: WstackPathOptions): WstackPaths {\n // Precedence: explicit globalRoot > explicit userHome (callers/tests that\n // pass one expect paths under it) > WRONGSTACK_HOME env > real home dir.\n const globalRoot =\n opts.globalRoot ?? (opts.userHome ? path.join(opts.userHome, '.wrongstack') : wstackGlobalRoot());\n // Home dir for FOREIGN tool state (Claude Code's ~/.claude). Independent of\n // WRONGSTACK_HOME, which redirects only WrongStack state: a real user's\n // Claude skills live in their real home, but tests pass `userHome` to keep\n // both `.wrongstack` and `.claude` under a temp dir.\n const homeDir = opts.userHome ?? os.homedir();\n const profileName = safeProfileName(opts.profileName ?? activeProfileName(globalRoot));\n const profileDir = path.join(globalRoot, 'profiles', profileName);\n const hash = projectHash(opts.projectRoot);\n const slug = projectSlug(opts.projectRoot);\n const projectDir = path.join(globalRoot, 'projects', slug);\n return {\n globalRoot,\n profileName,\n profileDir,\n projectRoot: opts.projectRoot,\n homeDir,\n configDir: profileDir,\n globalConfig: path.join(globalRoot, 'config.json'),\n profilesDir: path.join(globalRoot, 'profiles'),\n profileConfig: (name: string) => {\n return path.join(globalRoot, 'profiles', safeProfileName(name), 'config.json');\n },\n profileStatuslineConfig: (name: string) => {\n return path.join(globalRoot, 'profiles', safeProfileName(name), 'statusline.json');\n },\n profileModeConfig: (name: string) => {\n return path.join(globalRoot, 'profiles', safeProfileName(name), 'mode.json');\n },\n profileProviderStatus: (name: string) => {\n return path.join(globalRoot, 'profiles', safeProfileName(name), 'provider-status.json');\n },\n profileUpdateCache: (name: string) => {\n return path.join(globalRoot, 'profiles', safeProfileName(name), 'update-cache.json');\n },\n secretsKey: path.join(globalRoot, '.key'),\n globalMemory: path.join(profileDir, 'memory.md'),\n globalSkills: path.join(profileDir, 'skills'),\n globalClaudeSkills: path.join(homeDir, '.claude', 'skills'),\n globalDesignKits: path.join(profileDir, 'design-kits'),\n globalPrompts: path.join(profileDir, 'prompts'),\n globalInstructions: path.join(profileDir, 'instructions'),\n promptUsage: path.join(profileDir, 'prompt-usage.json'),\n cacheDir: path.join(globalRoot, 'cache'),\n modelsCache: path.join(globalRoot, 'cache', 'models.dev.json'),\n modelsOverlayCache: path.join(globalRoot, 'cache', 'models-overlay.json'),\n historyFile: path.join(profileDir, 'history'),\n logFile: path.join(globalRoot, 'logs', 'wrongstack.log'),\n projectDir,\n projectCodebaseIndex: path.join(projectDir, 'codebase-index'),\n projectMemory: path.join(projectDir, 'memory.md'),\n projectSessions: path.join(projectDir, 'sessions'),\n projectTrust: path.join(projectDir, 'trust.json'),\n projectMeta: path.join(projectDir, 'meta.json'),\n projectLocalConfig: path.join(projectDir, 'config.local.json'),\n inProjectConfig: path.join(opts.projectRoot, '.wrongstack', 'config.json'),\n inProjectAgentsFile: path.join(opts.projectRoot, '.wrongstack', 'AGENTS.md'),\n inProjectSkills: path.join(opts.projectRoot, '.wrongstack', 'skills'),\n inProjectClaudeSkills: path.join(opts.projectRoot, '.claude', 'skills'),\n inProjectPrompts: path.join(opts.projectRoot, '.wrongstack', 'prompts'),\n inProjectInstructions: path.join(opts.projectRoot, '.wrongstack', 'instructions'),\n inProjectDesignKits: path.join(opts.projectRoot, '.wrongstack', 'design-kits'),\n inProjectWorktrees: path.join(opts.projectRoot, '.wrongstack', 'worktrees'),\n projectHash: hash,\n projectSlug: slug,\n projectGoal: path.join(projectDir, 'goal.json'),\n projectInputHistory: path.join(projectDir, 'input-history.json'),\n projectSpecs: path.join(projectDir, 'specs'),\n projectTaskGraphs: path.join(projectDir, 'task-graphs'),\n projectSddSession: path.join(projectDir, 'sdd-session.json'),\n projectPlan: path.join(projectDir, 'plan.json'),\n projectAutophase: path.join(projectDir, 'autophase'),\n projectSddBoards: path.join(projectDir, 'sdd-boards'),\n syncConfig: path.join(profileDir, 'sync.json'),\n configHistoryDir: path.join(globalRoot, 'config-history'),\n projectStatus: (projectHash: string) => path.join(globalRoot, 'projects', projectHash, 'status.json'),\n };\n}\n", "import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { atomicWrite, withFileLock } from '../utils/atomic-write.js';\nimport type { PhaseStore } from './phase-store.js';\nimport type { PhaseGraph, PhaseNode } from './types.js';\n\nexport interface Checkpoint {\n id: string;\n graphId: string;\n phaseId: string;\n phaseStatus: PhaseNode['status'];\n taskStatuses: Array<{ taskId: string; status: string; title: string }>;\n timestamp: number;\n label?: string | undefined;\n}\n\nexport interface CheckpointManagerOptions {\n store: PhaseStore;\n maxCheckpoints?: number | undefined;\n /** Max age in ms before a checkpoint is eligible for TTL-based pruning. Default: 7 days. */\n maxCheckpointAgeMs?: number | undefined;\n baseDir?: string | undefined;\n}\n\ninterface SerializedCheckpoint {\n id: string;\n graphId: string;\n phaseId: string;\n phaseStatus: PhaseNode['status'];\n taskStatuses: Array<{ taskId: string; status: string; title: string }>;\n timestamp: number;\n label?: string | undefined;\n}\n\n/**\n * CheckpointManager - saves and restores snapshots of the phase graph.\n *\n * Usage:\n * const cm = new CheckpointManager({ store });\n * await cm.saveCheckpoint(graph, 'Before risky refactor');\n * // ... if something goes wrong ...\n * const restored = await cm.restoreCheckpoint(checkpointId);\n */\nexport class CheckpointManager {\n private store: PhaseStore;\n private maxCheckpoints: number;\n private maxCheckpointAgeMs: number;\n private checkpoints = new Map<string, Checkpoint>();\n private baseDir: string;\n\n constructor(opts: CheckpointManagerOptions) {\n this.store = opts.store;\n this.maxCheckpoints = opts.maxCheckpoints ?? 10;\n this.maxCheckpointAgeMs = opts.maxCheckpointAgeMs ?? 7 * 24 * 60 * 60 * 1000; // 7 days\n this.baseDir = opts.baseDir ?? path.join(opts.store.baseDir, '.checkpoints');\n // Directory creation is lazy \u2014 happens on first save\n }\n\n async initialize(): Promise<void> {\n await fsp.mkdir(this.baseDir, { recursive: true });\n await this.loadFromDisk();\n }\n\n async saveCheckpoint(graph: PhaseGraph, label?: string): Promise<Checkpoint> {\n // Save the graph first.\n await this.store.save(graph);\n\n // Extract checkpoint information from the active phase.\n const activePhase = Array.from(graph.phases.values()).find(\n (p) => p.status === 'running' || p.status === 'paused',\n );\n\n const checkpoint: Checkpoint = {\n id: crypto.randomUUID(),\n graphId: graph.id,\n phaseId: activePhase?.id ?? graph.rootPhaseIds[0] ?? '',\n phaseStatus: activePhase?.status ?? 'pending',\n taskStatuses: activePhase\n ? Array.from(activePhase.taskGraph.nodes.values()).map((t) => ({\n taskId: t.id,\n status: t.status,\n title: t.title,\n }))\n : [],\n timestamp: Date.now(),\n label,\n };\n\n this.checkpoints.set(checkpoint.id, checkpoint);\n\n // Save to disk.\n await this.saveToDisk(checkpoint);\n\n // Clean up old checkpoints for this graph only.\n await this.pruneCheckpoints(graph.id);\n\n return checkpoint;\n }\n\n async restoreCheckpoint(checkpointId: string): Promise<PhaseGraph | null> {\n let checkpoint = this.checkpoints.get(checkpointId);\n\n // Load from disk if the checkpoint is not in memory.\n if (!checkpoint) {\n await this.loadFromDisk();\n checkpoint = this.checkpoints.get(checkpointId);\n }\n\n if (!checkpoint) return null;\n\n const graph = await this.store.load(checkpoint.graphId);\n if (!graph) return null;\n\n // Restore the phase status from the checkpoint.\n const phase = graph.phases.get(checkpoint.phaseId);\n if (phase) {\n phase.status = checkpoint.phaseStatus;\n phase.updatedAt = Date.now();\n\n // Restore task statuses.\n for (const ts of checkpoint.taskStatuses) {\n const task = phase.taskGraph.nodes.get(ts.taskId);\n if (task) {\n task.status = ts.status as import('../types/task-graph.js').TaskStatus;\n task.updatedAt = Date.now();\n }\n }\n }\n\n graph.updatedAt = Date.now();\n return graph;\n }\n\n listCheckpoints(graphId?: string): Checkpoint[] {\n const all = Array.from(this.checkpoints.values());\n const filtered = graphId ? all.filter((c) => c.graphId === graphId) : all;\n return filtered.sort((a, b) => b.timestamp - a.timestamp);\n }\n\n async deleteCheckpoint(checkpointId: string): Promise<boolean> {\n const checkpoint = this.checkpoints.get(checkpointId);\n if (!checkpoint) return false;\n\n this.checkpoints.delete(checkpointId);\n // Await disk deletion to avoid split-brain between memory and disk\n await this.deleteFromDisk(checkpointId);\n return true;\n }\n\n private async saveToDisk(checkpoint: Checkpoint): Promise<void> {\n const filePath = path.join(this.baseDir, `${checkpoint.graphId}.json`);\n const serialized: SerializedCheckpoint = {\n ...checkpoint,\n };\n\n await withFileLock(filePath, async () => {\n // Read current on-disk state first\n let existing: SerializedCheckpoint[] = [];\n try {\n const raw = await fsp.readFile(filePath, 'utf8');\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) {\n existing = parsed as SerializedCheckpoint[];\n }\n } catch {\n // File doesn't exist or is invalid \u2014 start fresh\n }\n\n // Write to disk BEFORE updating in-memory state \u2014 ensures consistency\n existing.push(serialized);\n await atomicWrite(filePath, JSON.stringify(existing, null, 2), { mode: 0o600 });\n });\n }\n\n private async deleteFromDisk(checkpointId: string): Promise<void> {\n let entries: string[];\n try {\n entries = await fsp.readdir(this.baseDir);\n } catch {\n return; // Directory doesn't exist \u2014 nothing to delete\n }\n\n for (const filename of entries) {\n if (!filename.endsWith('.json')) continue;\n\n const filePath = path.join(this.baseDir, filename);\n try {\n await withFileLock(filePath, async () => {\n const raw = await fsp.readFile(filePath, 'utf8');\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return;\n const existing = parsed as SerializedCheckpoint[];\n const filtered = existing.filter((c) => c.id !== checkpointId);\n\n if (filtered.length !== existing.length) {\n if (filtered.length === 0) {\n await fsp.unlink(filePath);\n } else {\n await atomicWrite(filePath, JSON.stringify(filtered, null, 2), { mode: 0o600 });\n }\n }\n });\n } catch {\n // Skip invalid files\n }\n }\n }\n\n private async loadFromDisk(): Promise<void> {\n let entries: string[];\n try {\n entries = await fsp.readdir(this.baseDir);\n } catch {\n // Directory doesn't exist yet \u2014 nothing to load\n return;\n }\n\n for (const filename of entries) {\n if (!filename.endsWith('.json')) continue;\n\n const filePath = path.join(this.baseDir, filename);\n try {\n const raw = await fsp.readFile(filePath, 'utf8');\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) continue;\n const checkpoints = parsed as SerializedCheckpoint[];\n\n for (const sc of checkpoints) {\n const checkpoint: Checkpoint = {\n id: sc.id,\n graphId: sc.graphId,\n phaseId: sc.phaseId,\n phaseStatus: sc.phaseStatus,\n taskStatuses: sc.taskStatuses,\n timestamp: sc.timestamp,\n label: sc.label,\n };\n this.checkpoints.set(checkpoint.id, checkpoint);\n }\n } catch {\n // Skip invalid files\n }\n }\n }\n\n private async pruneCheckpoints(graphId: string): Promise<void> {\n const now = Date.now();\n const graphCheckpoints = Array.from(this.checkpoints.values())\n .filter((checkpoint) => checkpoint.graphId === graphId)\n .sort((a, b) => a.timestamp - b.timestamp);\n\n // TTL-based pruning: evict checkpoints older than maxCheckpointAgeMs.\n for (const cp of graphCheckpoints) {\n if (now - cp.timestamp > this.maxCheckpointAgeMs) {\n this.checkpoints.delete(cp.id);\n await this.deleteFromDisk(cp.id);\n }\n }\n\n // Count-based pruning: keep only the newest maxCheckpoints.\n const remaining = Array.from(this.checkpoints.values())\n .filter((checkpoint) => checkpoint.graphId === graphId)\n .sort((a, b) => a.timestamp - b.timestamp);\n while (remaining.length > this.maxCheckpoints) {\n const oldest = remaining.shift();\n if (oldest) {\n this.checkpoints.delete(oldest.id);\n await this.deleteFromDisk(oldest.id);\n }\n }\n }\n}\n"],
5
- "mappings": ";AAUO,IAAM,mBAAN,MAA4C;AAAA,EAChC,SAAS,oBAAI,IAAuB;AAAA,EAErD,MAAM,UAAU,OAAiC;AAC/C,SAAK,OAAO,IAAI,MAAM,IAAI,KAAK,WAAW,KAAK,CAAC;AAAA,EAClD;AAAA,EAEA,MAAM,UAAU,IAAuC;AACrD,UAAM,QAAQ,KAAK,OAAO,IAAI,EAAE;AAChC,WAAO,QAAQ,KAAK,WAAW,KAAK,IAAI;AAAA,EAC1C;AAAA,EAEA,MAAM,aAA+E;AACnF,WAAO,MAAM,KAAK,KAAK,OAAO,OAAO,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,MACtD,IAAI,MAAM;AAAA,MACV,OAAO,MAAM;AAAA,MACb,WAAW,MAAM;AAAA,IACnB,EAAE;AAAA,EACJ;AAAA,EAEA,MAAM,YAAY,IAA2B;AAC3C,SAAK,OAAO,OAAO,EAAE;AAAA,EACvB;AAAA,EAEQ,WAAW,OAA6B;AAC9C,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,IAAI,IAAI,MAAM,KAAK;AAAA,MAC1B,OAAO,CAAC,GAAG,MAAM,KAAK;AAAA,MACtB,WAAW,CAAC,GAAG,MAAM,SAAS;AAAA,IAChC;AAAA,EACF;AACF;;;ACtCO,SAAS,eAAe,KAAsB;AACnD,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;;ACkBO,IAAM,cAAc;AAAA;AAAA,EAEzB,uBAAuB;AAAA,EACvB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,0BAA0B;AAAA,EAC1B,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,2BAA2B;AAAA;AAAA,EAE3B,gBAAgB;AAAA,EAChB,wBAAwB;AAAA,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