@bastani/atomic 0.9.11-alpha.4 → 0.9.11-alpha.6

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 (1032) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +12 -5
  3. package/dist/builtin/intercom/package.json +2 -2
  4. package/dist/builtin/mcp/CHANGELOG.md +6 -0
  5. package/dist/builtin/mcp/README.md +3 -3
  6. package/dist/builtin/mcp/cli.js +0 -1
  7. package/dist/builtin/mcp/config.ts +0 -2
  8. package/dist/builtin/mcp/package.json +3 -3
  9. package/dist/builtin/mcp/types.ts +0 -1
  10. package/dist/builtin/subagents/CHANGELOG.md +19 -0
  11. package/dist/builtin/subagents/README.md +10 -1
  12. package/dist/builtin/subagents/agents/code-simplifier.md +47 -102
  13. package/dist/builtin/subagents/agents/codebase-analyzer.md +27 -130
  14. package/dist/builtin/subagents/agents/codebase-locator.md +24 -83
  15. package/dist/builtin/subagents/agents/codebase-online-researcher.md +60 -259
  16. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +29 -207
  17. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +28 -150
  18. package/dist/builtin/subagents/agents/codebase-research-locator.md +21 -118
  19. package/dist/builtin/subagents/agents/debugger.md +29 -65
  20. package/dist/builtin/subagents/agents/worker.md +23 -30
  21. package/dist/builtin/subagents/package.json +4 -4
  22. package/dist/builtin/subagents/prompts/gather-context-and-clarify.md +18 -11
  23. package/dist/builtin/subagents/prompts/parallel-cleanup.md +34 -33
  24. package/dist/builtin/subagents/prompts/parallel-context-build.md +22 -36
  25. package/dist/builtin/subagents/prompts/parallel-handoff-plan.md +20 -52
  26. package/dist/builtin/subagents/prompts/parallel-research.md +17 -41
  27. package/dist/builtin/subagents/prompts/parallel-review.md +23 -28
  28. package/dist/builtin/subagents/prompts/review-loop.md +18 -27
  29. package/dist/builtin/subagents/skills/subagent/SKILL.md +6 -6
  30. package/dist/builtin/subagents/src/extension/prompt-guidance.ts +4 -1
  31. package/dist/builtin/subagents/src/runs/background/async-execution-chain.ts +23 -4
  32. package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +2 -0
  33. package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +10 -0
  34. package/dist/builtin/subagents/src/runs/background/subagent-runner-step.ts +1 -0
  35. package/dist/builtin/subagents/src/runs/foreground/chain-execution-dynamic-step.ts +2 -0
  36. package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +8 -0
  37. package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-step.ts +1 -0
  38. package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +6 -0
  39. package/dist/builtin/subagents/src/runs/foreground/chain-execution-types.ts +2 -0
  40. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +7 -0
  41. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-chain.ts +1 -0
  42. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-resume.ts +3 -0
  43. package/dist/builtin/subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -2
  44. package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +1 -0
  45. package/dist/builtin/subagents/src/runs/shared/pi-args.ts +5 -3
  46. package/dist/builtin/subagents/src/shared/settings.ts +4 -0
  47. package/dist/builtin/web-access/package.json +2 -2
  48. package/dist/builtin/workflows/CHANGELOG.md +53 -0
  49. package/dist/builtin/workflows/README.md +72 -70
  50. package/dist/builtin/workflows/ambient.d.ts +0 -5
  51. package/dist/builtin/workflows/builtin/adversarial-verification-prompts.ts +7 -4
  52. package/dist/builtin/workflows/builtin/adversarial-verification-runner.ts +1 -1
  53. package/dist/builtin/workflows/builtin/adversarial-verification.ts +2 -1
  54. package/dist/builtin/workflows/builtin/classify-and-act-prompts.ts +5 -2
  55. package/dist/builtin/workflows/builtin/classify-and-act-runner.ts +5 -7
  56. package/dist/builtin/workflows/builtin/classify-and-act.ts +3 -2
  57. package/dist/builtin/workflows/builtin/fan-out-and-synthesize-prompts.ts +6 -3
  58. package/dist/builtin/workflows/builtin/fan-out-and-synthesize-runner.ts +5 -5
  59. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.ts +3 -2
  60. package/dist/builtin/workflows/builtin/generate-and-filter-prompts.ts +7 -4
  61. package/dist/builtin/workflows/builtin/generate-and-filter-runner.ts +6 -3
  62. package/dist/builtin/workflows/builtin/generate-and-filter.ts +3 -2
  63. package/dist/builtin/workflows/builtin/goal-artifacts.ts +1 -1
  64. package/dist/builtin/workflows/builtin/goal-models.ts +39 -39
  65. package/dist/builtin/workflows/builtin/goal-orchestrator-prompts.ts +94 -0
  66. package/dist/builtin/workflows/builtin/goal-prompts.ts +66 -286
  67. package/dist/builtin/workflows/builtin/goal-reducer.ts +1 -1
  68. package/dist/builtin/workflows/builtin/goal-runner.ts +72 -116
  69. package/dist/builtin/workflows/builtin/goal.ts +9 -8
  70. package/dist/builtin/workflows/builtin/index.d.ts +17 -112
  71. package/dist/builtin/workflows/builtin/index.ts +1 -2
  72. package/dist/builtin/workflows/builtin/loop-until-done-prompts.ts +20 -12
  73. package/dist/builtin/workflows/builtin/loop-until-done-runner.ts +3 -0
  74. package/dist/builtin/workflows/builtin/loop-until-done.ts +3 -2
  75. package/dist/builtin/workflows/builtin/open-claude-design-phases.ts +52 -55
  76. package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +45 -52
  77. package/dist/builtin/workflows/builtin/open-claude-design-setup.ts +41 -46
  78. package/dist/builtin/workflows/builtin/open-claude-design-utils.ts +16 -21
  79. package/dist/builtin/workflows/builtin/open-claude-design.ts +2 -1
  80. package/dist/builtin/workflows/builtin/ralph-core.ts +61 -57
  81. package/dist/builtin/workflows/builtin/ralph-forked-prompts.ts +41 -45
  82. package/dist/builtin/workflows/builtin/ralph-models.ts +33 -43
  83. package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +35 -117
  84. package/dist/builtin/workflows/builtin/ralph-runner.ts +81 -108
  85. package/dist/builtin/workflows/builtin/ralph.ts +2 -1
  86. package/dist/builtin/workflows/builtin/shared-prompts.ts +111 -80
  87. package/dist/builtin/workflows/builtin/steering-context.ts +51 -0
  88. package/dist/builtin/workflows/builtin/tournament-prompts.ts +21 -12
  89. package/dist/builtin/workflows/builtin/tournament-runner.ts +3 -0
  90. package/dist/builtin/workflows/builtin/tournament.ts +3 -2
  91. package/dist/builtin/workflows/package.json +2 -2
  92. package/dist/builtin/workflows/skills/create-spec/SKILL.md +1 -1
  93. package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +6 -8
  94. package/dist/builtin/workflows/skills/impeccable/reference/live.md +3 -4
  95. package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +2 -20
  96. package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +4 -42
  97. package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +3 -3
  98. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +2 -3
  99. package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +0 -1
  100. package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +2 -2
  101. package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +4 -4
  102. package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +57 -252
  103. package/dist/builtin/workflows/skills/prompt-engineer/references/advanced_patterns.md +70 -226
  104. package/dist/builtin/workflows/skills/prompt-engineer/references/core_prompting.md +64 -103
  105. package/dist/builtin/workflows/skills/prompt-engineer/references/quality_improvement.md +81 -155
  106. package/dist/builtin/workflows/src/authoring.d.ts +5 -1
  107. package/dist/builtin/workflows/src/durable/backend.ts +68 -9
  108. package/dist/builtin/workflows/src/durable/boundary-lifecycle.ts +148 -0
  109. package/dist/builtin/workflows/src/durable/boundary-topology.ts +420 -0
  110. package/dist/builtin/workflows/src/durable/child-invocation.ts +14 -0
  111. package/dist/builtin/workflows/src/durable/child-primitive.ts +74 -44
  112. package/dist/builtin/workflows/src/durable/completed-catalog-stage-groups.ts +250 -0
  113. package/dist/builtin/workflows/src/durable/completed-catalog.ts +205 -131
  114. package/dist/builtin/workflows/src/durable/completed-inspection.ts +8 -2
  115. package/dist/builtin/workflows/src/durable/completed-subtree.ts +31 -0
  116. package/dist/builtin/workflows/src/durable/dbos-backend.ts +28 -24
  117. package/dist/builtin/workflows/src/durable/dbos-envelope.ts +130 -3
  118. package/dist/builtin/workflows/src/durable/dbos-metadata.ts +18 -0
  119. package/dist/builtin/workflows/src/durable/scoped-backend.ts +64 -17
  120. package/dist/builtin/workflows/src/durable/stage-primitive.ts +60 -60
  121. package/dist/builtin/workflows/src/durable/stage-topology-validation.ts +234 -0
  122. package/dist/builtin/workflows/src/durable/stage-topology.ts +53 -0
  123. package/dist/builtin/workflows/src/durable/tool-failure-checkpoint.ts +49 -0
  124. package/dist/builtin/workflows/src/durable/tool-outcome.ts +120 -0
  125. package/dist/builtin/workflows/src/durable/tool-primitive.ts +367 -58
  126. package/dist/builtin/workflows/src/durable/types.ts +97 -0
  127. package/dist/builtin/workflows/src/durable/ui-primitive.ts +46 -0
  128. package/dist/builtin/workflows/src/durable/workflow-child-result.ts +58 -0
  129. package/dist/builtin/workflows/src/engine/options.ts +1 -0
  130. package/dist/builtin/workflows/src/engine/primitives/workflow.ts +19 -10
  131. package/dist/builtin/workflows/src/engine/run-durable-finalize.ts +11 -1
  132. package/dist/builtin/workflows/src/engine/run-durable-topology.ts +190 -18
  133. package/dist/builtin/workflows/src/engine/run-terminal-event.ts +37 -0
  134. package/dist/builtin/workflows/src/engine/run-terminal-failure.ts +50 -0
  135. package/dist/builtin/workflows/src/engine/run-tool-execution-tracker.ts +152 -0
  136. package/dist/builtin/workflows/src/engine/run-tool-node-lifecycle.ts +87 -0
  137. package/dist/builtin/workflows/src/engine/run.ts +111 -110
  138. package/dist/builtin/workflows/src/engine/runtime.ts +15 -2
  139. package/dist/builtin/workflows/src/extension/extension-factory.ts +1 -0
  140. package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +11 -0
  141. package/dist/builtin/workflows/src/extension/index.bundle.mjs +6599 -4776
  142. package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +16 -5
  143. package/dist/builtin/workflows/src/extension/render-result.ts +16 -2
  144. package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +3 -0
  145. package/dist/builtin/workflows/src/extension/runtime.ts +4 -0
  146. package/dist/builtin/workflows/src/extension/wiring.ts +3 -1
  147. package/dist/builtin/workflows/src/extension/workflow-command-surfaces.ts +1 -0
  148. package/dist/builtin/workflows/src/extension/workflow-durable-resume-command.ts +9 -3
  149. package/dist/builtin/workflows/src/extension/workflow-module-loader.ts +18 -3
  150. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +27 -9
  151. package/dist/builtin/workflows/src/extension/workflow-status-summary.ts +43 -0
  152. package/dist/builtin/workflows/src/extension/workflow-targets.ts +34 -30
  153. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +12 -5
  154. package/dist/builtin/workflows/src/extension/workflow-tool-send.ts +162 -63
  155. package/dist/builtin/workflows/src/runs/background/run-inspect.ts +7 -1
  156. package/dist/builtin/workflows/src/runs/background/status.ts +18 -8
  157. package/dist/builtin/workflows/src/runs/background/workflow-lifecycle-aggregate.ts +3 -11
  158. package/dist/builtin/workflows/src/runs/foreground/executor-child-boundary.ts +24 -21
  159. package/dist/builtin/workflows/src/runs/foreground/executor-hil.ts +1 -1
  160. package/dist/builtin/workflows/src/runs/foreground/executor-lifecycle.ts +30 -13
  161. package/dist/builtin/workflows/src/runs/foreground/executor-prompt-nodes.ts +102 -53
  162. package/dist/builtin/workflows/src/runs/foreground/executor-stage-call.ts +13 -5
  163. package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +26 -8
  164. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +11 -4
  165. package/dist/builtin/workflows/src/runs/foreground/executor-stage-types.ts +4 -1
  166. package/dist/builtin/workflows/src/runs/foreground/executor-types.ts +7 -1
  167. package/dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts +35 -1
  168. package/dist/builtin/workflows/src/runs/foreground/stage-control-registry.ts +136 -17
  169. package/dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts +12 -4
  170. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +35 -42
  171. package/dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts +5 -1
  172. package/dist/builtin/workflows/src/runs/foreground/stage-runner-pause.ts +195 -0
  173. package/dist/builtin/workflows/src/runs/foreground/stage-runner-session-options.ts +0 -13
  174. package/dist/builtin/workflows/src/runs/foreground/stage-runner-types.ts +14 -2
  175. package/dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts +3 -143
  176. package/dist/builtin/workflows/src/sdk-surface.ts +1 -1
  177. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +6 -11
  178. package/dist/builtin/workflows/src/shared/authoring-contract-stage.ts +6 -11
  179. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +57 -6
  180. package/dist/builtin/workflows/src/shared/authoring-contract-ui.ts +76 -11
  181. package/dist/builtin/workflows/src/shared/expanded-workflow-graph.ts +206 -116
  182. package/dist/builtin/workflows/src/shared/intercom-group.ts +17 -10
  183. package/dist/builtin/workflows/src/shared/persistence-restore-helpers.ts +30 -0
  184. package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +5 -0
  185. package/dist/builtin/workflows/src/shared/render-inputs-schema.ts +3 -3
  186. package/dist/builtin/workflows/src/shared/store-factory.ts +2 -0
  187. package/dist/builtin/workflows/src/shared/store-internal.ts +8 -0
  188. package/dist/builtin/workflows/src/shared/store-public-types.ts +8 -0
  189. package/dist/builtin/workflows/src/shared/store-run-methods.ts +9 -0
  190. package/dist/builtin/workflows/src/shared/store-stage-methods.ts +2 -0
  191. package/dist/builtin/workflows/src/shared/store-tool-node-methods.ts +46 -0
  192. package/dist/builtin/workflows/src/shared/store-types.ts +34 -0
  193. package/dist/builtin/workflows/src/shared/types.ts +14 -24
  194. package/dist/builtin/workflows/src/shared/workflow-failures-classifier.ts +11 -5
  195. package/dist/builtin/workflows/src/shared/workflow-failures-signals.ts +58 -0
  196. package/dist/builtin/workflows/src/shared/workflow-run-ownership.ts +53 -0
  197. package/dist/builtin/workflows/src/tui/graph-view-input.ts +2 -8
  198. package/dist/builtin/workflows/src/tui/graph-view-render-helpers.ts +11 -4
  199. package/dist/builtin/workflows/src/tui/graph-view-render.ts +1 -0
  200. package/dist/builtin/workflows/src/tui/graph-view-state.ts +27 -9
  201. package/dist/builtin/workflows/src/tui/graph-view-types.ts +4 -3
  202. package/dist/builtin/workflows/src/tui/node-card.ts +4 -3
  203. package/dist/builtin/workflows/src/tui/overlay-adapter.ts +0 -4
  204. package/dist/builtin/workflows/src/tui/run-detail.ts +53 -17
  205. package/dist/builtin/workflows/src/tui/session-list.ts +8 -4
  206. package/dist/builtin/workflows/src/tui/stage-chat-view-render-helpers.ts +12 -0
  207. package/dist/builtin/workflows/src/tui/stage-chat-view-render-settings.ts +21 -1
  208. package/dist/builtin/workflows/src/tui/stage-chat-view-state.ts +3 -19
  209. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +4 -2
  210. package/dist/builtin/workflows/src/tui/switcher.ts +13 -3
  211. package/dist/builtin/workflows/src/tui/workflow-attach-pane-handle.ts +1 -1
  212. package/dist/builtin/workflows/src/tui/workflow-attach-pane-types.ts +0 -9
  213. package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +16 -49
  214. package/dist/builtin/workflows/src/tui/workflow-status.ts +7 -0
  215. package/dist/builtin/workflows/src/workflows/identity.ts +1 -1
  216. package/dist/cli/args.d.ts +0 -1
  217. package/dist/cli/args.d.ts.map +1 -1
  218. package/dist/cli/args.js +1 -20
  219. package/dist/cli/args.js.map +1 -1
  220. package/dist/cli/config-selector.js +1 -1
  221. package/dist/cli/config-selector.js.map +1 -1
  222. package/dist/cli/list-models.d.ts.map +1 -1
  223. package/dist/cli/list-models.js +1 -2
  224. package/dist/cli/list-models.js.map +1 -1
  225. package/dist/cli/session-picker.d.ts.map +1 -1
  226. package/dist/cli/session-picker.js +2 -1
  227. package/dist/cli/session-picker.js.map +1 -1
  228. package/dist/cli/startup-ui.js +2 -2
  229. package/dist/cli/startup-ui.js.map +1 -1
  230. package/dist/config-self-update.js +1 -1
  231. package/dist/config-self-update.js.map +1 -1
  232. package/dist/config.d.ts +2 -0
  233. package/dist/config.d.ts.map +1 -1
  234. package/dist/config.js +34 -10
  235. package/dist/config.js.map +1 -1
  236. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  237. package/dist/core/agent-session-accessors.js +2 -1
  238. package/dist/core/agent-session-accessors.js.map +1 -1
  239. package/dist/core/agent-session-auto-compaction.d.ts +4 -3
  240. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  241. package/dist/core/agent-session-auto-compaction.js +55 -59
  242. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  243. package/dist/core/agent-session-bash.d.ts +9 -6
  244. package/dist/core/agent-session-bash.d.ts.map +1 -1
  245. package/dist/core/agent-session-bash.js +32 -13
  246. package/dist/core/agent-session-bash.js.map +1 -1
  247. package/dist/core/agent-session-compaction.d.ts +11 -1
  248. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  249. package/dist/core/agent-session-compaction.js +87 -19
  250. package/dist/core/agent-session-compaction.js.map +1 -1
  251. package/dist/core/agent-session-custom-message-commit.d.ts +14 -0
  252. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -0
  253. package/dist/core/agent-session-custom-message-commit.js +141 -0
  254. package/dist/core/agent-session-custom-message-commit.js.map +1 -0
  255. package/dist/core/agent-session-delivery-forwarding.d.ts +9 -0
  256. package/dist/core/agent-session-delivery-forwarding.d.ts.map +1 -0
  257. package/dist/core/agent-session-delivery-forwarding.js +36 -0
  258. package/dist/core/agent-session-delivery-forwarding.js.map +1 -0
  259. package/dist/core/agent-session-events.d.ts +1 -1
  260. package/dist/core/agent-session-events.d.ts.map +1 -1
  261. package/dist/core/agent-session-events.js +45 -14
  262. package/dist/core/agent-session-events.js.map +1 -1
  263. package/dist/core/agent-session-extension-bindings.d.ts +2 -6
  264. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  265. package/dist/core/agent-session-extension-bindings.js +18 -11
  266. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  267. package/dist/core/agent-session-message-queue.d.ts +5 -2
  268. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  269. package/dist/core/agent-session-message-queue.js +91 -97
  270. package/dist/core/agent-session-message-queue.js.map +1 -1
  271. package/dist/core/agent-session-methods.d.ts +47 -39
  272. package/dist/core/agent-session-methods.d.ts.map +1 -1
  273. package/dist/core/agent-session-methods.js.map +1 -1
  274. package/dist/core/agent-session-models.d.ts +2 -38
  275. package/dist/core/agent-session-models.d.ts.map +1 -1
  276. package/dist/core/agent-session-models.js +5 -147
  277. package/dist/core/agent-session-models.js.map +1 -1
  278. package/dist/core/agent-session-persistent-custom-messages.d.ts +47 -0
  279. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -0
  280. package/dist/core/agent-session-persistent-custom-messages.js +267 -0
  281. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -0
  282. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  283. package/dist/core/agent-session-post-tool-compaction.js +34 -9
  284. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  285. package/dist/core/agent-session-prompt.d.ts +2 -0
  286. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  287. package/dist/core/agent-session-prompt.js +42 -16
  288. package/dist/core/agent-session-prompt.js.map +1 -1
  289. package/dist/core/agent-session-queue-pause.d.ts +10 -0
  290. package/dist/core/agent-session-queue-pause.d.ts.map +1 -0
  291. package/dist/core/agent-session-queue-pause.js +86 -0
  292. package/dist/core/agent-session-queue-pause.js.map +1 -0
  293. package/dist/core/agent-session-retry.d.ts +0 -11
  294. package/dist/core/agent-session-retry.d.ts.map +1 -1
  295. package/dist/core/agent-session-retry.js +8 -57
  296. package/dist/core/agent-session-retry.js.map +1 -1
  297. package/dist/core/agent-session-runtime-auth.d.ts +6 -0
  298. package/dist/core/agent-session-runtime-auth.d.ts.map +1 -0
  299. package/dist/core/agent-session-runtime-auth.js +26 -0
  300. package/dist/core/agent-session-runtime-auth.js.map +1 -0
  301. package/dist/core/agent-session-runtime.d.ts +13 -2
  302. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  303. package/dist/core/agent-session-runtime.js +32 -6
  304. package/dist/core/agent-session-runtime.js.map +1 -1
  305. package/dist/core/agent-session-services.d.ts +0 -2
  306. package/dist/core/agent-session-services.d.ts.map +1 -1
  307. package/dist/core/agent-session-services.js +6 -7
  308. package/dist/core/agent-session-services.js.map +1 -1
  309. package/dist/core/agent-session-state.d.ts.map +1 -1
  310. package/dist/core/agent-session-state.js +3 -0
  311. package/dist/core/agent-session-state.js.map +1 -1
  312. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  313. package/dist/core/agent-session-tool-hooks.js +6 -1
  314. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  315. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  316. package/dist/core/agent-session-tool-registry.js +2 -18
  317. package/dist/core/agent-session-tool-registry.js.map +1 -1
  318. package/dist/core/agent-session-transfer.d.ts +4 -0
  319. package/dist/core/agent-session-transfer.d.ts.map +1 -0
  320. package/dist/core/agent-session-transfer.js +71 -0
  321. package/dist/core/agent-session-transfer.js.map +1 -0
  322. package/dist/core/agent-session-tree.js +1 -1
  323. package/dist/core/agent-session-tree.js.map +1 -1
  324. package/dist/core/agent-session-types.d.ts +5 -11
  325. package/dist/core/agent-session-types.d.ts.map +1 -1
  326. package/dist/core/agent-session-types.js +0 -3
  327. package/dist/core/agent-session-types.js.map +1 -1
  328. package/dist/core/agent-session.d.ts +12 -2
  329. package/dist/core/agent-session.d.ts.map +1 -1
  330. package/dist/core/agent-session.js +8 -2
  331. package/dist/core/agent-session.js.map +1 -1
  332. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  333. package/dist/core/atomic-guide-command.js +31 -33
  334. package/dist/core/atomic-guide-command.js.map +1 -1
  335. package/dist/core/auth-storage.js +2 -2
  336. package/dist/core/auth-storage.js.map +1 -1
  337. package/dist/core/bash-executor.d.ts +5 -3
  338. package/dist/core/bash-executor.d.ts.map +1 -1
  339. package/dist/core/bash-executor.js +5 -4
  340. package/dist/core/bash-executor.js.map +1 -1
  341. package/dist/core/builtin-packages.d.ts.map +1 -1
  342. package/dist/core/builtin-packages.js +0 -6
  343. package/dist/core/builtin-packages.js.map +1 -1
  344. package/dist/core/compaction/branch-summarization.d.ts +8 -3
  345. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  346. package/dist/core/compaction/branch-summarization.js +17 -6
  347. package/dist/core/compaction/branch-summarization.js.map +1 -1
  348. package/dist/core/compaction/compaction-boundary.d.ts +18 -1
  349. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  350. package/dist/core/compaction/compaction-boundary.js +2 -2
  351. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  352. package/dist/core/compaction/compaction-runner.d.ts +61 -6
  353. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  354. package/dist/core/compaction/compaction-runner.js +242 -18
  355. package/dist/core/compaction/compaction-runner.js.map +1 -1
  356. package/dist/core/compaction/compaction-types.d.ts +53 -2
  357. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  358. package/dist/core/compaction/compaction-types.js.map +1 -1
  359. package/dist/core/compaction/fallback-planner.d.ts +64 -0
  360. package/dist/core/compaction/fallback-planner.d.ts.map +1 -0
  361. package/dist/core/compaction/fallback-planner.js +75 -0
  362. package/dist/core/compaction/fallback-planner.js.map +1 -0
  363. package/dist/core/compaction/index.d.ts +3 -0
  364. package/dist/core/compaction/index.d.ts.map +1 -1
  365. package/dist/core/compaction/index.js +3 -0
  366. package/dist/core/compaction/index.js.map +1 -1
  367. package/dist/core/compaction/planner-outcome.d.ts +86 -0
  368. package/dist/core/compaction/planner-outcome.d.ts.map +1 -0
  369. package/dist/core/compaction/planner-outcome.js +122 -0
  370. package/dist/core/compaction/planner-outcome.js.map +1 -0
  371. package/dist/core/compaction/range-planner-diagnostics.d.ts +58 -6
  372. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  373. package/dist/core/compaction/range-planner-diagnostics.js +69 -31
  374. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  375. package/dist/core/compaction/range-planner.d.ts +36 -8
  376. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  377. package/dist/core/compaction/range-planner.js +136 -51
  378. package/dist/core/compaction/range-planner.js.map +1 -1
  379. package/dist/core/compaction/region-trimming.d.ts +34 -0
  380. package/dist/core/compaction/region-trimming.d.ts.map +1 -0
  381. package/dist/core/compaction/region-trimming.js +73 -0
  382. package/dist/core/compaction/region-trimming.js.map +1 -0
  383. package/dist/core/compaction/transcript-serialization.d.ts +8 -1
  384. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  385. package/dist/core/compaction/transcript-serialization.js +78 -27
  386. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  387. package/dist/core/context-tool-pairing.d.ts +19 -0
  388. package/dist/core/context-tool-pairing.d.ts.map +1 -0
  389. package/dist/core/context-tool-pairing.js +50 -0
  390. package/dist/core/context-tool-pairing.js.map +1 -0
  391. package/dist/core/diagnostics.d.ts +8 -0
  392. package/dist/core/diagnostics.d.ts.map +1 -1
  393. package/dist/core/diagnostics.js.map +1 -1
  394. package/dist/core/extensions/context-types.d.ts +3 -0
  395. package/dist/core/extensions/context-types.d.ts.map +1 -1
  396. package/dist/core/extensions/context-types.js.map +1 -1
  397. package/dist/core/extensions/index.d.ts +2 -0
  398. package/dist/core/extensions/index.d.ts.map +1 -1
  399. package/dist/core/extensions/index.js.map +1 -1
  400. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  401. package/dist/core/extensions/loader-api.js +48 -27
  402. package/dist/core/extensions/loader-api.js.map +1 -1
  403. package/dist/core/extensions/loader-runtime.d.ts +2 -4
  404. package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
  405. package/dist/core/extensions/loader-runtime.js +199 -18
  406. package/dist/core/extensions/loader-runtime.js.map +1 -1
  407. package/dist/core/extensions/message-types.d.ts +7 -4
  408. package/dist/core/extensions/message-types.d.ts.map +1 -1
  409. package/dist/core/extensions/message-types.js.map +1 -1
  410. package/dist/core/extensions/provider-types.d.ts +9 -4
  411. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  412. package/dist/core/extensions/provider-types.js.map +1 -1
  413. package/dist/core/extensions/runner-context.d.ts +2 -0
  414. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  415. package/dist/core/extensions/runner-context.js +4 -0
  416. package/dist/core/extensions/runner-context.js.map +1 -1
  417. package/dist/core/extensions/runner.d.ts +1 -0
  418. package/dist/core/extensions/runner.d.ts.map +1 -1
  419. package/dist/core/extensions/runner.js +28 -20
  420. package/dist/core/extensions/runner.js.map +1 -1
  421. package/dist/core/extensions/runtime-types.d.ts +25 -0
  422. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  423. package/dist/core/extensions/runtime-types.js.map +1 -1
  424. package/dist/core/extensions/tool-types.d.ts +7 -3
  425. package/dist/core/extensions/tool-types.d.ts.map +1 -1
  426. package/dist/core/extensions/tool-types.js.map +1 -1
  427. package/dist/core/extensions/ui-types.d.ts +14 -4
  428. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  429. package/dist/core/extensions/ui-types.js.map +1 -1
  430. package/dist/core/fallback-models.d.ts +37 -0
  431. package/dist/core/fallback-models.d.ts.map +1 -0
  432. package/dist/core/fallback-models.js +48 -0
  433. package/dist/core/fallback-models.js.map +1 -0
  434. package/dist/core/flattened-tool-arguments.d.ts +4 -7
  435. package/dist/core/flattened-tool-arguments.d.ts.map +1 -1
  436. package/dist/core/flattened-tool-arguments.js +4 -7
  437. package/dist/core/flattened-tool-arguments.js.map +1 -1
  438. package/dist/core/http-dispatcher.d.ts.map +1 -1
  439. package/dist/core/http-dispatcher.js +0 -5
  440. package/dist/core/http-dispatcher.js.map +1 -1
  441. package/dist/core/messages.d.ts +14 -2
  442. package/dist/core/messages.d.ts.map +1 -1
  443. package/dist/core/messages.js +28 -4
  444. package/dist/core/messages.js.map +1 -1
  445. package/dist/core/model-capabilities.d.ts +18 -0
  446. package/dist/core/model-capabilities.d.ts.map +1 -0
  447. package/dist/core/model-capabilities.js +23 -0
  448. package/dist/core/model-capabilities.js.map +1 -0
  449. package/dist/core/model-registry-auth.d.ts.map +1 -1
  450. package/dist/core/model-registry-auth.js +0 -2
  451. package/dist/core/model-registry-auth.js.map +1 -1
  452. package/dist/core/model-registry-builtins.d.ts +0 -2
  453. package/dist/core/model-registry-builtins.d.ts.map +1 -1
  454. package/dist/core/model-registry-builtins.js +9 -76
  455. package/dist/core/model-registry-builtins.js.map +1 -1
  456. package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
  457. package/dist/core/model-registry-custom-loader.js +1 -12
  458. package/dist/core/model-registry-custom-loader.js.map +1 -1
  459. package/dist/core/model-registry-dynamic.d.ts.map +1 -1
  460. package/dist/core/model-registry-dynamic.js +3 -15
  461. package/dist/core/model-registry-dynamic.js.map +1 -1
  462. package/dist/core/model-registry-extension-refresh.d.ts +23 -0
  463. package/dist/core/model-registry-extension-refresh.d.ts.map +1 -0
  464. package/dist/core/model-registry-extension-refresh.js +32 -0
  465. package/dist/core/model-registry-extension-refresh.js.map +1 -0
  466. package/dist/core/model-registry-schemas.d.ts +118 -9
  467. package/dist/core/model-registry-schemas.d.ts.map +1 -1
  468. package/dist/core/model-registry-schemas.js +10 -3
  469. package/dist/core/model-registry-schemas.js.map +1 -1
  470. package/dist/core/model-registry-types.d.ts +5 -5
  471. package/dist/core/model-registry-types.d.ts.map +1 -1
  472. package/dist/core/model-registry-types.js.map +1 -1
  473. package/dist/core/model-registry-validation.d.ts +7 -0
  474. package/dist/core/model-registry-validation.d.ts.map +1 -0
  475. package/dist/core/model-registry-validation.js +12 -0
  476. package/dist/core/model-registry-validation.js.map +1 -0
  477. package/dist/core/model-registry.d.ts +5 -3
  478. package/dist/core/model-registry.d.ts.map +1 -1
  479. package/dist/core/model-registry.js +34 -33
  480. package/dist/core/model-registry.js.map +1 -1
  481. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  482. package/dist/core/model-resolver-defaults.js +0 -1
  483. package/dist/core/model-resolver-defaults.js.map +1 -1
  484. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  485. package/dist/core/model-resolver-initial.js +9 -0
  486. package/dist/core/model-resolver-initial.js.map +1 -1
  487. package/dist/core/model-resolver-patterns.d.ts.map +1 -1
  488. package/dist/core/model-resolver-patterns.js +0 -2
  489. package/dist/core/model-resolver-patterns.js.map +1 -1
  490. package/dist/core/model-resolver-scope.d.ts +2 -0
  491. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  492. package/dist/core/model-resolver-scope.js +18 -4
  493. package/dist/core/model-resolver-scope.js.map +1 -1
  494. package/dist/core/model-resolver-types.d.ts +2 -0
  495. package/dist/core/model-resolver-types.d.ts.map +1 -1
  496. package/dist/core/model-resolver-types.js.map +1 -1
  497. package/dist/core/oauth-provider-bridge.d.ts +21 -0
  498. package/dist/core/oauth-provider-bridge.d.ts.map +1 -1
  499. package/dist/core/oauth-provider-bridge.js +68 -7
  500. package/dist/core/oauth-provider-bridge.js.map +1 -1
  501. package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
  502. package/dist/core/package-manager-auto-resources.js +12 -4
  503. package/dist/core/package-manager-auto-resources.js.map +1 -1
  504. package/dist/core/package-manager-resolver.d.ts.map +1 -1
  505. package/dist/core/package-manager-resolver.js +42 -11
  506. package/dist/core/package-manager-resolver.js.map +1 -1
  507. package/dist/core/package-manager-types.d.ts +2 -0
  508. package/dist/core/package-manager-types.d.ts.map +1 -1
  509. package/dist/core/package-manager-types.js.map +1 -1
  510. package/dist/core/package-manager.d.ts +1 -1
  511. package/dist/core/package-manager.d.ts.map +1 -1
  512. package/dist/core/package-manager.js.map +1 -1
  513. package/dist/core/remote-catalog-provider.d.ts +1 -1
  514. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  515. package/dist/core/remote-catalog-provider.js +17 -11
  516. package/dist/core/remote-catalog-provider.js.map +1 -1
  517. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  518. package/dist/core/resource-loader-assets.js +30 -4
  519. package/dist/core/resource-loader-assets.js.map +1 -1
  520. package/dist/core/resource-loader-context-files.d.ts.map +1 -1
  521. package/dist/core/resource-loader-context-files.js +3 -1
  522. package/dist/core/resource-loader-context-files.js.map +1 -1
  523. package/dist/core/resource-loader-core.d.ts +2 -1
  524. package/dist/core/resource-loader-core.d.ts.map +1 -1
  525. package/dist/core/resource-loader-core.js +3 -0
  526. package/dist/core/resource-loader-core.js.map +1 -1
  527. package/dist/core/resource-loader-extensions.d.ts +1 -0
  528. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  529. package/dist/core/resource-loader-extensions.js +120 -7
  530. package/dist/core/resource-loader-extensions.js.map +1 -1
  531. package/dist/core/resource-loader-package-resources.d.ts.map +1 -1
  532. package/dist/core/resource-loader-package-resources.js +14 -1
  533. package/dist/core/resource-loader-package-resources.js.map +1 -1
  534. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  535. package/dist/core/resource-loader-reload.js +2 -1
  536. package/dist/core/resource-loader-reload.js.map +1 -1
  537. package/dist/core/resource-loader-source-info.d.ts.map +1 -1
  538. package/dist/core/resource-loader-source-info.js +6 -3
  539. package/dist/core/resource-loader-source-info.js.map +1 -1
  540. package/dist/core/sdk-types.d.ts +11 -10
  541. package/dist/core/sdk-types.d.ts.map +1 -1
  542. package/dist/core/sdk-types.js.map +1 -1
  543. package/dist/core/sdk.d.ts +1 -0
  544. package/dist/core/sdk.d.ts.map +1 -1
  545. package/dist/core/sdk.js +13 -84
  546. package/dist/core/sdk.js.map +1 -1
  547. package/dist/core/session-manager-core.d.ts +3 -3
  548. package/dist/core/session-manager-core.d.ts.map +1 -1
  549. package/dist/core/session-manager-core.js +18 -25
  550. package/dist/core/session-manager-core.js.map +1 -1
  551. package/dist/core/session-manager-entries.d.ts +2 -5
  552. package/dist/core/session-manager-entries.d.ts.map +1 -1
  553. package/dist/core/session-manager-entries.js +2 -8
  554. package/dist/core/session-manager-entries.js.map +1 -1
  555. package/dist/core/session-manager-history.d.ts +3 -3
  556. package/dist/core/session-manager-history.d.ts.map +1 -1
  557. package/dist/core/session-manager-history.js +49 -27
  558. package/dist/core/session-manager-history.js.map +1 -1
  559. package/dist/core/session-manager-storage.d.ts +6 -0
  560. package/dist/core/session-manager-storage.d.ts.map +1 -1
  561. package/dist/core/session-manager-storage.js +38 -5
  562. package/dist/core/session-manager-storage.js.map +1 -1
  563. package/dist/core/session-manager-types.d.ts +6 -6
  564. package/dist/core/session-manager-types.d.ts.map +1 -1
  565. package/dist/core/session-manager-types.js.map +1 -1
  566. package/dist/core/session-manager.d.ts +1 -1
  567. package/dist/core/session-manager.d.ts.map +1 -1
  568. package/dist/core/session-manager.js.map +1 -1
  569. package/dist/core/settings-manager-basic-accessors.d.ts +0 -4
  570. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  571. package/dist/core/settings-manager-basic-accessors.js +0 -50
  572. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  573. package/dist/core/settings-manager-core.d.ts +2 -4
  574. package/dist/core/settings-manager-core.d.ts.map +1 -1
  575. package/dist/core/settings-manager-core.js +5 -51
  576. package/dist/core/settings-manager-core.js.map +1 -1
  577. package/dist/core/settings-manager.d.ts +1 -1
  578. package/dist/core/settings-manager.d.ts.map +1 -1
  579. package/dist/core/settings-manager.js.map +1 -1
  580. package/dist/core/settings-storage.d.ts +3 -1
  581. package/dist/core/settings-storage.d.ts.map +1 -1
  582. package/dist/core/settings-storage.js +22 -0
  583. package/dist/core/settings-storage.js.map +1 -1
  584. package/dist/core/settings-types.d.ts +2 -4
  585. package/dist/core/settings-types.d.ts.map +1 -1
  586. package/dist/core/settings-types.js.map +1 -1
  587. package/dist/core/slash-commands.d.ts.map +1 -1
  588. package/dist/core/slash-commands.js +69 -23
  589. package/dist/core/slash-commands.js.map +1 -1
  590. package/dist/core/source-info.d.ts +3 -1
  591. package/dist/core/source-info.d.ts.map +1 -1
  592. package/dist/core/source-info.js +2 -0
  593. package/dist/core/source-info.js.map +1 -1
  594. package/dist/core/system-prompt.d.ts.map +1 -1
  595. package/dist/core/system-prompt.js +11 -0
  596. package/dist/core/system-prompt.js.map +1 -1
  597. package/dist/core/tools/ask-user-question/ask-user-question.js +1 -1
  598. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -1
  599. package/dist/core/tools/bash-session-environment.d.ts +13 -0
  600. package/dist/core/tools/bash-session-environment.d.ts.map +1 -0
  601. package/dist/core/tools/bash-session-environment.js +35 -0
  602. package/dist/core/tools/bash-session-environment.js.map +1 -0
  603. package/dist/core/tools/bash.d.ts +4 -1
  604. package/dist/core/tools/bash.d.ts.map +1 -1
  605. package/dist/core/tools/bash.js +16 -8
  606. package/dist/core/tools/bash.js.map +1 -1
  607. package/dist/core/tools/tool-definition-wrapper.d.ts +3 -0
  608. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  609. package/dist/core/tools/tool-definition-wrapper.js +10 -2
  610. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  611. package/dist/extensions/index.js +1 -1
  612. package/dist/extensions/index.js.map +1 -1
  613. package/dist/extensions/llama/provider.d.ts +3 -2
  614. package/dist/extensions/llama/provider.d.ts.map +1 -1
  615. package/dist/extensions/llama/provider.js +9 -3
  616. package/dist/extensions/llama/provider.js.map +1 -1
  617. package/dist/index-extensions.d.ts +1 -1
  618. package/dist/index-extensions.d.ts.map +1 -1
  619. package/dist/index-extensions.js.map +1 -1
  620. package/dist/index.d.ts +2 -3
  621. package/dist/index.d.ts.map +1 -1
  622. package/dist/index.js +1 -2
  623. package/dist/index.js.map +1 -1
  624. package/dist/main-session-options.d.ts.map +1 -1
  625. package/dist/main-session-options.js +0 -4
  626. package/dist/main-session-options.js.map +1 -1
  627. package/dist/main-session.d.ts.map +1 -1
  628. package/dist/main-session.js +2 -1
  629. package/dist/main-session.js.map +1 -1
  630. package/dist/main.d.ts.map +1 -1
  631. package/dist/main.js +1 -17
  632. package/dist/main.js.map +1 -1
  633. package/dist/modes/index.d.ts +1 -1
  634. package/dist/modes/index.d.ts.map +1 -1
  635. package/dist/modes/index.js.map +1 -1
  636. package/dist/modes/interactive/chat-input-actions.d.ts +1 -1
  637. package/dist/modes/interactive/chat-input-actions.d.ts.map +1 -1
  638. package/dist/modes/interactive/chat-input-actions.js +14 -96
  639. package/dist/modes/interactive/chat-input-actions.js.map +1 -1
  640. package/dist/modes/interactive/components/atomic-banner.d.ts +9 -8
  641. package/dist/modes/interactive/components/atomic-banner.d.ts.map +1 -1
  642. package/dist/modes/interactive/components/atomic-banner.js +68 -24
  643. package/dist/modes/interactive/components/atomic-banner.js.map +1 -1
  644. package/dist/modes/interactive/components/atomic-working-status.d.ts +52 -0
  645. package/dist/modes/interactive/components/atomic-working-status.d.ts.map +1 -0
  646. package/dist/modes/interactive/components/atomic-working-status.js +202 -0
  647. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -0
  648. package/dist/modes/interactive/components/chat-message-renderer.js +1 -1
  649. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  650. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  651. package/dist/modes/interactive/components/chat-session-host-actions.js +99 -7
  652. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  653. package/dist/modes/interactive/components/chat-session-host-editor.js +3 -3
  654. package/dist/modes/interactive/components/chat-session-host-editor.js.map +1 -1
  655. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/chat-session-host-events.js +52 -9
  657. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  658. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  659. package/dist/modes/interactive/components/chat-session-host-rendering.js +23 -7
  660. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  661. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +2 -0
  662. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  663. package/dist/modes/interactive/components/chat-session-host-runtime.js +67 -18
  664. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  665. package/dist/modes/interactive/components/chat-session-host-state.d.ts +9 -0
  666. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  667. package/dist/modes/interactive/components/chat-session-host-state.js +5 -0
  668. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  669. package/dist/modes/interactive/components/chat-session-host-types.d.ts +10 -0
  670. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  671. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  672. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  673. package/dist/modes/interactive/components/compaction-boundary-message.js +2 -1
  674. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  675. package/dist/modes/interactive/components/custom-message.d.ts +3 -1
  676. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  677. package/dist/modes/interactive/components/custom-message.js +9 -2
  678. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  679. package/dist/modes/interactive/components/extension-editor.d.ts +3 -2
  680. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  681. package/dist/modes/interactive/components/extension-editor.js +14 -43
  682. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  683. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  684. package/dist/modes/interactive/components/scoped-models-selector.js +18 -13
  685. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  686. package/dist/modes/interactive/components/startup-identity.d.ts +22 -0
  687. package/dist/modes/interactive/components/startup-identity.d.ts.map +1 -0
  688. package/dist/modes/interactive/components/startup-identity.js +58 -0
  689. package/dist/modes/interactive/components/startup-identity.js.map +1 -0
  690. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  691. package/dist/modes/interactive/components/tree-selector-content.js +0 -6
  692. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  693. package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
  694. package/dist/modes/interactive/components/tree-selector-model.js +0 -1
  695. package/dist/modes/interactive/components/tree-selector-model.js.map +1 -1
  696. package/dist/modes/interactive/components/working-status.d.ts +5 -11
  697. package/dist/modes/interactive/components/working-status.d.ts.map +1 -1
  698. package/dist/modes/interactive/components/working-status.js +14 -15
  699. package/dist/modes/interactive/components/working-status.js.map +1 -1
  700. package/dist/modes/interactive/external-editor.d.ts +23 -0
  701. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  702. package/dist/modes/interactive/external-editor.js +120 -0
  703. package/dist/modes/interactive/external-editor.js.map +1 -0
  704. package/dist/modes/interactive/interactive-agent-events.js +25 -20
  705. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  706. package/dist/modes/interactive/interactive-auth-login.js +16 -6
  707. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  708. package/dist/modes/interactive/interactive-auth-routing.js +3 -0
  709. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  710. package/dist/modes/interactive/interactive-bash-compact.d.ts +2 -1
  711. package/dist/modes/interactive/interactive-bash-compact.d.ts.map +1 -1
  712. package/dist/modes/interactive/interactive-bash-compact.js +8 -0
  713. package/dist/modes/interactive/interactive-bash-compact.js.map +1 -1
  714. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  715. package/dist/modes/interactive/interactive-deferred-startup.js +49 -19
  716. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  717. package/dist/modes/interactive/interactive-editor-actions.js +4 -3
  718. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  719. package/dist/modes/interactive/interactive-extension-dialogs.js +1 -1
  720. package/dist/modes/interactive/interactive-extension-dialogs.js.map +1 -1
  721. package/dist/modes/interactive/interactive-extension-runtime.js +3 -2
  722. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  723. package/dist/modes/interactive/interactive-initial-session-binding.d.ts +4 -0
  724. package/dist/modes/interactive/interactive-initial-session-binding.d.ts.map +1 -0
  725. package/dist/modes/interactive/interactive-initial-session-binding.js +23 -0
  726. package/dist/modes/interactive/interactive-initial-session-binding.js.map +1 -0
  727. package/dist/modes/interactive/interactive-input-handling.d.ts +2 -1
  728. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  729. package/dist/modes/interactive/interactive-input-handling.js +27 -51
  730. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  731. package/dist/modes/interactive/interactive-mode-base.d.ts +11 -7
  732. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  733. package/dist/modes/interactive/interactive-mode-base.js +14 -6
  734. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  735. package/dist/modes/interactive/interactive-mode-deps.d.ts +2 -4
  736. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  737. package/dist/modes/interactive/interactive-mode-deps.js +2 -4
  738. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  739. package/dist/modes/interactive/interactive-mode-surface.d.ts +9 -8
  740. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  741. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  742. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  743. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  744. package/dist/modes/interactive/interactive-mode.js +1 -0
  745. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  746. package/dist/modes/interactive/interactive-model-catalog-startup.d.ts +2 -3
  747. package/dist/modes/interactive/interactive-model-catalog-startup.d.ts.map +1 -1
  748. package/dist/modes/interactive/interactive-model-catalog-startup.js +3 -6
  749. package/dist/modes/interactive/interactive-model-catalog-startup.js.map +1 -1
  750. package/dist/modes/interactive/interactive-model-routing.js +26 -97
  751. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  752. package/dist/modes/interactive/interactive-pause.d.ts +4 -0
  753. package/dist/modes/interactive/interactive-pause.d.ts.map +1 -0
  754. package/dist/modes/interactive/interactive-pause.js +8 -0
  755. package/dist/modes/interactive/interactive-pause.js.map +1 -0
  756. package/dist/modes/interactive/interactive-process-lifecycle.js +5 -4
  757. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  758. package/dist/modes/interactive/interactive-prompt-turn.d.ts +2 -0
  759. package/dist/modes/interactive/interactive-prompt-turn.d.ts.map +1 -0
  760. package/dist/modes/interactive/interactive-prompt-turn.js +41 -0
  761. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -0
  762. package/dist/modes/interactive/interactive-render-chat.js +20 -8
  763. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  764. package/dist/modes/interactive/interactive-resource-paths.js +11 -2
  765. package/dist/modes/interactive/interactive-resource-paths.js.map +1 -1
  766. package/dist/modes/interactive/interactive-resource-rendering.js +99 -0
  767. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  768. package/dist/modes/interactive/interactive-session-runtime.js +1 -1
  769. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  770. package/dist/modes/interactive/interactive-slash-commands.js +1 -1
  771. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  772. package/dist/modes/interactive/interactive-startup-chat-container.d.ts +20 -0
  773. package/dist/modes/interactive/interactive-startup-chat-container.d.ts.map +1 -0
  774. package/dist/modes/interactive/interactive-startup-chat-container.js +26 -0
  775. package/dist/modes/interactive/interactive-startup-chat-container.js.map +1 -0
  776. package/dist/modes/interactive/interactive-startup.d.ts +1 -1
  777. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  778. package/dist/modes/interactive/interactive-startup.js +30 -25
  779. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  780. package/dist/modes/interactive/interactive-summarization-retry-events.d.ts.map +1 -1
  781. package/dist/modes/interactive/interactive-summarization-retry-events.js +9 -3
  782. package/dist/modes/interactive/interactive-summarization-retry-events.js.map +1 -1
  783. package/dist/modes/interactive/theme/catppuccin-frappe.json +1 -1
  784. package/dist/modes/interactive/theme/catppuccin-latte.json +1 -1
  785. package/dist/modes/interactive/theme/catppuccin-macchiato.json +1 -1
  786. package/dist/modes/interactive/theme/catppuccin-mocha.json +9 -1
  787. package/dist/modes/interactive/theme/dark.json +1 -1
  788. package/dist/modes/interactive/theme/light.json +1 -1
  789. package/dist/modes/interactive/theme/theme-class.d.ts +4 -0
  790. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  791. package/dist/modes/interactive/theme/theme-class.js +7 -0
  792. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  793. package/dist/modes/interactive/theme/theme-loading.d.ts.map +1 -1
  794. package/dist/modes/interactive/theme/theme-loading.js +4 -0
  795. package/dist/modes/interactive/theme/theme-loading.js.map +1 -1
  796. package/dist/modes/interactive/theme/theme-schema.d.ts +32 -0
  797. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -1
  798. package/dist/modes/interactive/theme/theme-schema.js +8 -0
  799. package/dist/modes/interactive/theme/theme-schema.js.map +1 -1
  800. package/dist/modes/interactive/theme/theme-schema.json +15 -2
  801. package/dist/modes/interactive/whimsical-messages.d.ts +1 -0
  802. package/dist/modes/interactive/whimsical-messages.d.ts.map +1 -1
  803. package/dist/modes/interactive/whimsical-messages.js +2 -2
  804. package/dist/modes/interactive/whimsical-messages.js.map +1 -1
  805. package/dist/modes/interactive-engine/create-isolated-runtime.d.ts.map +1 -1
  806. package/dist/modes/interactive-engine/create-isolated-runtime.js +3 -1
  807. package/dist/modes/interactive-engine/create-isolated-runtime.js.map +1 -1
  808. package/dist/modes/interactive-engine/engine-args.d.ts.map +1 -1
  809. package/dist/modes/interactive-engine/engine-args.js +0 -1
  810. package/dist/modes/interactive-engine/engine-args.js.map +1 -1
  811. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  812. package/dist/modes/interactive-engine/engine-custom-ui.js +5 -17
  813. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  814. package/dist/modes/interactive-engine/engine-render-service.d.ts.map +1 -1
  815. package/dist/modes/interactive-engine/engine-render-service.js +8 -19
  816. package/dist/modes/interactive-engine/engine-render-service.js.map +1 -1
  817. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +2 -0
  818. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  819. package/dist/modes/interactive-engine/extension-ui-bridge.js +3 -0
  820. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  821. package/dist/modes/interactive-engine/isolated-auth.d.ts +10 -0
  822. package/dist/modes/interactive-engine/isolated-auth.d.ts.map +1 -0
  823. package/dist/modes/interactive-engine/isolated-auth.js +14 -0
  824. package/dist/modes/interactive-engine/isolated-auth.js.map +1 -0
  825. package/dist/modes/interactive-engine/isolated-runtime.d.ts +9 -1
  826. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  827. package/dist/modes/interactive-engine/isolated-runtime.js +46 -34
  828. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  829. package/dist/modes/interactive-engine/protocol.d.ts +1 -1
  830. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  831. package/dist/modes/interactive-engine/protocol.js +3 -10
  832. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  833. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +1 -0
  834. package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -1
  835. package/dist/modes/interactive-engine/remote-model-catalog.js +10 -1
  836. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
  837. package/dist/modes/interactive-engine/remote-queue-pause.d.ts +13 -0
  838. package/dist/modes/interactive-engine/remote-queue-pause.d.ts.map +1 -0
  839. package/dist/modes/interactive-engine/remote-queue-pause.js +38 -0
  840. package/dist/modes/interactive-engine/remote-queue-pause.js.map +1 -0
  841. package/dist/modes/interactive-engine/remote-renderer.d.ts +3 -1
  842. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  843. package/dist/modes/interactive-engine/remote-renderer.js +4 -1
  844. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  845. package/dist/modes/print-mode.d.ts.map +1 -1
  846. package/dist/modes/print-mode.js +5 -0
  847. package/dist/modes/print-mode.js.map +1 -1
  848. package/dist/modes/rpc/jsonl.d.ts +2 -7
  849. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  850. package/dist/modes/rpc/jsonl.js +7 -24
  851. package/dist/modes/rpc/jsonl.js.map +1 -1
  852. package/dist/modes/rpc/queued-writer.d.ts +19 -0
  853. package/dist/modes/rpc/queued-writer.d.ts.map +1 -0
  854. package/dist/modes/rpc/{bounded-writer.js → queued-writer.js} +7 -30
  855. package/dist/modes/rpc/queued-writer.js.map +1 -0
  856. package/dist/modes/rpc/rpc-bash-request-owners.d.ts +24 -0
  857. package/dist/modes/rpc/rpc-bash-request-owners.d.ts.map +1 -0
  858. package/dist/modes/rpc/rpc-bash-request-owners.js +45 -0
  859. package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -0
  860. package/dist/modes/rpc/rpc-client-api.d.ts +8 -5
  861. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  862. package/dist/modes/rpc/rpc-client-api.js +10 -11
  863. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  864. package/dist/modes/rpc/rpc-client-process.d.ts +1 -4
  865. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  866. package/dist/modes/rpc/rpc-client-process.js +2 -14
  867. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  868. package/dist/modes/rpc/rpc-client.d.ts +8 -4
  869. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  870. package/dist/modes/rpc/rpc-client.js +21 -30
  871. package/dist/modes/rpc/rpc-client.js.map +1 -1
  872. package/dist/modes/rpc/rpc-command-handler.d.ts +7 -4
  873. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  874. package/dist/modes/rpc/rpc-command-handler.js +76 -93
  875. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  876. package/dist/modes/rpc/rpc-input-scheduler.d.ts +3 -3
  877. package/dist/modes/rpc/rpc-input-scheduler.d.ts.map +1 -1
  878. package/dist/modes/rpc/rpc-input-scheduler.js +7 -4
  879. package/dist/modes/rpc/rpc-input-scheduler.js.map +1 -1
  880. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  881. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  882. package/dist/modes/rpc/rpc-mode.js +5 -5
  883. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  884. package/dist/modes/rpc/rpc-model-fallback-prompt.d.ts +4 -0
  885. package/dist/modes/rpc/rpc-model-fallback-prompt.d.ts.map +1 -0
  886. package/dist/modes/rpc/rpc-model-fallback-prompt.js +11 -0
  887. package/dist/modes/rpc/rpc-model-fallback-prompt.js.map +1 -0
  888. package/dist/modes/rpc/rpc-oauth-client.d.ts +22 -0
  889. package/dist/modes/rpc/rpc-oauth-client.d.ts.map +1 -0
  890. package/dist/modes/rpc/rpc-oauth-client.js +74 -0
  891. package/dist/modes/rpc/rpc-oauth-client.js.map +1 -0
  892. package/dist/modes/rpc/rpc-oauth-interaction.d.ts +9 -0
  893. package/dist/modes/rpc/rpc-oauth-interaction.d.ts.map +1 -0
  894. package/dist/modes/rpc/rpc-oauth-interaction.js +49 -0
  895. package/dist/modes/rpc/rpc-oauth-interaction.js.map +1 -0
  896. package/dist/modes/rpc/rpc-output-buffer.d.ts +2 -1
  897. package/dist/modes/rpc/rpc-output-buffer.d.ts.map +1 -1
  898. package/dist/modes/rpc/rpc-output-buffer.js +4 -39
  899. package/dist/modes/rpc/rpc-output-buffer.js.map +1 -1
  900. package/dist/modes/rpc/rpc-provider-auth.d.ts +23 -0
  901. package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -0
  902. package/dist/modes/rpc/rpc-provider-auth.js +145 -0
  903. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -0
  904. package/dist/modes/rpc/rpc-responses.d.ts +0 -1
  905. package/dist/modes/rpc/rpc-responses.d.ts.map +1 -1
  906. package/dist/modes/rpc/rpc-responses.js +0 -14
  907. package/dist/modes/rpc/rpc-responses.js.map +1 -1
  908. package/dist/modes/rpc/rpc-types.d.ts +83 -27
  909. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  910. package/dist/modes/rpc/rpc-types.js.map +1 -1
  911. package/dist/utils/clipboard.d.ts.map +1 -1
  912. package/dist/utils/clipboard.js +21 -8
  913. package/dist/utils/clipboard.js.map +1 -1
  914. package/dist/utils/version-check.d.ts.map +1 -1
  915. package/dist/utils/version-check.js +3 -1
  916. package/dist/utils/version-check.js.map +1 -1
  917. package/docs/changelog.mdx +12 -1
  918. package/docs/compaction.md +101 -18
  919. package/docs/custom-provider.md +13 -4
  920. package/docs/docs.json +1 -0
  921. package/docs/environment-variables.md +37 -0
  922. package/docs/extensions.md +45 -9
  923. package/docs/index.md +1 -0
  924. package/docs/intercom.md +1 -1
  925. package/docs/json.md +4 -4
  926. package/docs/keybindings.md +4 -2
  927. package/docs/llama-cpp.md +3 -1
  928. package/docs/models.md +29 -43
  929. package/docs/providers.md +18 -24
  930. package/docs/quickstart.md +19 -16
  931. package/docs/rpc.md +38 -85
  932. package/docs/sdk.md +15 -22
  933. package/docs/session-format.md +2 -15
  934. package/docs/sessions.md +1 -1
  935. package/docs/settings.md +10 -15
  936. package/docs/skills.md +8 -0
  937. package/docs/subagents.md +24 -8
  938. package/docs/themes.md +10 -1
  939. package/docs/tui.md +3 -3
  940. package/docs/usage.md +30 -2
  941. package/docs/windows.md +1 -1
  942. package/docs/workflows.md +1128 -522
  943. package/examples/extensions/README.md +1 -1
  944. package/examples/extensions/handoff.ts +8 -1
  945. package/examples/extensions/message-renderer.ts +2 -2
  946. package/examples/extensions/summarize.ts +3 -0
  947. package/examples/extensions/working-indicator.ts +2 -2
  948. package/npm-shrinkwrap.json +40 -46
  949. package/package.json +9 -7
  950. package/dist/builtin/cursor/CHANGELOG.md +0 -281
  951. package/dist/builtin/cursor/LICENSE +0 -26
  952. package/dist/builtin/cursor/README.md +0 -24
  953. package/dist/builtin/cursor/index.ts +0 -9
  954. package/dist/builtin/cursor/package.json +0 -47
  955. package/dist/builtin/cursor/src/auth.ts +0 -352
  956. package/dist/builtin/cursor/src/catalog-cache.ts +0 -155
  957. package/dist/builtin/cursor/src/config.ts +0 -123
  958. package/dist/builtin/cursor/src/conversation-state.ts +0 -135
  959. package/dist/builtin/cursor/src/cursor-models-raw.json +0 -412
  960. package/dist/builtin/cursor/src/model-mapper.ts +0 -369
  961. package/dist/builtin/cursor/src/model-reference.ts +0 -282
  962. package/dist/builtin/cursor/src/models.ts +0 -54
  963. package/dist/builtin/cursor/src/native-loader.ts +0 -71
  964. package/dist/builtin/cursor/src/proto/README.md +0 -34
  965. package/dist/builtin/cursor/src/proto/agent_pb.ts +0 -15294
  966. package/dist/builtin/cursor/src/proto/protobuf-codec-base64.ts +0 -22
  967. package/dist/builtin/cursor/src/proto/protobuf-codec-json.ts +0 -44
  968. package/dist/builtin/cursor/src/proto/protobuf-codec-request.ts +0 -311
  969. package/dist/builtin/cursor/src/proto/protobuf-codec-wire.ts +0 -248
  970. package/dist/builtin/cursor/src/proto/protobuf-codec.ts +0 -200
  971. package/dist/builtin/cursor/src/provider.ts +0 -301
  972. package/dist/builtin/cursor/src/stream.ts +0 -494
  973. package/dist/builtin/cursor/src/transport-errors.ts +0 -74
  974. package/dist/builtin/cursor/src/transport-frame.ts +0 -56
  975. package/dist/builtin/cursor/src/transport-http2.ts +0 -122
  976. package/dist/builtin/cursor/src/transport-native-client.ts +0 -161
  977. package/dist/builtin/cursor/src/transport-run-stream.ts +0 -188
  978. package/dist/builtin/cursor/src/transport-timeouts.ts +0 -87
  979. package/dist/builtin/cursor/src/transport-types.ts +0 -143
  980. package/dist/builtin/cursor/src/transport.ts +0 -26
  981. package/dist/builtin/workflows/builtin/deep-research-codebase-runner.ts +0 -492
  982. package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +0 -383
  983. package/dist/builtin/workflows/builtin/deep-research-codebase.d.ts +0 -35
  984. package/dist/builtin/workflows/builtin/deep-research-codebase.ts +0 -47
  985. package/dist/builtin/workflows/skills/impeccable/scripts/hook-before-edit.mjs +0 -516
  986. package/dist/core/context-window.d.ts +0 -54
  987. package/dist/core/context-window.d.ts.map +0 -1
  988. package/dist/core/context-window.js +0 -110
  989. package/dist/core/context-window.js.map +0 -1
  990. package/dist/core/copilot-anthropic-sse-repair.d.ts +0 -23
  991. package/dist/core/copilot-anthropic-sse-repair.d.ts.map +0 -1
  992. package/dist/core/copilot-anthropic-sse-repair.js +0 -340
  993. package/dist/core/copilot-anthropic-sse-repair.js.map +0 -1
  994. package/dist/core/copilot-errors.d.ts +0 -9
  995. package/dist/core/copilot-errors.d.ts.map +0 -1
  996. package/dist/core/copilot-errors.js +0 -32
  997. package/dist/core/copilot-errors.js.map +0 -1
  998. package/dist/core/copilot-gemini-payload-sanitizer.d.ts +0 -72
  999. package/dist/core/copilot-gemini-payload-sanitizer.d.ts.map +0 -1
  1000. package/dist/core/copilot-gemini-payload-sanitizer.js +0 -296
  1001. package/dist/core/copilot-gemini-payload-sanitizer.js.map +0 -1
  1002. package/dist/core/copilot-gemini-reasoning.d.ts +0 -126
  1003. package/dist/core/copilot-gemini-reasoning.d.ts.map +0 -1
  1004. package/dist/core/copilot-gemini-reasoning.js +0 -265
  1005. package/dist/core/copilot-gemini-reasoning.js.map +0 -1
  1006. package/dist/core/copilot-gemini-tool-arguments.d.ts +0 -42
  1007. package/dist/core/copilot-gemini-tool-arguments.d.ts.map +0 -1
  1008. package/dist/core/copilot-gemini-tool-arguments.js +0 -159
  1009. package/dist/core/copilot-gemini-tool-arguments.js.map +0 -1
  1010. package/dist/core/copilot-hosts.d.ts +0 -12
  1011. package/dist/core/copilot-hosts.d.ts.map +0 -1
  1012. package/dist/core/copilot-hosts.js +0 -33
  1013. package/dist/core/copilot-hosts.js.map +0 -1
  1014. package/dist/core/copilot-model-catalog.d.ts +0 -114
  1015. package/dist/core/copilot-model-catalog.d.ts.map +0 -1
  1016. package/dist/core/copilot-model-catalog.js +0 -392
  1017. package/dist/core/copilot-model-catalog.js.map +0 -1
  1018. package/dist/core/copilot-model-static-fallbacks.d.ts +0 -43
  1019. package/dist/core/copilot-model-static-fallbacks.d.ts.map +0 -1
  1020. package/dist/core/copilot-model-static-fallbacks.js +0 -50
  1021. package/dist/core/copilot-model-static-fallbacks.js.map +0 -1
  1022. package/dist/core/copilot-model-synthesis.d.ts +0 -10
  1023. package/dist/core/copilot-model-synthesis.d.ts.map +0 -1
  1024. package/dist/core/copilot-model-synthesis.js +0 -91
  1025. package/dist/core/copilot-model-synthesis.js.map +0 -1
  1026. package/dist/modes/interactive/components/context-window-selector.d.ts +0 -53
  1027. package/dist/modes/interactive/components/context-window-selector.d.ts.map +0 -1
  1028. package/dist/modes/interactive/components/context-window-selector.js +0 -136
  1029. package/dist/modes/interactive/components/context-window-selector.js.map +0 -1
  1030. package/dist/modes/rpc/bounded-writer.d.ts +0 -27
  1031. package/dist/modes/rpc/bounded-writer.d.ts.map +0 -1
  1032. package/dist/modes/rpc/bounded-writer.js.map +0 -1
package/docs/workflows.md CHANGED
@@ -32,8 +32,10 @@ Default to a workflow for non-trivial work with a verifiable objective — see [
32
32
 
33
33
  - [Quick Start](#quick-start)
34
34
  - [When to Use Workflows](#when-to-use-workflows)
35
+ - [The Run Contract](#the-run-contract)
35
36
  - [Built-in Workflows](#built-in-workflows)
36
37
  - [Writing a Workflow](#writing-a-workflow)
38
+ - [Scope-Guard Starter Pattern](#scope-guard-starter-pattern)
37
39
  - [The `workflow()` Definition](#the-workflow-definition)
38
40
  - [WorkflowContext](#workflowcontext)
39
41
  - [Task and Stage Options](#task-and-stage-options)
@@ -112,6 +114,8 @@ List and run it like any other workflow:
112
114
 
113
115
  Named workflow runs execute in the background. By default, after launch expect a run id and monitor it with `/workflow status <run-id>`, F2, or `/workflow connect <run-id>`. A definition with `autoAttach: true` instead opens the graph overlay as soon as an interactive top-level named launch through `/workflow <name>` or the registered `workflow` tool is accepted. This option does not affect headless launches or nested `ctx.workflow(...)` calls, and existing input-form launch behavior is unchanged.
114
116
 
117
+ For a request with several implementation items, do not turn list order into one serial workflow by default. Triage dependencies first, then launch independent items as a bounded wave of separate top-level runs; see [Task queues and software factories](#task-queues-and-software-factories).
118
+
115
119
  While a workflow is running, the visible below-editor `BACKGROUND` panel advances its elapsed label every second from the moment the run starts; it does not require opening or switching to the orchestrator. Updates repaint the existing mounted panel in place, paused timers stay frozen, and terminal cards retain their short recent-run expiry.
116
120
 
117
121
  ### Or hand-write the TypeScript
@@ -166,7 +170,7 @@ Workflows are the default execution path when a request is non-trivial or combin
166
170
 
167
171
  Loop or stop-condition phrasing is an especially strong workflow signal: `do X until Y`, `repeat until`, `iterate until`, `review/fix until passing`, `run checks and fix until green`, and `keep going until done` define control flow and convergence criteria that should be tracked.
168
172
 
169
- Use direct chat only for tiny, deterministic, low-risk answers or edits where stage tracking clearly costs more than it adds, typically a single-file/no-test/no-review change. Decide inline versus workflow before the first tool call; reconnaissance is already inline execution. Once workflow fit is clear, limit pre-workflow reconnaissance to the few reads needed to sharpen the objective and validation criteria, and put deeper research or behavior probing inside the run.
173
+ Use direct chat only for tiny, deterministic, low-risk answers or edits where stage tracking clearly costs more than it adds, typically a single-file/no-test/no-review change. Choose direct chat or a workflow based on that fit; reconnaissance is already inline execution. Once workflow fit is clear, limit pre-workflow reconnaissance to the few reads needed to sharpen the objective and validation criteria, and put deeper research or behavior probing inside the run.
170
174
 
171
175
  Workflow-first does not require builtins, monolithic workflows, or a force-fit builtin: a builtin that matches 60% of the task and fights the other 40% is worse than a small custom graph. Discover named builtin, project, user, and package workflows; or author a task-specific TypeScript `workflow({...})` inline with normal coding tools whenever the task needs richer branching, dynamic fan-out, artifacts, structured outputs, child workflows, human input, gates, retries, or loops.
172
176
 
@@ -174,41 +178,114 @@ Rich custom workflows can compose the [common workflow patterns](#common-workflo
174
178
 
175
179
  If inline work drifts past roughly ten exploratory tool calls without an artifact, edit, or commit, or repeats a "verify one more thing" loop, save the findings to a context file and hand the task to the best-fit named or custom workflow through `reads`. Sunk research is transferable, not a reason to continue inline.
176
180
 
177
- | User goal | Use |
181
+ | User need | Use |
178
182
  |-----------|-----|
179
183
  | Run, inspect, connect to, pause, interrupt, quit, resume, or check status for an existing workflow | `/workflow ...` or `workflow({ action: ... })` |
180
- | Run an autonomous job that materially benefits from a durable goal ledger, bounded worker turns, named validation, and reviewer-gated completion | `/workflow goal objective="..."` so Atomic captures receipts, gates completion through reviewers, stops as `complete`, `blocked`, or `needs_human`, and can optionally run a final PR handoff with `create_pr=true` after approval |
181
- | Run an autonomous job that materially benefits from a durable research-first pipeline, delegated implementation, and iterative review | `/workflow ralph prompt="..."` so Atomic can transform the prompt into a research question, research the codebase first, delegate implementation through sub-agents, review, and iterate; prompt text alone does not opt in to PR creation, so add `create_pr=true` only when you want the final `pull-request` stage and `pr_report` |
182
- | Create or edit reusable automation | a TypeScript workflow definition exported from `workflow({...})` |
183
- | Make a workflow robust | design the stage graph, context handoffs, artifacts, validation gates, model fallbacks, and human approval points before coding |
184
+ | Run repository-wide research | Compose `fan-out-and-synthesize` with repository-focused branches, artifact outputs, and a synthesis barrier, or author a smaller task-specific research workflow. |
185
+ | Run an implementation/review loop | Author a task-specific worker fresh verifier reducer loop with explicit evidence, repair bounds, and stop conditions. |
186
+ | Create or edit reusable automation | A TypeScript workflow definition exported from `workflow({...})` |
187
+ | Make a workflow robust | Design the stage graph, context handoffs, artifacts, validation gates, model fallbacks, and human approval points before coding |
184
188
 
185
189
  ### Choosing an Execution Shape
186
190
 
187
191
  "Use a workflow" is not one decision — it covers several execution shapes with different costs and guarantees. This section is written as agent-facing guidance: it is the self-prompt an orchestrating agent should run before the first tool call on a new request, and it doubles as documentation for humans who want to steer that choice explicitly.
188
192
 
193
+ > **Multi-item routing rule:** Enumerate requested implementation items and prove their dependencies before launch. Run independent items as separate concurrent top-level workflow runs with bounded concurrency, one explicit worktree and root failure boundary per item. Preserve ordered composition only for real code, artifact, contract, decision, approval, or merged-result dependencies.
194
+
189
195
  The shapes, cheapest first:
190
196
 
191
197
  | Shape | What it is | Guarantees you gain | Cost you pay |
192
198
  |---|---|---|---|
193
199
  | **Inline** | Answer or edit directly in the current session. | Lowest latency, zero ceremony. | No tracking, no gates, no isolation, easy to drift. |
194
- | **Inline + subagents** | Bounded specialist delegation (locate/analyze/research/debug passes, noisy command investigation, parallel read-only fanouts) while the parent keeps control and synthesizes. | Context isolation for noisy or parallel evidence-gathering. | No completion gate, no durable stages; the parent is the only reviewer. |
195
- | **Named workflows** | Installed builtin, project, user, or package workflows (`goal`, `ralph`, `deep-research-codebase`, `open-claude-design`, ...). | A proven graph: bounded loops, reviewer gates, ledgers, evidence contracts, tuned model chains. | The task must actually match the graph's objective and inputs. |
196
- | **Custom workflow** | A task-specific TypeScript `workflow({...})` authored inline, composing the common workflow patterns. | Exactly the control flow the task needs: runtime branching, dynamic fan-out, custom gates, tournaments, bounded loops. | Authoring and reload time; you own the design quality. |
197
- | **Composed/nested workflows** | A custom parent that imports proven definitions and calls `ctx.workflow(child)`. | Reuse of hardened children (research, review loops) inside custom control flow, within `maxDepth`. | Parent/child input-output contracts must be mapped deliberately. |
200
+ | **Inline + subagents** | Bounded specialist delegation while the parent keeps control and synthesizes. | Context isolation for noisy or parallel evidence-gathering. | No completion gate or durable stages; the parent remains the reviewer. |
201
+ | **Named workflows** | Installed builtin, project, user, or package workflows. | A tested graph with known inputs, outputs, gates, and artifacts. | The task must match the graph's objective and contract. |
202
+ | **Custom workflow** | A task-specific TypeScript `workflow({...})` composed from common patterns. | Exact control flow for runtime branching, fan-out, gates, tournaments, and bounded loops. | Authoring and reload time; you own design quality. |
203
+ | **Composed/nested workflows** | A parent that imports definitions and calls `ctx.workflow(child)`. | Reuse of tested children inside custom control flow, within `maxDepth`. | Parent/child input-output contracts must be mapped deliberately. |
204
+
205
+ #### The self-prompt: pre-launch workflow architecture
206
+
207
+ For every non-trivial workflow task, perform a short workflow-architecture pass before the first launch. Choose the execution shape before starting substantive work; reconnaissance already counts as inline execution. Derive the task's implementation lifecycle needs, whole-codebase research needs, independent work slices, competing strategies, exact API/type/build contracts, schema or generated-artifact contracts, state-transition/lifecycle behavior, deterministic stop conditions, and required evidence.
208
+
209
+ Use this compact coverage matrix internally (it may stay concise for a straightforward task), and let every unresolved material row change the graph choice:
210
+
211
+ ```text
212
+ requirement/risk | required evidence | workflow/stage that produces it | gap
213
+ ```
214
+
215
+ For any custom or composed graph, add this row and resolve it before launch:
216
+
217
+ ```text
218
+ acyclic topology | node/edge sketch for branches and loops | architecture pass | unresolved back-edge
219
+ ```
220
+
221
+ Answer these topology questions as part of the pass:
222
+
223
+ 1. Which stages may repeat?
224
+ 2. Does each iteration create distinct tracked work?
225
+ 3. What is the current frontier before each repeated stage?
226
+ 4. Could any proposed parent edge target an ancestor or the node itself?
227
+ 5. Are nested child workflows composed through boundaries rather than recursive `run` invocation?
228
+ 6. Does resume/replay rely on stable per-iteration identity and call order?
229
+
230
+ Sketch expected nodes and dependencies for each branch, loop, and nested boundary. Any unresolved self-edge or back-edge must change the workflow design before launch.
198
231
 
199
- #### The self-prompt
232
+ Compare candidate workflow **guarantees**, not only broad descriptions. A named graph fits only when it covers the task's lifecycle **and** produces the evidence required for every material requirement/risk. A generic implementation workflow can cover the lifecycle while missing exact API/type/build contracts, schemas/generated artifacts, state transitions, or domain-specific gates. **Do not treat "has reviewers" as proof that a task-specific risk is covered.**
200
233
 
201
- Ask these questions in order and stop at the first shape that satisfies every remaining requirement. Decide before the first tool call and state the decision; reconnaissance already counts as inline execution.
234
+ Ask these questions in order and stop at the cheapest shape that satisfies every remaining coverage row:
202
235
 
203
236
  1. **Is the outcome provable?** If success can be stated as evidence (tests green, artifact exists, behavior demonstrated, reviewer approves), the task fits a workflow. If no proof is possible or needed, inline is probably fine.
204
237
  2. **Is there structure?** Multiple subtasks, dependencies, handoffs, or parallel slices rule out inline execution. A single focused evidence-gathering pass does not.
205
238
  3. **Is there a loop or gate?** Any "until Y", "fix until passing", review/approval gate, or unknown-length repair cycle requires a workflow that enforces the stop condition, never an improvised inline retry loop or a stretched subagent chain.
206
- 4. **Is it one task or a queue of tasks?** "Address all open issues" or "fix every ticket assigned to me" is a factory request, not one workflow. Enumerate and dependency-classify the items first, then follow [Task queues and software factories](#task-queues-and-software-factories): independent items become separate per-item runs; dependent items share one composed graph.
207
- 5. **Does an installed graph already fit?** If a named workflow's objective and inputs cover essentially the whole task, run it. Do not force-fit a partial match ([When to Use Workflows](#when-to-use-workflows)).
208
- 6. **Does the control flow need shapes builtins don't offer?** Runtime classification, per-item dynamic fan-out, generate-and-filter, tournaments, or domain-specific gates mean authoring a custom workflow from the common workflow patterns.
209
- 7. **Does a proven graph already solve a sub-problem?** Nest it with `ctx.workflow(...)` instead of re-authoring its prompts and gates. Use composition instead of duplication whenever you can cleanly map the child's input/output contract.
210
- 8. **Is it only specialist evidence-gathering?** If the parent keeps control, no completion gate is needed, and the work is bounded (a debug pass, a parallel research fanout, one noisy investigation), inline subagents are enough and cheaper than a workflow.
211
- 9. **Is it truly tiny?** Deterministic, low-risk, single-file/no-test/no-review answer or edit inline and stop.
239
+ 4. **Is it one task or a queue of tasks?** "Address all open issues" or "fix every ticket assigned to me" is a factory request, not one workflow. Enumerate and dependency-classify the items first, then follow [Task queues and software factories](#task-queues-and-software-factories): independent items become bounded concurrent top-level per-item runs; dependent items share one ordered composed graph; independent dependency clusters become separate top-level runs.
240
+ 5. **Does an installed graph supply complete coverage?** Run a named workflow only if its objective, inputs, lifecycle, and produced evidence cover every material row. Do not force-fit a broad-but-partial match ([When to Use Workflows](#when-to-use-workflows)).
241
+ 6. **What routing signals shape the graph?** Broad repository uncertainty points to repository-focused Fan-out-and-synthesize; independent slices to Fan-out-and-synthesize; plausible-but-wrong contract risk to Adversarial verification or a task-specific verification stage; competing architectures or implementations to Generate-and-filter or Tournament; an explicit repeat-until condition to Loop until done; implementation work to a task-specific worker/reviewer loop; and exact API/build/schema requirements to dedicated deterministic gates.
242
+ 7. **Does a tested graph solve only part of the task?** Author one custom parent and nest that definition with `ctx.workflow(...)`, placing the missing research, verification, or deterministic gates around it instead of copying its prompts and gates.
243
+ 8. **Is it only specialist evidence-gathering?** If the parent keeps control, no completion gate is needed, and the work is bounded (a debug pass, a parallel research fanout, one noisy investigation), inline subagents are enough—and cheaper than a workflow.
244
+ 9. **Is it truly tiny?** Deterministic, low-risk, single-file/no-test/no-review—answer or edit inline and stop.
245
+
246
+ A first named workflow launch commits the selected execution shape for the turn. For one task, end the turn after that launch. For an independent queue, the selected shape is a bounded launch wave: issue every planned per-item top-level launch up to the concurrency bound before ending the turn. Do not casually chain unplanned unrelated top-level workflow launches. When one task needs multiple workflow capabilities or dependent items need ordered handoffs, design composition **before** launch: author one custom parent, import project/package definitions or builtins from `@bastani/workflows/builtin`, and call `ctx.workflow(...)`. Nested children preserve their stages and guarantees within the expanded graph up to `maxDepth`, but they remain under the parent's root lifecycle and failure boundary.
247
+
248
+ Choose the cheapest complete graph. Routing cues are not a reason to add decorative stages: avoid duplicated research and review loops. Before launch, state the selected graph, why one broad builtin is sufficient or insufficient, the evidence each major stage produces, and the stop/repair conditions. A simple direct match can be one sentence; a composed graph should briefly name its children and task-specific gates.
249
+
250
+ When an arbitrary task-specific workflow has plausible-but-wrong contract risk, design a bounded evidence-backed adversarial loop:
251
+
252
+ 1. Give a fresh-context, grumpy/skeptical-but-fair reviewer the literal objective. It should aggressively seek realistic counterexamples without inventing requirements or accepting hand-waving and circular worker-authored evidence, then emit a structured verifier plan: exact probe, inputs, command/assertion, expected success condition, and requirement/risk covered.
253
+ 2. For known contracts, author direct task-specific `ctx.tool(...)` gates up front. For adversarially discovered risks, let the model select high-value probes in structured output, but execute the selected compile, test, schema generation/validation, runtime, and artifact-inspection checks authoritatively through durable workflow-owned `ctx.tool(...)` calls. The model must not self-report outcomes.
254
+ 3. Feed the actual tool results to a skeptical evaluation stage. It classifies failures and emits one consolidated, evidence-backed, bounded repair payload for the implementation child.
255
+ 4. After repair, rerun the deterministic verifier tools until the declared pass condition succeeds or the iteration budget is exhausted. Define pass, repair, failure, and iteration-limit conditions before launch.
256
+
257
+ Use `ctx.tool` for workflow-owned external checks and side effects that benefit from durable checkpointing. Leave pure transformations as ordinary TypeScript; do not wrap every model-stage action in a tool call. A custom-loop pre-launch declaration must name the skeptical reviewer, deterministic verifier gates, how model-selected plans become tool executions, how evidence reaches evaluation/repair, and the bounded success/failure condition.
258
+
259
+ #### Judging task complexity
260
+
261
+ Complexity is a property of risk, not effort. Score a task on five axes and let the **worst axis dominate** — complexity is not the sum:
262
+
263
+ | Axis | Low | High |
264
+ |---|---|---|
265
+ | **Blast radius** | one file, one function | crosses module/package boundaries; touches shared contracts (APIs, schemas, migrations) |
266
+ | **Uncertainty** | the exact edit is known before opening the file | the location or cause of the behavior is unknown |
267
+ | **Verifiability cost** | type-checker or a glance confirms it | multi-step validation: build + tests + runtime behavior + artifact checks |
268
+ | **Dependency structure** | independent steps | ordered handoffs where an early mistake propagates |
269
+ | **Failure cost** | reversible edit | wire formats, published APIs, data migrations, releases |
270
+
271
+ A one-line change to a serialization format is complex (high failure cost, exact contract). A 500-line mechanical rename is simple (zero uncertainty, type-checker-verified). The common trap is judging by effort instead of risk: long-but-mechanical is simple; short-but-contractual is not.
272
+
273
+ Fast tells, usable in the first 30 seconds:
274
+
275
+ - **Done-condition test:** if the success condition does not fit in one sentence, the task is complex or underspecified — clarify before guessing.
276
+ - **The "and" test:** "fix X and update docs and add a test" is three tasks in one sentence; enumerate and classify each.
277
+ - **Loop words:** "until it passes", "keep trying" make the task at least moderate — iteration is expected.
278
+ - **Working-memory test:** more than about three interacting constraints at once means complex.
279
+
280
+ **Threshold.** A task earns a workflow when at least two of these are true, or any one is strongly true:
281
+
282
+ 1. Two or more distinct phases with a real handoff (research → implement, implement → verify), not just steps.
283
+ 2. The done-condition needs proof — tests, builds, review, or a contract check. If "how do you know it works?" is a fair question, a verification stage is waiting to exist.
284
+ 3. Iteration is expected — an anticipated repair loop, not a straight line.
285
+ 4. Failure cost is high — even a one-line change gets adversarial verification.
286
+ 5. The work outlives one attention span — losing mid-task state is a real risk.
287
+
288
+ The honest form of the threshold is a comparison: workflow overhead is roughly constant and small, while the cost of being wrong inline scales with uncertainty × failure cost — so the line crosses at "moderate" on any single axis. Guard against the ratchet failure mode: a task that looked simple, then accumulated exploratory calls, ad-hoc fixes, and an untracked mental TODO list is a workflow being run badly in-head; apply the ten-call rule from [When to Use Workflows](#when-to-use-workflows). Map axes to action: all low → inline now; only uncertainty high → short recon, then re-judge; any axis high with a checkable outcome → workflow with a stage producing evidence for the worst axis; failure cost high → add deterministic or adversarial gates regardless of the rest. When the mapping stays ambiguous, fall through to the [scoring rubric](#scoring-rubric) below.
212
289
 
213
290
  #### Scoring rubric
214
291
 
@@ -234,341 +311,409 @@ The rubric prevents two common misuses: using parent-controlled subagent calls f
234
311
 
235
312
  #### Task queues and software factories
236
313
 
237
- Some requests are not one task but a queue of them: "address all open issues", "fix every Linear ticket assigned to me", "burn down the TODO backlog", "upgrade every service to the new SDK". These fire-and-forget factory requests need a separate decision step because one monolithic workflow would process the queue serially in a single growing context.
238
-
239
- **Triage the queue before choosing the shape.** The first action is always a cheap enumeration-and-dependency pass, not implementation: list the items (issue tracker query, ticket API, grep for TODOs), then classify how they relate:
240
-
241
- - **Independent items** — different subsystems, no shared files, no ordering constraints, each individually verifiable.
242
- - **Dependent items** — one blocks another, they touch the same files/modules, they share a migration or API change, or their acceptance criteria reference each other.
243
- - **Clustered** — the queue splits into groups: dependencies inside a group, independence between groups.
244
-
245
- **Independent items → many small runs, not one big one.** Spawn one workflow run per item (typically `goal` with the item's text as the objective and acceptance criteria, `create_pr=true` for per-item PRs), each in its own `git_worktree_dir`, running in the background. One run per item provides what a monolith cannot:
246
-
247
- - **Isolation:** a hard item that stalls or fails does not affect the remaining ones; each run resumes, retries, or can be stopped independently.
248
- - **Clean contexts:** every item starts with fresh context focused on its own objective instead of receiving the transcripts of twenty finished tickets.
249
- - **Independent evidence:** per-item reviewer gates, receipts, and PRs that a human can merge or reject one at a time.
250
- - **Real parallelism:** runs proceed concurrently, up to the number you choose to run at once (worktrees prevent filesystem collisions).
251
-
252
- Dispatch a bounded number at a time (for example 3–5 concurrent runs), wait for lifecycle notices, then dispatch the next wave — and report the dispatch plan (item → run id → worktree) so the queue is auditable.
253
-
254
- **Dependent items → one graph that encodes the ordering.** When items block each other or share a change surface, isolation no longer helps — separate runs could modify the same files or rely on outdated assumptions. Encode the dependency structure explicitly instead:
255
-
256
- - **A composed parent workflow** that nests a proven child (for example `ctx.workflow(goal, ...)` per item) in dependency order, passing each item's outputs/artifacts to its dependents — the preferred form, because each item still gets its own bounded loop and reviewer gate while the parent owns sequencing.
257
- - **A single monolithic workflow** only when the items share enough dependencies to form one task with subtasks (one migration touching every call site is one task, not a queue).
258
-
259
- **Clustered queues → both.** Compose within a cluster, fan out across clusters: each cluster becomes one run (a composed parent or a single `goal` objective covering the cluster), and independent clusters are dispatched as parallel background runs in waves.
260
-
261
- The self-prompt for factory requests, condensed: **enumerate → classify dependencies → fan out runs where independent, compose graphs where dependent → dispatch in bounded waves → report the plan.** When dependency classification is uncertain, prefer smaller independent runs and let per-item reviewer gates catch collisions — a rejected PR is cheaper than a monolith that applied a bad assumption throughout the queue.
262
-
263
- #### Prompting the choice
264
-
265
- Humans can steer the shape directly. The most direct controls, in rough order of effect:
266
-
267
- - **Name the shape or workflow.** "Do this inline", "use subagents to investigate", "run the goal workflow", or "write a custom workflow for this" overrides the agent's own scoring.
268
- - **State acceptance criteria.** Verbatim acceptance criteria make the objective provable, which both selects workflow execution and sets the immutable contract that `goal`/`ralph` reviewers enforce.
269
- - **State the loop.** "Iterate until tests pass", "review and fix until approved" — loop wording is a hard workflow signal and defines the stop condition.
270
- - **State the evidence.** Asking for a PR, a QA video, test output, or reviewer sign-off tells the agent which gates the graph needs.
271
- - **State the boundary.** "Work in a separate worktree", "don't create the PR yet", or "stop after implementation" separates the implementation loop from explicitly authorized final actions.
272
- - **State the queue policy.** For factory requests, say how to split and gate the queue: "one workflow and PR per issue", "these three tickets depend on each other — do them in order in one run", "triage first and show me the dependency plan before dispatching", or "no more than three runs at a time". Absent a policy, the agent triages dependencies itself and defaults to independent per-item runs with per-item evidence.
314
+ Some requests are not one task but a queue of them: "address all open issues", "fix every Linear ticket assigned to me", "burn down the TODO backlog", or "implement issue A and create a PR after; also implement issue B and create a PR after". One monolithic worker loop would process the queue serially in a growing context and make unrelated work share one root failure boundary.
273
315
 
274
- Absent these levers, the agent applies the self-prompt and rubric above so a prompt that mentions none of them is delegating the shape decision, not avoiding it.
316
+ **Interpret ordering words locally unless a cross-item dependency is explicit.** "Implement A and create PR A after; implement B and create PR B after" normally means `implement A → validate A → PR A` and `implement B → validate B → PR B`; those two item lifecycles may run concurrently. It does not mean `PR A → start B`. Serialize only when the user or repository evidence says, for example, "implement B after A is merged", "B builds on A's branch", "use A's generated schema in B", or "do these in order". Do not infer a cross-item sequence from list order or from "create a PR after" when "after" naturally refers to that item's own implementation. Prove the dependency before serializing independent workflow items. If wording remains materially ambiguous after dependency research, ask one grouped clarification instead of silently serializing.
275
317
 
276
- ### Atomic vs Claude Code Dynamic Workflows
318
+ **Triage before dispatch:**
277
319
 
278
- Claude Code Dynamic Workflows and Atomic address a similar problem: important software engineering work is too large for one agent pass, so the system should split the job into stages, run agents in parallel, verify the result, and keep enough state to finish long-running work.
320
+ 1. Enumerate every requested item.
321
+ 2. Inspect stated issue, PR, branch, and approval dependencies.
322
+ 3. Check whether each prerequisite is already merged into the base each run will use. A merged prerequisite does not serialize current items when every base contains it. An unmerged prerequisite delays only the item or dependency cluster that consumes it; unrelated items remain eligible for separate concurrent workflow runs under the queue's bound.
323
+ 4. Check likely shared files, API contracts, migrations, generated artifacts, and release or deployment effects. A shared unmerged contract can create a dependency even when items edit different files.
324
+ 5. Classify items as **independent**, **dependent**, or **clustered**.
325
+ 6. Dispatch independent items or clusters concurrently with an explicit concurrency bound; preserve dependency order inside each cluster.
326
+ 7. Report an item → run ID → worktree → branch → result/PR map. After each terminal lifecycle notice, inspect that run's status detail before updating its result/PR fields.
279
327
 
280
- Atomic's category is broader and more explicit: it is the loop engine for engineering work. The difference is who controls the process and how much of the loop you can inspect, version, extend, and connect to your stack.
328
+ | Relationship | Execution shape |
329
+ |---|---|
330
+ | Independent issues in separate code areas | Separate top-level workflow runs in bounded parallel waves |
331
+ | A prerequisite is already merged into every selected base | Treat the prerequisite as satisfied; run otherwise independent items in parallel |
332
+ | Same files or a shared unmerged API, schema, migration, or generated artifact | One ordered/composed workflow, or one ordered run per dependent cluster |
333
+ | One issue explicitly builds on another branch, PR, artifact, decision, approval, or merged result | Sequential dependency |
334
+ | Independent clusters with internal dependencies | Separate cluster runs in parallel; compose or sequence items inside each cluster |
335
+ | Material dependency remains unclear | Ask one grouped clarification before implementation |
281
336
 
282
- | Dimension | Atomic | Claude Code Dynamic Workflows |
283
- | --- | --- | --- |
284
- | Core idea | Open-source, repo-native loop engine for coding agents. You can run built-ins, tell the coding agent to use a workflow for a task, describe new loops in natural language for Atomic to scaffold dynamically, or version them as explicit TypeScript files. | Claude dynamically creates orchestration scripts for a task and fans work out to many parallel Claude subagents. |
285
- | Best fit | Teams that want repeatable software engineering loops they can inspect, version, extend, connect to tools, and run across providers. | Claude Code users who want Claude to decide when a task needs a larger dynamic workflow and orchestrate it automatically. |
286
- | Workflow control | The process is explicit: stages, inputs, handoffs, retries, artifacts, model choices, checkpoints, and human gates are part of the workflow definition. | The process is generated dynamically by Claude for the current task, with confirmation before the first workflow run. |
287
- | Models | Model-agnostic. Atomic connects directly to supported API-key and subscription providers, and workflows can use model fallback chains. | Claude-first. Availability is tied to Claude Code, Claude plans, and Anthropic-supported API/cloud channels. |
288
- | Extensibility | Built on Pi extensions: add tools, TUI, MCP, web access, intercom, skills, prompt templates, themes, custom providers, and packaged workflows. | Optimized for Claude Code's built-in dynamic orchestration experience rather than an open extension SDK you own in-repo. |
289
- | Artifacts and auditability | Research docs, specs, logs, transcripts, reviewer notes, check output, and final summaries can live in the repo or workflow run directory. | Progress is saved and resumable, but the orchestration is primarily a Claude Code runtime behavior. |
290
- | Cost/scale posture | You choose the graph and concurrency. Atomic can be small and deterministic, or broad when you intentionally design a larger workflow. | Designed for large fan-outs, including tens to hundreds of subagents; Anthropic notes it can consume substantially more tokens than a typical Claude Code session. |
337
+ **Workflow run isolation and Git worktree isolation are separate guarantees.** A top-level run provides its own context, progress, lifecycle controls, retry state, and root failure boundary. A worktree provides a separate checkout and Git state; it is not an operating-system sandbox. Several worktrees inside one sequential root do not create concurrent top-level runs or independent root failure boundaries, while concurrent writer runs without separate worktrees can still conflict. Use both for independent implementation items.
291
338
 
292
- ## Built-in Workflows
339
+ A natural-language request for a worktree does not configure runner isolation. Inspect the named workflow's inputs first. Each per-item definition must declare and implement its reusable-worktree and branch inputs, and the dispatcher must pass distinct values explicitly. With `worktreeFromInputs`, a missing target is created as a detached checkout from `baseBranch`, while an existing same-repository worktree is reused as-is. Neither case checks out the feature branch named by a separate `branch` input, so the item workflow must enforce that branch step itself.
293
340
 
294
- Atomic bundles ten workflows: four established end-to-end workflows and six reusable implementations of the common workflow patterns. They are available in every session no install step required. Use `/workflow list` to confirm they are loaded, and `/workflow inputs <name>` to see the exact inputs in your environment.
341
+ **Supported example: two independent top-level issue runs with a bound of 2.** First save this complete project workflow as `.atomic/workflows/issue-to-pr.ts`, then run `/workflow reload`. It is a user-defined workflow built only from supported authoring APIs, not a bundled workflow name that Atomic installs by default.
295
342
 
296
- Workflow authors can also use these builtins as workflow definitions. Import them from `@bastani/workflows/builtin` and pass the definition directly to `ctx.workflow(...)` when one workflow should call `deep-research-codebase`, `goal`, `ralph`, `open-claude-design`, or any of the six pattern builtins as a nested child workflow. See [Workflow Composition](#workflow-composition) for full examples alongside user-defined child workflows.
343
+ ```ts
344
+ // .atomic/workflows/issue-to-pr.ts
345
+ import { workflow } from "@bastani/workflows";
346
+ import { Type, type Static } from "typebox";
297
347
 
298
- For the builtin result tables below, `deep-research-codebase`, `goal`, and `ralph` explicitly declare `outputs: { result: Type.Optional(Type.String(...)) }`, so `result` is an optional part of their declared output contracts and may be omitted, including after an intentional early exit. Like every workflow output, `result` must be declared in `outputs` and returned from `run` or supplied to `ctx.exit({ outputs })` when present — see [Outputs](#outputs); Atomic adds no automatic `result` output.
348
+ const reviewDecision = Type.Object(
349
+ {
350
+ approved: Type.Boolean(),
351
+ findings: Type.Array(Type.String()),
352
+ },
353
+ { additionalProperties: false },
354
+ );
355
+
356
+ function runCommand(argv: readonly string[], cwd: string): string {
357
+ const result = Bun.spawnSync([...argv], { cwd, stdout: "pipe", stderr: "pipe" });
358
+ const stdout = result.stdout.toString().trim();
359
+ const stderr = result.stderr.toString().trim();
360
+ if (result.exitCode !== 0) {
361
+ throw new Error(`${argv.join(" ")} failed (${result.exitCode})\n${stderr || stdout}`);
362
+ }
363
+ return stdout;
364
+ }
299
365
 
300
- | Workflow | What it does | When to use |
301
- |---|---|---|
302
- | `classify-and-act` | Structured classifier deterministic category action; low confidence falls back to human selection. | Route heterogeneous requests to isolated category-specific work. |
303
- | `fan-out-and-synthesize` | Structured partition → bounded parallel artifact branches → synthesis barrier. | Split independent slices and merge evidence with dedupe/conflict resolution. |
304
- | `adversarial-verification` | Worker → fresh rubric verifiers → reducer → bounded repair loop. | Independently prove or reject a candidate. |
305
- | `generate-and-filter` | Candidate fan-out → rubric dedupe/filter → optional judge → shortlist. | Explore more options than you need and select the strongest distinct few. |
306
- | `tournament` | Whole-task attempts → balanced pairwise judges → bracket reducer. | Compare subjective or approach-sensitive solutions. |
307
- | `loop-until-done` | Durable ledger → iteration/evaluator loop → success or inspectable bound exhaustion. | Continue until explicit evidence proves completion. |
308
- | `deep-research-codebase` | Heavy research for tasks requiring comprehensive, whole-repository context. | Tasks that genuinely require comprehensive whole-repository coverage. |
309
- | `goal` | Persisted goal ledger → bounded worker turns → receipts → three-reviewer gate → deterministic reducer → final report → optional final-stage PR handoff after approval. | Clearly delegated autonomous work that materially benefits from a durable goal ledger, bounded worker turns, named validation, and reviewer-gated completion; optionally allow only the final `pull-request` stage to attempt PR creation with `create_pr=true` after Goal reaches `complete`. |
310
- | `ralph` | Raw prompt → research-prompt-refinement → codebase/online research → sub-agent orchestration → multi-model parallel review → optional final-stage PR handoff. | Clearly delegated autonomous work that materially benefits from a durable research-first pipeline, delegated implementation, and iterative review; optionally allow only the final `pull-request` stage to attempt PR creation with `create_pr=true`. |
311
- | `open-claude-design` | Combined discovery/init (`/skill:impeccable shape` + `/skill:impeccable init` in one `discovery` stage) → design-system/reference research (`ds-*`) → curated gallery reference-discovery using that context → separate forked `generate-*` and `user-feedback-*` chains → rich HTML handoff (`exporter` → `final-display`). The discovery stage asks what to build, the output type, and which references to emulate, then lets impeccable init detect/create/reconcile `PRODUCT.md` and `DESIGN.md` (references take precedence over project context). Renders a live `preview.html` you can iterate against in the browser (opens through impeccable `live` / the `playwright-cli` skill when available). | UI, page, component, theme, or design-token work that benefits from a guided brief, beautiful references, and generation + user feedback loops. |
366
+ export default workflow({
367
+ name: "issue-to-pr",
368
+ description: "Implement, review, check, and open one issue PR in its own worktree.",
369
+ inputs: {
370
+ issue: Type.String(),
371
+ git_worktree_dir: Type.String(),
372
+ base_ref: Type.String({ default: "origin/main" }),
373
+ pr_base: Type.String({ default: "main" }),
374
+ branch: Type.String(),
375
+ checks: Type.Array(Type.Array(Type.String(), { minItems: 1 }), { minItems: 1 }),
376
+ },
377
+ outputs: {
378
+ result: Type.String(),
379
+ pr_url: Type.String(),
380
+ branch: Type.String(),
381
+ worktree: Type.String(),
382
+ },
383
+ worktreeFromInputs: { gitWorktreeDir: "git_worktree_dir", baseBranch: "base_ref" },
384
+ run: async (ctx) => {
385
+ const { issue, branch, checks } = ctx.inputs;
386
+ const cwd = ctx.cwd ?? ctx.inputs.git_worktree_dir;
387
+ const baseRef = ctx.inputs.base_ref;
388
+
389
+ await ctx.tool("select-feature-branch", { branch, base_ref: baseRef }, async () => {
390
+ const probe = Bun.spawnSync(
391
+ ["git", "show-ref", "--verify", "--quiet", `refs/heads/${branch}`],
392
+ { cwd, stdout: "pipe", stderr: "pipe" },
393
+ );
394
+ if (probe.exitCode === 0) return runCommand(["git", "switch", branch], cwd);
395
+ if (probe.exitCode !== 1) throw new Error(probe.stderr.toString().trim());
396
+ return runCommand(["git", "switch", "-c", branch, baseRef], cwd);
397
+ });
312
398
 
313
- ### Six composable pattern builtins
399
+ await ctx.task("implement", {
400
+ context: "fork",
401
+ prompt: [
402
+ `Implement ${issue}.`,
403
+ "Add or update tests, make the smallest correct change, and commit all changes.",
404
+ "Do not create the PR; this workflow does that only after review and checks pass.",
405
+ ].join("\n"),
406
+ });
314
407
 
315
- The six patterns in [Pattern diagrams](#pattern-diagrams) ship as full definitions exported from `@bastani/workflows/builtin`. Each has typed/defaulted inputs and declared outputs a parent can consume:
408
+ let approved = false;
409
+ for (let round = 1; round <= 2; round += 1) {
410
+ const review = await ctx.task(`review-${round}`, {
411
+ context: "fresh",
412
+ schema: reviewDecision,
413
+ prompt: [
414
+ `Review the current ${branch} diff against ${baseRef} for ${issue}.`,
415
+ "Inspect the code and tests. Approve only when the issue is fully met and the patch is safe.",
416
+ "Return structured_output with approved and evidence-backed findings.",
417
+ ].join("\n"),
418
+ });
419
+ const decision = review.structured as Static<typeof reviewDecision>;
420
+ if (decision.approved) {
421
+ approved = true;
422
+ break;
423
+ }
424
+ if (round === 2) {
425
+ throw new Error(`review bound exhausted: ${decision.findings.join("; ")}`);
426
+ }
427
+ await ctx.task(`repair-${round}`, {
428
+ context: "fork",
429
+ prompt: [
430
+ `Repair ${issue} on ${branch}.`,
431
+ ...decision.findings.map((finding) => `- ${finding}`),
432
+ "Run relevant checks and commit the repair. Do not create a PR.",
433
+ ].join("\n"),
434
+ });
435
+ }
436
+ if (!approved) throw new Error("review did not approve the patch");
316
437
 
317
- | Workflow | Required input | Bounded/defaulted knobs | Principal declared outputs |
318
- |---|---|---|---|
319
- | `classify-and-act` | `prompt` | `categories` (1–8), `confidence_threshold` (0.5–0.99) | `result`, `category`, `confidence`, classification/action paths |
320
- | `fan-out-and-synthesize` | `prompt` | `max_branches` (1–12), `max_concurrency` (1–12) | `result`, partitions, branch paths, synthesis/manifest paths |
321
- | `adversarial-verification` | `task` | `verifier_count` (1–5), `max_repairs` (0–5) | `result`, `approved`, repairs, candidate/review/verifier paths, remaining work |
322
- | `generate-and-filter` | `prompt` | `num_candidates` (2–20), `shortlist_size` (1–10), `use_judge`, `max_concurrency` | `result`, shortlist, candidate/filter/judge/final/manifest paths |
323
- | `tournament` | `prompt` | `num_attempts` (2–8), `max_concurrency` (1–8) | `result`, winner, attempt/judge/bracket paths |
324
- | `loop-until-done` | `prompt` | `max_iterations` (1–20) | `result`, `status`, ledger, iteration/evaluation paths, remaining work |
438
+ await ctx.tool("require-clean-commit", { branch }, async () => {
439
+ const pending = runCommand(["git", "status", "--porcelain"], cwd);
440
+ if (pending !== "") throw new Error("implementation left uncommitted changes");
441
+ return { commit: runCommand(["git", "rev-parse", "HEAD"], cwd) };
442
+ });
325
443
 
326
- Run them by name with `/workflow <name> ...` or import their definitions:
444
+ for (const [index, argv] of checks.entries()) {
445
+ await ctx.tool(`check-${index + 1}`, { argv }, async () => runCommand(argv, cwd));
446
+ }
327
447
 
328
- ```ts
329
- import {
330
- adversarialVerification, classifyAndAct, fanOutAndSynthesize,
331
- generateAndFilter, loopUntilDone, tournament,
332
- } from "@bastani/workflows/builtin";
448
+ await ctx.tool("push-feature-branch", { branch }, async () =>
449
+ runCommand(["git", "push", "--set-upstream", "origin", branch], cwd),
450
+ );
451
+ const prUrl = await ctx.tool("create-pr", { issue, branch, base: ctx.inputs.pr_base }, async () =>
452
+ runCommand(
453
+ ["gh", "pr", "create", "--base", ctx.inputs.pr_base, "--head", branch, "--title", issue, "--body", `Implements ${issue}.`],
454
+ cwd,
455
+ ),
456
+ );
333
457
 
334
- const child = await ctx.workflow(fanOutAndSynthesize, {
335
- inputs: { prompt: "Fix every migration call site", max_branches: 6 },
336
- stageName: "migration fix pass",
458
+ return {
459
+ result: `completed ${issue}`,
460
+ pr_url: prUrl,
461
+ branch,
462
+ worktree: cwd,
463
+ };
464
+ },
337
465
  });
338
- if (child.exited === false) console.log(child.outputs.synthesis_path);
339
466
  ```
340
467
 
341
- All six can be nested with `ctx.workflow(definition, { inputs, stageName })` and count toward `maxDepth` (default four workflow levels). Prefer composing these definitions over copying their prompts or graphs: nested children contribute their stages, dedicated prompts, gates, artifacts, HIL nodes, and declared outputs to the expanded parent graph. A migration parent can wrap a `fan-out-and-synthesize` fix pass in `loop-until-done` while tests fail, then invoke `adversarial-verification` for each resulting patch; the parent consumes declared artifact paths and decisions rather than recreating the three graphs.
468
+ The workflow binding creates or validates the reusable worktree before `run` starts. The first durable tool then creates or checks out the requested feature branch, so worktree setup's detached checkout never becomes the implementation branch. The item run owns branch setup implementation bounded review/repair deterministic checks push PR creation. A failed review or check fails that item before push/PR.
342
469
 
343
- Concrete migration composition:
470
+ Inspect the new target with `workflow({ action: "inputs", workflow: "issue-to-pr" })`. Then issue these two ordinary named-run tool calls in the same dispatch turn and end the turn. Interactive named launches return after startup admission instead of waiting for terminal completion, so the two run bodies overlap. Starting exactly two item runs and admitting no third until one ends enforces the bound of 2; the top-level tool has no batch-only worker loop or hidden concurrency field.
344
471
 
345
472
  ```ts
346
- import { adversarialVerification, fanOutAndSynthesize, loopUntilDone } from "@bastani/workflows/builtin";
473
+ workflow({
474
+ action: "run",
475
+ workflow: "issue-to-pr",
476
+ inputs: {
477
+ issue: "#2101 fix cache-key normalization",
478
+ git_worktree_dir: "../atomic-issue-2101",
479
+ base_ref: "origin/main",
480
+ pr_base: "main",
481
+ branch: "fix/2101-cache-key",
482
+ checks: [["bun", "test", "test/unit/cache-key.test.ts"]],
483
+ },
484
+ })
347
485
 
348
- const fixes = await ctx.workflow(fanOutAndSynthesize, {
349
- inputs: { prompt: "Fix every migration call site", max_branches: 6 },
350
- stageName: "migration fixes",
351
- });
352
- const verification = await ctx.workflow(adversarialVerification, {
353
- inputs: { task: `Verify every patch listed by ${fixes.outputs.manifest_path}` },
354
- stageName: "verify migration patches",
355
- });
356
- const convergence = await ctx.workflow(loopUntilDone, {
486
+ workflow({
487
+ action: "run",
488
+ workflow: "issue-to-pr",
357
489
  inputs: {
358
- prompt: `Run migration tests and repair remaining failures using ${fixes.outputs.manifest_path} and ${verification.outputs.review_report_path}.`,
359
- max_iterations: 5,
490
+ issue: "#2102 correct CLI help output",
491
+ git_worktree_dir: "../atomic-issue-2102",
492
+ base_ref: "origin/main",
493
+ pr_base: "main",
494
+ branch: "fix/2102-cli-help",
495
+ checks: [["bun", "test", "test/unit/cli-help.test.ts"]],
360
496
  },
361
- stageName: "loop while migration tests fail",
362
- });
497
+ })
363
498
  ```
364
499
 
365
- The parent can consume every child's precise declared outputs and can call `adversarialVerification` once per patch when its own typed input enumerates patch artifacts.
500
+ For a longer queue, wait for a terminal lifecycle notice before filling an open slot; do not poll. Keep each returned top-level run ID with its item metadata. Lifecycle notices carry terminal status/error, not declared workflow outputs.
366
501
 
367
- ### `deep-research-codebase`
502
+ After each terminal lifecycle notice, inspect the completed or failed run by its returned ID with the supported per-run status action:
368
503
 
369
- Inputs:
504
+ ```ts
505
+ workflow({ action: "status", runId: "<run-id-for-#2101>", format: "json" })
506
+ workflow({ action: "status", runId: "<run-id-for-#2102>", format: "json" })
507
+ ```
370
508
 
371
- | Input | Type | Required | Default | Description |
372
- |---|---|---|---|---|
373
- | `prompt` | text | yes | — | Research question or investigation focus. |
374
- | `max_partitions` | number | no | `100` | Maximum codebase partitions explored in parallel. Actual partitions scale by one per 10K LoC, capped by this value. |
375
- | `max_concurrency` | number | no | `100` | Maximum workflow stages running concurrently during deep research. |
509
+ Each JSON response has `action: "statusDetail"` and a `detail` object. Read `detail.status` and `detail.error`. For a completed run, read its declared outputs from `detail.result` and require a string `detail.result.pr_url` before filling that item's result/PR fields; do not infer the PR URL from the lifecycle notice or stage prose. A completed detail without the required result or `pr_url` is a reporting-contract failure.
376
510
 
377
- Run examples:
511
+ For a failed run, record `detail.error` and leave the PR field as `no PR` when the failure occurred before `create-pr`. If failure may have occurred during or after that durable tool, inspect its status/tool detail or the GitHub PR list before retrying so the dispatcher does not create a duplicate PR. In either case, free the dispatcher slot, keep unrelated top-level runs active, and do not treat a failed run's partial result as successful output. Only after these per-run inspections should the dispatcher fill the final map:
378
512
 
379
- ```text
380
- /workflow deep-research-codebase prompt="How do payment retries work end to end?"
381
- /workflow deep-research-codebase prompt="Map the workflow runtime" max_partitions=8 max_concurrency=4
382
- ```
513
+ | Item | Run ID | Worktree | Branch | Result / PR |
514
+ |---|---|---|---|---|
515
+ | `#2101` | `7f31a2c0-...` | `../atomic-issue-2101` | `fix/2101-cache-key` | `completed` / `<PR-2101-URL>` |
516
+ | `#2102` | `b84d090e-...` | `../atomic-issue-2102` | `fix/2102-cli-help` | `failed: review/repair bound exhausted` / no PR |
383
517
 
384
- Workflow tool call:
518
+ The second failure does not cancel, pause, or roll back the first run, and it does not block unrelated later items from using an open dispatcher slot. A first item's review, repair, or check failure must not block unrelated items; if it would, reconsider whether the queue was placed in one root workflow by mistake.
385
519
 
386
- ```ts
387
- workflow({
388
- action: "run",
389
- workflow: "deep-research-codebase",
390
- inputs: { prompt: "map workflow runtime", max_concurrency: 4 },
391
- })
392
- ```
520
+ This example uses **top-level named runs**, not nested `ctx.workflow(...)` children. Each launch appears in top-level status, gets its own lifecycle notices and controls, and owns an independent root failure boundary. Nested children are hidden from top-level run lists and expand inside one parent graph; a failed child call normally fails its parent, and parent exit cancels in-flight children. Use nested children to preserve ordered composition inside a truly dependent item or cluster, not to claim separate root lifecycles for independent queue items.
393
521
 
394
- Output locations and result fields:
522
+ The factory self-prompt is: **enumerate → inspect and classify dependencies → fan out top-level runs where independent → compose where dependent → dispatch in bounded waves → report the map.**
395
523
 
396
- | Field | Meaning |
397
- |---|---|
398
- | `result` | Final Markdown research report text, matching `findings`. |
399
- | `findings` | Final Markdown research report text. |
400
- | `research_doc_path` | Public report path under `research/<date>-<topic>.md`. If a file already exists, the workflow writes a suffixed filename. |
401
- | `artifact_dir` | Hidden per-run handoff directory under `research/.deep-research-<run-id>/`. |
402
- | `manifest_path` | Manifest JSON path inside the hidden artifact directory. |
403
- | `partitions` | Codebase partitions the specialists explored. |
404
- | `explorer_count` | Number of partition explorer groups used. |
405
- | `specialist_count` | Number of specialist stages run across the research waves. |
406
- | `max_concurrency` | Concurrency limit used for the run. |
407
- | `history` | Prior-research/history overview included in the final synthesis. |
408
-
409
- People can read, commit, or share the dated Markdown report. The hidden artifact directory keeps large scout, history, and specialist handoff files available for audit without cluttering the visible research index.
524
+ #### Prompting the choice
410
525
 
411
- ### `goal`
526
+ Humans can steer the shape directly:
412
527
 
413
- Inputs:
528
+ - **Name the shape or installed workflow.** "Do this inline", "use subagents to investigate", or "write a custom workflow for this" overrides automatic scoring.
529
+ - **State acceptance criteria.** Verbatim criteria make the objective provable and define reviewer and reducer contracts.
530
+ - **State the loop.** "Iterate until tests pass" or "review and fix until approved" defines a hard workflow stop condition.
531
+ - **State the evidence.** A QA video, test output, generated artifact, or reviewer sign-off tells the graph which gates it needs.
532
+ - **State the boundary.** "Work in a separate worktree", "do not create a PR", or "stop after implementation" separates implementation from final actions.
533
+ - **State the queue policy.** Say how to split, order, isolate, and bound queued items; otherwise Atomic runs the [dependency-triage and bounded-dispatch playbook](#task-queues-and-software-factories) before implementation. Ordinary list order and per-item "create a PR after" wording do not create a cross-item dependency.
414
534
 
415
- | Input | Type | Required | Default | Description |
416
- |---|---|---|---|---|
417
- | `objective` | text | yes | — | Goal-runner objective or delta. Include the desired end state, expected outcome, testing/validation instructions, and any explicit done criteria. Do not include PR/MR submission instructions here; strip them from the task text and request them via `create_pr=true` instead. |
418
- | `acceptance_criteria` | text | no | objective | Original immutable task contract that the run must remain consistent with. When launching a follow-up `goal` run from review findings, pass the ORIGINAL task text here so reviewer suggestions cannot drift or contradict the literal contract. |
419
- | `max_turns` | number | no | `10` | Maximum worker/review turns before human follow-up is needed. |
420
- | `base_branch` | string | no | `origin/main` | Branch reviewers and the optional final stage compare the current code delta against; also used to create a missing worktree. |
421
- | `git_worktree_dir` | string | no | `""` | Optional reusable Git worktree root. Empty runs in the invoking checkout; non-empty values run Goal stages in the created/reused worktree. Set it only when the user explicitly requested worktree isolation — worker stages are instructed never to create git worktrees, clones, or repository copies on their own. |
422
- | `create_pr` | boolean | no | `false` | Safe-by-default PR creation flag. Omitted or `false` skips the final `pull-request` stage and omits `pr_report`; prompt text alone does not opt in, and only strict `true` authorizes the final `pull-request` stage to attempt provider-appropriate PR/MR/review creation after Goal reaches `complete`. If the delegated task asks to submit a PR/MR/review, remove that instruction from `objective` and set `create_pr=true` instead. |
535
+ Absent these controls, Atomic applies the self-prompt and rubric above; a prompt that names none of them delegates the shape decision rather than avoiding it.
423
536
 
424
- `goal` defaults to 10 worker/review turns. Reviewer quorum is fixed internally at 2 reviewer `complete` votes, and approval is deterministic on each reviewer's self-reported `stop_review_loop` boolean: a reviewer approves exactly when it returns `stop_review_loop=true` with no `reviewer_error` (schema-parse failures count as non-approval), and the reducer completes the run when quorum of those booleans is met without recomputing approval from findings arrays or traceability statuses. The repeated-blocker threshold defaults to 3 consecutive same-blocker turns and is clamped to `max_turns` when you run fewer than 3 turns.
537
+ ### Atomic vs Claude Code Dynamic Workflows
425
538
 
426
- Run examples:
539
+ Claude Code Dynamic Workflows and Atomic address a similar problem: important software engineering work is too large for one agent pass, so the system should split the job into stages, run agents in parallel, verify the result, and keep enough state to finish long-running work.
427
540
 
428
- ```text
429
- /workflow goal objective="Implement specs/2026-03-rate-limit.md, add the requested regression tests, run bun test packages/api/rate-limit.test.ts, and finish only when burst traffic returns 429 with Retry-After"
430
- /workflow goal objective="Update the CLI docs to describe the new --json flag, include one usage example, and verify the docs build still passes" max_turns=3
431
- /workflow goal objective="Fix the settings form validation bug; add/adjust the focused test and consider it done when invalid emails show the inline error without submitting"
432
- /workflow goal objective="Implement the focused docs fix and run the docs validation command" create_pr=true
433
- /workflow goal objective="Fix the flaky package install test in an isolated worktree and run the focused regression" git_worktree_dir=../atomic-goal-install-wt base_branch=main
434
- ```
541
+ Atomic's category is broader and more explicit: it is the loop engine for engineering work. The difference is who controls the process and how much of the loop you can inspect, version, extend, and connect to your stack.
435
542
 
436
- `goal` uses the raw `objective` exactly as supplied as the operative objective recorded in the ledger and stores `acceptance_criteria` as the immutable literal contract (defaulting to the objective when omitted); it does not run an initial prompt-refinement stage. It creates an OS-temp `goal-ledger.json` artifact, renders goal-continuation context for each worker turn, writes the latest worker receipt to `worker-receipt.md`, and appends receipts, reviewer decisions, blockers, reducer decisions, and lifecycle events to the ledger.
543
+ | Dimension | Atomic | Claude Code Dynamic Workflows |
544
+ | --- | --- | --- |
545
+ | Core idea | Open-source, repo-native loop engine for coding agents. You can run built-ins, tell the coding agent to use a workflow for a task, describe new loops in natural language for Atomic to scaffold dynamically, or version them as explicit TypeScript files. | Claude dynamically creates orchestration scripts for a task and fans work out to many parallel Claude subagents. |
546
+ | Best fit | Teams that want repeatable software engineering loops they can inspect, version, extend, connect to tools, and run across providers. | Claude Code users who want Claude to decide when a task needs a larger dynamic workflow and orchestrate it automatically. |
547
+ | Workflow control | The process is explicit: stages, inputs, handoffs, retries, artifacts, model choices, checkpoints, and human gates are part of the workflow definition. | The process is generated dynamically by Claude for the current task, with confirmation before the first workflow run. |
548
+ | Models | Model-agnostic. Atomic connects directly to supported API-key and subscription providers, and workflows can use model fallback chains. | Claude-first. Availability is tied to Claude Code, Claude plans, and Anthropic-supported API/cloud channels. |
549
+ | Extensibility | Built on Pi extensions: add tools, TUI, MCP, web access, intercom, skills, prompt templates, themes, custom providers, and packaged workflows. | Optimized for Claude Code's built-in dynamic orchestration experience rather than an open extension SDK you own in-repo. |
550
+ | Artifacts and auditability | Research docs, specs, logs, transcripts, reviewer notes, check output, and final summaries can live in the repo or workflow run directory. | Progress is saved and resumable, but the orchestration is primarily a Claude Code runtime behavior. |
551
+ | Cost/scale posture | You choose the graph and concurrency. Atomic can be small and deterministic, or broad when you intentionally design a larger workflow. | Designed for large fan-outs, including tens to hundreds of subagents; Anthropic notes it can consume substantially more tokens than a typical Claude Code session. |
437
552
 
438
- Worker and reviewer prompts (and the model-facing ledger artifact) deliberately omit the current turn/attempt number so the worker focuses on completing the objective rather than pacing itself to the workflow budget. Worker and reviewer prompts treat the objective as user-provided data, not higher-priority instructions. By default `goal` does not start the final `pull-request` stage, and `pr_report` is omitted. Prompt text alone does not opt in.
553
+ ## The Run Contract
439
554
 
440
- Pass `create_pr=true` only when you explicitly want the final stage to inspect provider credentials and attempt provider-appropriate PR/MR/review creation, such as GitHub `gh`, Azure Repos `az repos pr create`, or Sapling/Phabricator tooling, after Goal reaches `complete` within `max_turns`. Goal worker and reviewer prompts explicitly tell intermediate stages to ignore PR-creation requests; only the final `pull-request` stage may attempt that handoff.
555
+ **A run's contract is its objective plus its acceptance criteria. Only the user may change it. Every stage that receives a change must hand it to the next stage.**
441
556
 
442
- Set `git_worktree_dir` when you want Goal's worker and reviewer stages isolated in a reusable Git worktree. Relative paths resolve from the invoking repository root, existing same-repository worktree roots are reused, and missing paths are created from `base_branch`. Goal preserves the invoking repo-relative cwd inside the worktree, so launching from `repo/packages/api` with `git_worktree_dir=../repo-wt` runs stages from `../repo-wt/packages/api`.
557
+ This is the single most important rule for getting predictable results out of a multi-stage run, and it is the rule most often broken by accident.
443
558
 
444
- If the run is resumed later with `/workflow resume`, Atomic reuses the original invocation cwd and recorded reusable-worktree metadata instead of resolving the worktree path from the resumed chat's current cwd. Slow Git subprocesses can run for up to 60 seconds before Atomic reports an explicit Git timeout diagnostic.
559
+ ### Only the user may change the contract
445
560
 
446
- Write the `objective` as a compact acceptance spec. Define the desired end state, required testing, relevant commands or manual checks, and the outcome that proves completion. The workflow is intentionally lean: it does not first generate an RFC or migration plan, so the developer-supplied objective is where scope, validation, and completion criteria belong.
561
+ A workflow launches with a contract: the objective and, when supplied, explicit acceptance criteria. Two parties relate to it very differently:
447
562
 
448
- Goal worker/reviewer prompts treat the objective and acceptance criteria as the sole literal source of truth: if follow-up deltas, language specs, upstream issues, in-repo comments, or best practices conflict with explicit wording, reviewers surface the conflict instead of silently implementing external knowledge.
563
+ - **You may amend it at any time.** A mid-run message steering, a follow-up, resume text is authoritative. If you say "also handle the detached path," that is a new requirement, and the run adopts it from that moment.
564
+ - **Agents may not amend it at all.** An implementer that notices a nearby bug, a cleaner abstraction, or a missing feature has found *deferred work*, not a new criterion. It records the observation and keeps building to the contract.
449
565
 
450
- Reviewer findings carry `objective_alignment` (`required_by_objective`, `consistent_with_objective`, `beyond_objective`, or `contradicts_objective`); `beyond_objective` and `contradicts_objective` findings are reported but do not block completion and must not be promoted into follow-up objectives without reconciling them against the acceptance criteria. Severity labels alone never dismiss objective-relevant findings: `required_by_objective` findings block at any priority (P3 included), while `consistent_with_objective` P3 nice-to-haves stay non-blocking.
566
+ ### Amendments must reach the next stage
451
567
 
452
- Review decisions also include `requirements_traceability`, a clause-by-clause evidence map over every explicit objective/acceptance-criteria requirement. Findings and traceability are audit evidence that drive how each reviewer derives its authoritative `stop_review_loop` boolean; the harness gates approval on that boolean alone, and Goal tells reviewers that process-only clauses (reviewer quorum/approval counts, and the authorized post-approval PR/MR/review final action when `create_pr=true`) must never hold the flag at `false`. Reviewers must also first prove the code delta actually exists in the review checkout (the invoking cwd or explicitly configured worktree): receipts claiming implemented work over an empty or unrelated delta are a blocking finding rather than grounds for approval, and modifications, renames, or deletions of pre-existing tests require explicit justification.
568
+ An amendment that stays inside the session that received it is invisible to everything downstream. That produces the failure this rule exists to prevent:
453
569
 
454
- Passing worker-authored tests or snapshots alone is circular evidence unless tied to independent current-state proof.
570
+ > You steer the implementation stage to add a requirement. The implementer adopts it and builds it. The reviewers were launched with the original criteria, so they score the added work as unrequested scope and the original criteria as contradicted. The run then burns review loops arguing about a contract mismatch nobody can see.
455
571
 
456
- The worker may claim readiness, but it cannot finalize completion. Before implementing, Goal prompts the worker to derive an observable acceptance/contract matrix from the literal objective/acceptance criteria (one row per clause, each mapped to the concrete check that proves it) and to model states, transitions, and invariants explicitly when the work is stateful.
572
+ So every builtin stage prompt carries a **steering propagation contract**:
457
573
 
458
- Delivery is part of readiness: unless the objective or acceptance criteria explicitly forbid committing, worker prompts require committing the work in the current checkout with a descriptive message before claiming readiness — verifying a clean working tree with the repository's version-control status command — and reporting the commit identifier in the receipt. Reviewers back this with the code-delta contract: uncommitted work at claimed readiness is remaining work, and a checkout whose delta is empty or unrelated to the objective can never be approved regardless of what receipts claim. Verification stays with prompts and reviewers using the repository's own version-control tooling, so no single VCS provider is hardcoded into the runner.
574
+ - Restate every objective-relevant steering message in your report or handoff artifact, under an explicit `Contract amendments received` heading, verbatim when short.
575
+ - Keep user-authored amendments visibly separate from your own observations, so the next stage can tell a required clause from an agent proposal.
576
+ - Treat amendments inherited from an upstream stage as contract clauses. Cover them in acceptance and traceability work; never classify them as out-of-scope.
577
+ - Resolve ambiguity before implementing. Use `intercom` to ask the supervisor or originating stage when one is reachable; otherwise state the conflict and implement the narrowest reading consistent with the launch contract.
578
+ - Propagate nothing else this way. Tool preferences, working style, and your own ideas are not amendments.
459
579
 
460
- Goal consolidates the latest reviewer findings into a deduplicated cross-reviewer batch persisted in the round artifact (`consolidated_findings` in `review-round-latest.json`), and the next worker prompt instructs the worker to plan and repair the whole batch with durable regression evidence for reproduced findings — rather than fixing one finding per turn. Goal prompts workers and reviewers to verify user-visible behavior end-to-end when practical, using `playwright-cli`-skilled subagents for web/frontend flows that may depend on backend/API behavior and tmux-skilled subagents for TUI or terminal-app scenarios.
580
+ Every bundled workflow wraps its run context once at the definition entry point, so each `ctx.task`, `ctx.chain`, and `ctx.parallel` prompt carries the contract automatically. Do the same in a custom workflow:
461
581
 
462
- They must assume credentials/auth/environment access exists until concrete checks plus an actual app/flow launch attempt prove otherwise; reviewers accept skipped E2E only when the worker records the exact attempted commands and observed failure output. Goal reviewers also look for any QA E2E video referenced by the ledger or receipt and must inspect the actual video before treating it as proof.
582
+ ```ts
583
+ import { withSteeringPropagationContext } from "@bastani/workflows/builtin/steering-context";
463
584
 
464
- Three reviewers independently inspect the ledger, worker receipt, repository state, and diff against `base_branch`; each starts in a clean, non-forked context, matching Ralph's reviewer context behavior, and every Goal reviewer uses Ralph's `reviewer-a` model chain with Claude Fable 5 as the primary model.
585
+ export default workflow({
586
+ name: "my-workflow",
587
+ // ...
588
+ run: async (ctx) => await runMyWorkflow(withSteeringPropagationContext(ctx)),
589
+ });
590
+ ```
465
591
 
466
- Goal instructs each reviewer to first derive its own adversarial check list from the literal contract boundary/edge/negative probes plus state/transition/invariant probes before relying on the worker receipt or worker-authored tests, and each returns structured JSON with findings, evidence, verification still remaining, and an optional blocker.
592
+ Wrapping the context rather than each call site means a stage added later inherits the pattern instead of silently dropping amendments.
467
593
 
468
- A TypeScript reducer marks the goal complete when reviewer quorum approves via the `stop_review_loop` booleans, marks blocked only when the same dependency/tool blocker repeats for the blocker threshold, continues while quorum is missing (recording the reviewers' remaining work in the decision reason), and returns `needs_human` when `max_turns` is exhausted or worker execution fails, so the bounded loop always stops with an inspectable reason.
594
+ ### Scope discipline
469
595
 
470
- At the start of every Goal review, each concurrent reviewer uses [Intercom](/intercom) to initialize/check coordination and discover the sibling reviewers in the same workflow run. Before validation, reviewers communicate their plans and intended ownership, claim expensive or lock-prone checks, and serialize commands that can conflict in a shared checkout or environment, including full test suites, build or test commands, package-manager operations, browser/E2E sessions, migrations, and generated-artifact steps.
596
+ The mirror of "only the user may amend" is that the agent holds the line. Every builtin implementation stage carries this contract:
471
597
 
472
- They announce each coordinated check's start and completion, release every claimed resource and send siblings an explicit resource-release update, and share reusable command outcomes/evidence where appropriate. This operational coordination prevents collisions and duplicate conflicting work; it does not replace independent patch inspection, analysis, or each reviewer's own verdict.
598
+ > Before writing code, state the goal in one sentence and list the acceptance criteria. That list is the contract. Freeze it.
473
599
 
474
- When Goal's reducer returns `needs_human`, `blocked`, or another incomplete status, Atomic does not report the top-level workflow run as successful. `/workflow status` and lifecycle notices surface it as blocked/failed according to the run's terminal condition. Atomic also preserves structured recoverable failure metadata from the run's blocking stage (`failedStageId`) or run-level failure metadata, so auth, rate-limit, and provider fallback exhaustion remains blocked/resumable even if the workflow later returns ordinary outputs instead of a reserved `status` value. Tolerated branch failures from non-fail-fast parallel work do not reclassify an otherwise completed run.
600
+ While implementing:
475
601
 
476
- Each Goal review round persists a convergence summary. Each reviewer record and review artifact distinguishes schema-parse status from the review verdict with `parsed`, `approved`, `stopReviewLoop`, `nextAction`, `finalActionRemaining`, and `diagnostics` fields; each reports malformed or missing structured reviewer output as a parse failure rather than as an ordinary finding/rejection.
602
+ - **Done means the contract, not "good."** When all criteria pass, stop. Polish, refactors, and "while I'm here" fixes are new work, not this work.
603
+ - **Every addition must trace to a criterion.** If you cannot point at the criterion a change serves, do not make it. Log it instead.
604
+ - **Keep a deferred list, not a growing diff.** When you notice a bug, smell, or missing feature outside the contract, write one line in a deferred note and move on. Surface it at the end.
605
+ - **Distinguish blockers from improvements.** Change scope only if a criterion is impossible or wrong as written — and say so explicitly before proceeding, rather than silently absorbing the work.
606
+ - **Watch for the tells.** "It would be cleaner if…", "we should also…", "this really ought to…" mean you are about to move the goalpost. Stop and check the contract.
607
+ - **Prefer the smallest diff that satisfies the contract.** Fewer files touched, fewer abstractions introduced, no speculative generality for futures nobody asked for.
477
608
 
478
- When `create_pr=true`, reviewers are told that PR/MR/review creation is a post-approval final action: if implementation and validation requirements are proven and only PR creation remains, the implementation can approve with `finalActionRemaining: true` and `nextAction: "pull-request"` instead of consuming another worker turn. The ledger's reducer decision repeats the same concise fields for the controller outcome, so a successful quorum records `approved: true`, `stopReviewLoop: true`, and `nextAction: "pull-request"` when `create_pr=true` (otherwise `"finish"`) before any final handoff runs.
609
+ At the end, report three things: what the contract was, evidence each criterion passes, and the deferred list. Scope changes belong in the report, never in the diff.
479
610
 
480
- Result fields:
611
+ ### Practical consequences
481
612
 
482
- | Field | Meaning |
483
- |---|---|
484
- | `result` | Final report with objective, status, receipts, turns, and remaining work. |
485
- | `status` | Final reducer status: `complete`, `blocked`, or `needs_human` (or `active` only if externally interrupted). |
486
- | `approved` | Whether the reducer reached `complete`. |
487
- | `goal_id` | Per-run goal identifier stored in the ledger. |
488
- | `objective` | Raw goal objective used by the run. |
489
- | `acceptance_criteria` | Immutable acceptance criteria used by the run. |
490
- | `ledger_path` | OS-temp path to `goal-ledger.json`, including receipts, reviewer decisions, reducer decisions, blockers, and lifecycle events. |
491
- | `turns_completed` | Worker/review turns completed. |
492
- | `iterations_completed` | Same value as `turns_completed`, retained for status summaries. |
493
- | `receipts` | Ledger receipt summaries and worker artifact paths. |
494
- | `remaining_work` | Remaining gaps/blockers when incomplete, or `none`. |
495
- | `review_report` | Markdown report containing the last structured reviewer decision payloads used by the reducer. |
496
- | `review_report_path` | JSON artifact path for the latest Goal review round. |
497
- | `pr_report` | Pull-request report emitted only when `create_pr=true`, Goal reaches `complete`, and the final `pull-request` stage runs. |
613
+ - **Steer freely it is the supported amendment channel.** You do not need to restart a run to add a requirement.
614
+ - **Say what you mean as a requirement.** "It would be nice if…" reads as guidance; "also handle X" reads as a clause. Stages are told to distinguish them.
615
+ - **Expect amendments in the reports.** If a stage received one and its report has no `Contract amendments received` section, the amendment did not propagate and downstream stages will not honor it.
616
+ - **A growing diff with no new criteria is a defect.** That is the tell that scope discipline slipped, and it is a legitimate reason to stop a run.
498
617
 
499
- ### `ralph`
618
+ ## Built-in Workflows
500
619
 
501
- Inputs:
620
+ Atomic bundles nine workflows: six reusable control-flow patterns, two autonomous implementation loops, and one end-to-end design workflow. They are available in every session. Use `/workflow list` to confirm the current set and `/workflow inputs <name>` to inspect a contract before launch.
502
621
 
503
- | Input | Type | Required | Default | Description |
504
- |---|---|---|---|---|
505
- | `prompt` | text | yes | | Task, feature request, issue summary, or spec path to research, execute, refine, and review. Do not include PR/MR submission instructions here; strip them from the task text and request them via `create_pr=true` instead. |
506
- | `acceptance_criteria` | text | no | prompt | Original immutable task contract that the run must remain consistent with. When launching a follow-up `ralph` run from review findings, pass the ORIGINAL task text here so reviewer suggestions cannot drift or contradict the literal contract. |
507
- | `max_loops` | number | no | `10` | Maximum research/orchestrate/review iterations before the workflow completes or reports the remaining work without reviewer approval. |
508
- | `base_branch` | string | no | `origin/main` | Branch reviewers and the optional final stage compare the current code delta against; also used to create a missing worktree. |
509
- | `git_worktree_dir` | string | no | `""` | Optional reusable Git worktree root. Empty runs in the invoking checkout; non-empty values run Ralph stages in the created/reused worktree. Set it only when the user explicitly requested worktree isolation — orchestrator stages are instructed never to create git worktrees, clones, or repository copies on their own. |
510
- | `create_pr` | boolean | no | `false` | Safe-by-default PR creation flag. Omitted or `false` skips the final `pull-request` stage and omits `pr_report`; prompt text alone does not opt in, and only strict `true` authorizes the final `pull-request` stage to attempt provider-appropriate PR/MR/review creation. If the delegated task asks to submit a PR/MR/review, remove that instruction from `prompt` and set `create_pr=true` instead. |
622
+ | Workflow | What it does | When to use |
623
+ |---|---|---|
624
+ | `classify-and-act` | Structured classifier deterministic category action; low confidence can fall back to human selection. | Route mixed requests to isolated category-specific work. |
625
+ | `fan-out-and-synthesize` | Structured partition bounded parallel artifact branches synthesis barrier. | Split independent slices, including repository research, and merge evidence. |
626
+ | `adversarial-verification` | Worker fresh rubric verifiers reducer bounded repair loop. | Independently prove or reject a candidate. |
627
+ | `generate-and-filter` | Candidate fan-out rubric dedupe/filter optional judge shortlist. | Explore more options than needed and keep the strongest distinct few. |
628
+ | `tournament` | Whole-task attempts balanced pairwise judges bracket reducer. | Compare subjective or approach-sensitive solutions. |
629
+ | `loop-until-done` | Durable ledger iteration/evaluator loop success or inspectable bound exhaustion. | Continue until explicit evidence proves completion. |
630
+ | `goal` | Durable goal ledger → bounded sub-agent orchestration → parallel review → deterministic reducer. | Autonomous implementation that needs receipts and reviewer-gated completion. |
631
+ | `ralph` | Prompt refinement → codebase research → delegated implementation → multi-model review loop. | Research-first autonomous implementation with bounded review and repair. |
632
+ | `open-claude-design` | Guided discovery and reference research → HTML generation → feedback loop → export and handoff. | UI, page, component, theme, or design-token work. |
511
633
 
512
- Run examples:
634
+ Across these builtins, model-facing stages use compact, outcome-first contracts tuned for GPT-5.6, Claude Opus 5, and Claude Fable 5. Long artifacts and receipts are rendered before the final instruction, reporting stages ground completion claims in current tool evidence, and user-facing or downstream reports have explicit shape and length bounds. Orchestrators delegate only genuinely independent work that is too large for a handful of tool calls, rather than spawning agents to recheck their own work.
513
635
 
514
- ```text
515
- /workflow ralph prompt="Migrate the database layer to Drizzle" max_loops=3 base_branch=develop
516
- /workflow ralph prompt="Refactor authentication across the API, CLI, and web UI" create_pr=true
517
- /workflow ralph prompt="Safely implement the API refactor" git_worktree_dir=../atomic-ralph-api-wt base_branch=main
518
- ```
636
+ ### Six composable pattern builtins
519
637
 
520
- Each `ralph` run uses the raw `prompt` exactly as supplied as the operative objective for research, orchestration, and review, and stores `acceptance_criteria` as the immutable literal contract (defaulting to the prompt when omitted). Shared literal-contract prompt language forbids adding behaviors, restrictions, or error conditions beyond the prompt/acceptance criteria and requires surfacing conflicts with external knowledge; Ralph does not run an initial prompt-refinement stage.
638
+ The six common patterns are full definitions exported from `@bastani/workflows/builtin`:
521
639
 
522
- Each iteration transforms that raw prompt with `/skill:prompt-engineer Transform the following user request into a codebase and online research question which can be thoroughly explored: ...` (`research-prompt-refinement`), researches that transformed question with `/skill:research-codebase ...`, and writes the findings under `research/`. The research, orchestrator, and reviewer prompts carry `acceptance_criteria` next to the literal contract, so orchestrators should pass the ORIGINAL task text when launching follow-up Ralph runs from reviewer findings.
640
+ | Workflow | Required input | Bounded/defaulted knobs | Principal declared outputs |
641
+ |---|---|---|---|
642
+ | `classify-and-act` | `prompt` | `categories` (1–8), `confidence_threshold` (0.5–0.99) | `result`, category, confidence, classification/action paths |
643
+ | `fan-out-and-synthesize` | `prompt` | `max_branches` (1–12), `max_concurrency` (1–12) | `result`, partitions, branch paths, synthesis/manifest paths |
644
+ | `adversarial-verification` | `task` | `verifier_count` (1–5), `max_repairs` (0–5) | `result`, approval, repairs, candidate/review/verifier paths |
645
+ | `generate-and-filter` | `prompt` | `num_candidates` (2–20), `shortlist_size` (1–10), `use_judge`, `max_concurrency` | `result`, shortlist, candidate/filter/judge/final/manifest paths |
646
+ | `tournament` | `prompt` | `num_attempts` (2–8), `max_concurrency` (1–8) | `result`, winner, attempt/judge/bracket paths |
647
+ | `loop-until-done` | `prompt` | `max_iterations` (1–20) | `result`, `status`, ledger, iteration/evaluation paths, remaining work |
523
648
 
524
- Before implementing, Ralph prompts the orchestrator to derive an observable acceptance/contract matrix from the literal prompt/acceptance criteria (one row per clause mapped to the concrete observable check that proves it) and to model states, transitions, and invariants explicitly when the work is stateful.
649
+ ```ts
650
+ import {
651
+ adversarialVerification,
652
+ classifyAndAct,
653
+ fanOutAndSynthesize,
654
+ generateAndFilter,
655
+ goal,
656
+ loopUntilDone,
657
+ ralph,
658
+ tournament,
659
+ } from "@bastani/workflows/builtin";
525
660
 
526
- It treats the research artifact as its primary implementation context, initializes/updates an OS-temp implementation notes file while generating verifiable evidence for any claims it records in the notes and reviewer artifacts, delegates implementation through sub-agents, repairs unresolved reviewer findings as one consolidated batch (with durable regression evidence for reproduced findings) rather than one finding per iteration, and asks two independent reviewers (`reviewer-a` and `reviewer-b`) to inspect the patch directly against `base_branch`.
661
+ const research = await ctx.workflow(fanOutAndSynthesize, {
662
+ inputs: {
663
+ prompt: "Map the repository by independent subsystem and synthesize cited findings.",
664
+ max_branches: 6,
665
+ },
666
+ stageName: "repository research",
667
+ });
668
+ ```
527
669
 
528
- The reviewer fan-out runs reviewers on different primary model families (Claude Fable 5 and GPT-5.5 Codex, with shared fallbacks) so the adversarial review gets cross-model coverage instead of repeated passes from one model, and Ralph instructs each reviewer to first derive its own adversarial check list from the literal contract boundary/edge/negative probes plus state/transition/invariant probes before relying on the implementation notes, orchestrator report, or worker-authored tests.
670
+ All six can run by name or as nested definitions. Prefer composition over copying prompts or graphs: nested children contribute stages, gates, artifacts, HIL nodes, and declared outputs to the expanded parent graph. For broad repository work, write a precise partition prompt, give branches distinct artifact paths, and make synthesis cite concrete files and resolve conflicts. For implementation, author a task-specific parent around the pattern builtins so its literal contract, deterministic checks, repair policy, and final actions stay explicit.
529
671
 
530
- Ralph prompts its orchestrator and reviewers to verify user-visible behavior end-to-end when practical, using `playwright-cli`-skilled subagents for web/frontend flows that may depend on backend/API behavior and tmux-skilled subagents for TUI or terminal-app scenarios. They must assume credentials/auth/environment access exists until concrete checks plus an actual app/flow launch attempt prove otherwise; reviewers accept skipped E2E only when the orchestrator records the exact attempted commands and observed failure output.
672
+ ### `goal`
531
673
 
532
- For UI-applicable or full-stack changes, the orchestrator runs a `playwright-cli` end-to-end QA pass and records a reviewable proof video (referenced in the implementation notes and surfaced as `qa_video_path`); reviewers receive that path and must inspect the actual video before treating it as proof. When `create_pr=true`, the final `pull-request` stage attaches or links that video to the created PR/MR/review after reviewer approval.
674
+ Goal persists the literal objective and immutable acceptance criteria in a run ledger, delegates implementation through bounded orchestrator turns, records receipts, and asks independent reviewers to inspect the current delta. A TypeScript reducer returns `complete`, `blocked`, or `needs_human` rather than trusting free-form completion claims.
533
675
 
534
- If reviewers find issues, the next `research-prompt-refinement` and research stages receive the review artifact path (whose `review-round-latest.json` carries a deduplicated cross-reviewer `consolidated_findings` batch) so follow-up research can address unresolved findings, and research stages fork from prior research session data when available. The loop stops only when both reviewers independently approve or `max_loops` is reached, so the bounded loop always stops with an inspectable review round.
676
+ Goal reviewers derive checks from the literal objective before consulting implementation receipts, inspect the actual checkout delta, and report commands, observed output, and file:line evidence rather than internal reasoning. Shared contracts cover acceptance-matrix traceability, contract-fidelity risks, end-to-end and QA-video evidence, and independent verification. `stop_review_loop` is the authoritative convergence signal: it remains `false` for P0–P2 findings, any `required_by_objective` finding, or unproven implementation/validation requirements; it becomes `true` only when independent evidence proves the objective and only non-blocking or authorized post-approval work remains. The deterministic reducer consumes that signal without reinterpreting free-form prose.
535
677
 
536
- Ralph findings include the same `objective_alignment` classification used by Goal, and each reviewer derives a single authoritative `stop_review_loop` boolean from that evidence: `required_by_objective` findings mean `false` at any priority (P3 included, because severity labels alone never dismiss objective-relevant findings), `consistent_with_objective` P0/P1/P2 findings mean `false` while P3 remains a non-blocking nice-to-have, and `beyond_objective`/`contradicts_objective` findings are surfaced but non-blocking so they are not silently converted into new requirements.
678
+ | Input | Type | Required | Default | Description |
679
+ |---|---|---|---|---|
680
+ | `objective` | text | yes | — | Task to implement and validate. Keep PR/MR creation out of this text. |
681
+ | `acceptance_criteria` | text | no | objective | Immutable original contract, especially for follow-up runs. |
682
+ | `max_turns` | number | no | `10` | Maximum orchestrator/review turns. |
683
+ | `base_branch` | string | no | `origin/main` | Review and optional final-action comparison base. |
684
+ | `git_worktree_dir` | string | no | `""` | Optional reusable worktree, only when explicitly requested. |
685
+ | `create_pr` | boolean | no | `false` | Authorize the post-approval PR/MR/review stage. Prompt text alone never opts in. |
537
686
 
538
- The loop gate approves deterministically on `stop_review_loop=true` plus a null `reviewer_error` (parse failures count as non-approval) without recomputing approval from the findings arrays. Ralph review decisions also include `requirements_traceability`, a clause-by-clause evidence map over every explicit prompt/acceptance-criteria requirement kept as audit evidence for deriving the flag; reviewers are explicitly told that process-only clauses (reviewer quorum, and the authorized post-approval PR/MR/review final action when `create_pr=true`) must never hold the flag at `false`. Reviewers must also first prove the code delta actually exists in the review checkout (the invoking cwd or explicitly configured worktree): receipts claiming implemented work over an empty or unrelated delta are a blocking finding rather than grounds for approval, and modifications, renames, or deletions of pre-existing tests require explicit justification.
687
+ ```text
688
+ /workflow goal objective="Update the CLI docs for --json, add one example, and validate the docs build"
689
+ /workflow goal objective="Implement specs/rate-limit.md and run focused checks" create_pr=true
690
+ ```
539
691
 
540
- Passing worker-authored tests or snapshots is circular evidence unless tied to independent current-state proof. By default Ralph does not start the final `pull-request` stage, and `pr_report` is omitted. Prompt text alone does not opt in. Pass `create_pr=true` only when you explicitly want the final `pull-request` stage to inspect provider credentials and attempt provider-appropriate PR/MR/review creation, such as GitHub `gh`, Azure Repos `az repos pr create`, or Sapling/Phabricator tooling; Ralph's own PR-creation instructions live in that final stage and run only after approval.
692
+ Declared outputs include `result`, `status`, `approved`, `goal_id`, `objective`, `acceptance_criteria`, `ledger_path`, turn counts, receipts, remaining work, review artifacts, and optional `pr_report`.
541
693
 
542
- At the start of every Ralph review, each concurrent reviewer uses Intercom to initialize/check coordination and discover the sibling reviewer in the same workflow run. Before validation, reviewers communicate their plans and intended ownership, claim expensive or lock-prone checks, and serialize commands that can conflict in a shared checkout or environment, including full test suites, build or test commands, package-manager operations, browser/E2E sessions, migrations, and generated-artifact steps.
694
+ ### `ralph`
543
695
 
544
- They announce each coordinated check's start and completion, release every claimed resource and send the sibling an explicit resource-release update, and share reusable command outcomes/evidence where appropriate. This operational coordination prevents collisions and duplicate conflicting work; it does not replace independent patch inspection, analysis, or each reviewer's own verdict.
696
+ Ralph starts from the raw task, refines it into a research question, runs codebase research, delegates implementation from the research artifact, and sends the patch to independent model-family reviewers. It repeats research, orchestration, and review until reviewers approve or `max_loops` is exhausted.
545
697
 
546
- Each Ralph review artifact and `review-round-latest.json` includes a `convergence_decision` summary with `parsed`, `approved`, `stopReviewLoop`, `nextAction`, `finalActionRemaining`, and `diagnostics`. This distinguishes malformed or missing structured reviewer output from a parsed reviewer rejection or blocking finding by reporting it as a parse failure.
698
+ Ralph uses the same canonical reviewer evidence and convergence contracts as Goal. Its reviewer prompt receives artifacts first and the review objective last, requires independently derived probes before implementation-authored evidence, and preserves unresolved findings when the bounded loop ends. Forked continuation prompts send only changed state and artifact paths instead of repeating the full established contract.
547
699
 
548
- When `create_pr=true`, reviewers are told that PR/MR/review creation is a post-approval final action: if implementation and validation requirements are proven and only PR creation remains, the implementation can approve with `finalActionRemaining: true` and `nextAction: "pull-request"` instead of consuming another orchestration iteration. When both reviewers converge, the latest round records `approved: true`, `stopReviewLoop: true`, and `nextAction: "pull-request"` when `create_pr=true` (otherwise `"finish"`), and the implementation loop stops before the final handoff stage.
700
+ | Input | Type | Required | Default | Description |
701
+ |---|---|---|---|---|
702
+ | `prompt` | text | yes | — | Task, issue, or spec to research, implement, and review. Keep PR/MR creation out of this text. |
703
+ | `acceptance_criteria` | text | no | prompt | Immutable original contract, especially for follow-up runs. |
704
+ | `max_loops` | number | no | `10` | Maximum research/orchestrate/review iterations. |
705
+ | `base_branch` | string | no | `origin/main` | Review and optional final-action comparison base. |
706
+ | `git_worktree_dir` | string | no | `""` | Optional reusable worktree, only when explicitly requested. |
707
+ | `create_pr` | boolean | no | `false` | Authorize the post-approval PR/MR/review stage. Prompt text alone never opts in. |
549
708
 
550
- Set `git_worktree_dir` when you want Ralph's worker stages isolated in a reusable Git worktree. Relative paths resolve from the invoking repository root, existing same-repository worktree roots are reused, and missing paths are created from `base_branch`. Ralph preserves the invoking repo-relative cwd inside the worktree, so launching from `repo/packages/api` with `git_worktree_dir=../repo-wt` runs stages from `../repo-wt/packages/api`.
709
+ ```text
710
+ /workflow ralph prompt="Migrate the database layer to Drizzle" max_loops=3
711
+ /workflow ralph prompt="Implement specs/rate-limit.md and validate burst behavior" create_pr=true
712
+ ```
551
713
 
552
- Result fields:
714
+ Declared outputs include `result`, the latest research question and artifact paths, implementation notes, optional QA video and PR reports, approval, iteration count, and review artifacts.
553
715
 
554
- | Field | Meaning |
555
- |---|---|
556
- | `result` | Final implementation report from the orchestrator stage. |
557
- | `plan` | Latest transformed research question, retained for compatibility. |
558
- | `plan_path` | Backward-compatible alias for `research_path`. |
559
- | `research` | Latest research report text or artifact reference. |
560
- | `research_path` | Path to the latest generated research artifact under `research/`. |
561
- | `implementation_notes_path` | OS-temp notes file containing decisions, deviations, blockers, and validation notes. |
562
- | `qa_video_path` | Absolute path to the reviewable QA end-to-end proof video recorded with `playwright-cli` for UI-applicable changes, when one was produced. |
563
- | `pr_report` | Pull-request report emitted only when `create_pr=true` and the final `pull-request` stage runs. |
564
- | `approved` | Whether the reviewer loop approved before completion or optional final handoff. |
565
- | `iterations_completed` | Number of research/orchestrate/review loops completed. |
566
- | `review_report` | Compact reference to the latest reviewer payload artifact. |
567
- | `review_report_path` | JSON artifact path for the latest Ralph review round. |
568
-
569
- For a delegated autonomous implementation that materially benefits from a durable research-first pipeline, use `/skill:research-codebase` → `/skill:create-spec` → `/workflow ralph prompt="Implement specs/2026-03-rate-limit.md and validate the documented burst behavior"`. Ralph can start from a spec path, GitHub issue, or crisp ticket description; it uses that prompt as-is, researches the task, delegates through sub-agents, reviews, records a QA proof video for UI/full-stack changes when practical, and iterates.
570
-
571
- Use `/workflow goal` when an autonomous job instead materially benefits from a durable goal ledger, bounded worker turns, and reviewer-gated completion; give it a concrete objective and add `create_pr=true` only when you want Goal's final `pull-request` stage after approval. Task size alone does not select either workflow.
716
+ Goal and Ralph both support reusable worktree binding through `git_worktree_dir` and `base_branch`. Use `create_pr=true` only for an explicitly authorized final action after implementation approval. For follow-up runs based on reviewer findings, pass the original task text as `acceptance_criteria` to prevent contract drift.
572
717
 
573
718
  ### `open-claude-design`
574
719
 
@@ -576,86 +721,32 @@ Inputs:
576
721
 
577
722
  | Input | Type | Required | Default | Description |
578
723
  |---|---|---|---|---|
579
- | `prompt` | text | yes | — | What to design (dashboard, page, component, prototype, …). The discovery stage refines this into a confirmed brief and asks for the output type and references. |
580
- | `discover_references` | boolean | no | `true` | Discover beautiful, current reference designs (Awwwards, recent.design, Dribbble, Monet, Motionsites) and feed them to generation. Set `false` to skip the network/browser reference pass. |
724
+ | `prompt` | text | yes | — | What to design. The discovery stage refines the brief, output type, and references. |
725
+ | `discover_references` | boolean | no | `true` | Discover current design references and feed them to generation. |
581
726
  | `max_refinements` | number | no | `3` | Maximum generate/user-feedback loop iterations. |
582
727
 
583
- The output type (`prototype`, `wireframe`, `page`, `component`, `theme`, `tokens`) and any reference designs are **not** inputs the discovery stage asks for them. There is no `design_system` input; the workflow establishes or loads the project's `DESIGN.md`/`PRODUCT.md` automatically.
584
-
585
- Result fields:
586
-
587
- | Field | Meaning |
588
- |---|---|
589
- | `output_type` | Kind of design artifact produced (chosen during the discovery interview). |
590
- | `design_system` | Design system source used for generation: the project-derived design system. |
591
- | `artifact` | Latest final design summary from the approved preview artifact. |
592
- | `handoff` | Final rich HTML spec and implementation handoff summary. |
593
- | `approved_for_export` | Whether the latest user-feedback stage reported no further changes before export. |
594
- | `refinements_completed` | Number of refinement iterations completed. |
595
- | `import_context` | Reference-import context used during generation. |
596
- | `run_id` | Per-run design workflow artifact identifier. |
597
- | `artifact_dir` | Directory containing preview and spec artifacts. |
598
- | `preview_path` | Absolute path to the generated `preview.html` file. |
599
- | `preview_file_url` | `file://` URL for the generated `preview.html` file. |
600
- | `spec_path` | Absolute path to the generated `spec.html` file. |
601
- | `spec_file_url` | `file://` URL for the generated `spec.html` file. |
602
- | `playwright_cli_status` | Outcome of the initial deterministic step that ensures the `playwright-cli` skill's `playwright-cli` command is installed. |
603
-
604
- `open-claude-design` has no `result` output; it exposes only the declared fields listed above. Use the declared `artifact` and `handoff` fields for generated content.
605
-
606
- **Combined discovery/init.** The workflow's first and only front-door stage runs `/skill:impeccable shape` and `/skill:impeccable init` together. It interviews you (via the structured question tool) about what you want to build, the **output type** (`prototype`, `wireframe`, `page`, `component`, `theme`, or `tokens`), and which **references** to emulate (URLs, local file paths, screenshots, or design docs). Then, in the same `discovery` stage, impeccable init detects `PRODUCT.md`/`DESIGN.md` and creates or reconciles those files as needed.
607
-
608
- The references you name take **precedence over `DESIGN.md`/`PRODUCT.md`** during generation (the design system fills gaps the references don't cover, and `PRODUCT.md` still governs strategic register/voice). Headless runs infer a defensible brief, output type, references, and project-context assumptions rather than blocking.
609
-
610
- **Context and reference phase.** Design-system/reference research runs first, then gallery reference discovery uses those findings before the generator consumes the combined context:
728
+ The workflow establishes or loads project design context, extracts user-provided references, can browse curated galleries, writes a live `preview.html`, and keeps separate generator and feedback session lineages. It exports an HTML spec and implementation handoff after approval. Browser-backed preview and feedback use the `playwright-cli` skill when available.
611
729
 
612
- - *Design-system/reference research* three parallel passes (`ds-locator` / `ds-analyzer` / `ds-patterns`) extract the project's design-system evidence and also handle user-provided references. URL references are captured with browser/screenshot tooling where available; local files, screenshots, and design docs are parsed by the applicable `ds-*` pass. Their extracted requirements feed the generator and **take precedence over `DESIGN.md`/`PRODUCT.md`**. There are no separate `web-capture-*`, `file-parser-*`, or `design-system-builder` stages.
613
- - *Reference discovery* (gated by `discover_references=true`, the default) — after the `ds-*` passes complete, the `reference-discovery` stage receives their evidence plus the `PRODUCT.md`/`DESIGN.md` init summary.
614
- - It uses the `playwright-cli` skill to browse five curated galleries: [Awwwards](https://www.awwwards.com/websites/), [recent.design](https://recent.design/), [Dribbble recents](https://dribbble.com/shots/recent), [Monet](https://www.monet.design/c), and [Motionsites](https://motionsites.ai/).
615
- - It then **opens the strongest selected designs** and, ideally, **records a scroll-through video of each real design page so its animations are captured**. A full-page screenshot is a supplement or fallback, and the real destination URL is retained; it does not just screenshot gallery thumbnails, with web search as the fallback when the browser is unavailable.
616
- - It asks which curated reference direction you prefer. If none align, it asks you to provide a reference image, screenshot, URL, or local path for best results.
617
- - The workflow persists the curated **references brief** to `<artifact_dir>/references.md` and passes it to the generator (`reference_inspiration`) and refinement. Set `discover_references=false` to skip it.
618
-
619
- **Generate/user-feedback loop.** Refinement is intentionally simple and mirrors Ralph's implement/reviewer rhythm: `generate-1` writes the first `preview.html`, `user-feedback-1` opens that preview with `/skill:impeccable live`, and any captured `live_changes`, `user_notes`, or `annotated_snapshot` feed the next forked `generate-*` stage. Generator and feedback stages keep separate session lineages: each later `generate-*` forks from the previous generate session, `user-feedback-1` starts its own feedback chain, and each later `user-feedback-*` forks only from the previous feedback session rather than falling back to generator sessions.
620
-
621
- When a `user-feedback-*` stage captures no meaningful feedback, the loop exports immediately. The workflow deliberately runs only `exporter`, followed by `final-display`; there is no pre-export scan, forced-fix stage, or export gate. The workflow saves captured feedback as durable artifacts under `<artifact_dir>/feedback/iteration-<n>.md` / `.json` (plus a best-effort copy of the annotated snapshot, constrained to files within the project/artifact dir). If captured notes fail to thread into the next generate prompt, the run fails with an explicit error rather than silently generating without user feedback.
622
-
623
- **Browser requirement.** open-claude-design is browser-centric (the discovery/preview review and the `live` QA loop need the `playwright-cli` skill's browser). If no browser is available, the workflow exits cleanly before generation and reports the would-be artifact paths and install instructions rather than generating a design you could not review interactively. (The test harness skips this early exit so headless test runs still complete.)
624
-
625
- Run examples:
730
+ Declared outputs are `output_type`, `design_system`, `artifact`, `handoff`, `approved_for_export`, `refinements_completed`, `import_context`, `run_id`, `artifact_dir`, `preview_path`, `preview_file_url`, `spec_path`, `spec_file_url`, and `playwright_cli_status`. It has no implicit `result` output.
626
731
 
627
732
  ```text
628
733
  /workflow open-claude-design prompt="Refresh the settings page hierarchy"
629
- /workflow open-claude-design prompt="Design a billing page like Stripe's"
630
- /workflow open-claude-design prompt="Generate spacing and color tokens"
631
734
  /workflow open-claude-design prompt="Design a marketing landing page" discover_references=false
632
735
  ```
633
736
 
634
- The discovery interview asks for the output type and any reference URLs/files, so do not pass `output_type`, `reference`, or `design_system` on the command line.
635
-
636
737
  ### Launching with natural language
637
738
 
638
- You can also start a built-in workflow by describing the task in chat. Atomic picks the matching workflow and fills in inputs from your request:
639
-
640
- ```text
641
- Run a deep codebase research workflow on how the rate limiter behaves under burst traffic.
642
- ```
643
-
644
- ```text
645
- Use the goal workflow to implement specs/2026-03-rate-limit.md, run the focused rate-limit tests, finish only when burst traffic returns 429 with Retry-After, and cap it at 5 turns.
646
- ```
739
+ You can start a builtin in chat by naming its objective:
647
740
 
648
741
  ```text
649
- Use the ralph workflow to research a database-layer migration, implement it, review it, and set `create_pr=true` for final-stage PR handoff.
742
+ Fan out repository research by subsystem, save each branch as an artifact, and synthesize cited findings.
650
743
  ```
651
744
 
652
745
  ```text
653
- Run open-claude-design to refresh the settings page hierarchy as a page.
746
+ Run open-claude-design to refresh the settings page hierarchy.
654
747
  ```
655
748
 
656
- If required inputs are missing or ambiguous, Atomic asks for missing inputs or opens the inline input picker before launching.
657
-
658
- Named workflows run in the background with a run id. See [Running Workflows](#running-workflows) for launch behavior, [Workflow Commands](#workflow-commands) for the common controls, and [Monitor and Control Runs](#monitor-and-control-runs) for steering, pausing, and resuming.
749
+ If required inputs are missing or ambiguous, Atomic asks for them or opens the inline picker. Named runs execute in the background and return a run id.
659
750
 
660
751
  ## Writing a Workflow
661
752
 
@@ -740,17 +831,65 @@ To migrate an existing file from the removed `defineWorkflow(...).compile()` bui
740
831
 
741
832
  `prompt` and `task` are aliases for task text inside authored workflow primitives. Prefer `prompt` because it mirrors lower-level `stage.prompt(...)`; `task` remains useful in `ctx.chain(...)` examples.
742
833
 
743
- Author workflows to create at least one tracked stage by calling `ctx.task()`, `ctx.chain()`, `ctx.parallel()`, `ctx.stage()`, or `ctx.workflow()` in the run body so each normal run has graph nodes to inspect, attach to, interrupt, resume, and render. Guard-only workflows may call `ctx.exit(...)` before creating a stage when they intentionally stop early.
834
+ Author workflows to create at least one tracked execution node by calling `ctx.task()`, `ctx.chain()`, `ctx.parallel()`, `ctx.stage()`, `ctx.workflow()`, or `ctx.tool()` in the run body so each normal run has graph work to inspect and render. Stage nodes remain the attachable, interruptible, resumable chat units; durable tool nodes are non-chat execution. Guard-only workflows may call `ctx.exit(...)` before creating a node when they intentionally stop early.
835
+
836
+ ### Dynamic topology must remain acyclic
837
+
838
+ Atomic `workflow({ run })` definitions are imperative, dynamic TypeScript. The final graph is materialized only while `run(ctx)` executes and may depend on runtime inputs, branches, loops, files or network data, model or human output, helpers, and nested workflows. Discovery can report module import and definition-shape diagnostics: it loads the module, checks its exports, schemas, and `run` function, and rejects failures observable at that point. It does not execute every control-flow path or compile `run` into a complete graph. TypeScript and discovery cannot prove arbitrary dynamic acyclicity.
839
+
840
+ **Cyclic workflow graphs are unsupported. Workflow authors and coding agents MUST NOT create self-edges or dependency edges from the current frontier to an existing ancestor. Every materialized execution topology must remain a DAG. If a cycle cannot be removed, redesign or stop before launch.**
841
+
842
+ Before launch, sketch the expected node and dependency shape for every branch and loop. Reject any proposed edge from the current frontier to the node itself or an ancestor. Bounded loops must create distinct tracked work for each iteration, with stable per-iteration identity and call order for resume/replay; never reopen an ancestor below its downstream work.
843
+
844
+ Invalid structural cycle:
845
+
846
+ ```text
847
+ Implement → Review → Validate
848
+ ▲ │
849
+ └────── Repair ──────┘
850
+ ```
851
+
852
+ `Repair` points back to the existing `Implement` ancestor.
853
+
854
+ Valid unrolled loop:
855
+
856
+ ```text
857
+ Implement
858
+
859
+ Review 1
860
+
861
+ Validate 1
862
+
863
+ Repair 1
864
+
865
+ Review 2
866
+
867
+ Validate 2
868
+ ```
869
+
870
+ Each iteration creates new tracked nodes, so the materialized topology stays acyclic.
871
+
872
+ Retained-session activity without new dependency work is not a loop edge:
873
+
874
+ ```text
875
+ Implement ✓
876
+ activity: processing follow-up
877
+ ```
878
+
879
+ Record such follow-up as non-topological activity metadata. Do not reopen the original node as a descendant of its own downstream review or validation work.
880
+
881
+ Runtime and replayed topology checks are the authoritative cycle boundary. If code that materializes or restores topology changes, cover every new parent edge with incremental edge checks and validate reconstruction during execution, replay, and DBOS hydration. Authoring guidance cannot replace those runtime checks or make malformed durable topology safe.
744
882
 
745
883
  ### Guiding Principles
746
884
 
747
885
  - **Locally scoped stage prompts** - Describe only the current stage's objective, inputs, expected outputs, and success criteria. Avoid references to other stages unless the current stage explicitly receives and needs that information, and avoid workflow-specific or stage-specific vocabulary that is not explained inside the current prompt. See [Locally Scoped Stage Prompts](#locally-scoped-stage-prompts) for the expanded contract.
886
+ - **DAG-only dynamic topology** - Treat `run(ctx)` as imperative code that materializes graph nodes at runtime. Keep every branch, loop iteration, and nested boundary acyclic; never add a self-edge or a parent edge to an ancestor, and redesign or stop before launch if one remains.
748
887
  - **Clear vocabulary** - Use clear software engineering terminology in self-described prompts.
749
888
  - **No regex gates** - Avoid hard-coded regular expressions that gate reviews or model outputs.
750
889
  - **Schema-backed gates** - Prefer schema-backed workflow stages (`ctx.stage(..., { schema })`, `ctx.chain` items, or `ctx.parallel` items) for review/gate decisions whenever the workflow must evaluate model output; a schema-enabled item receives the structured-output tool automatically. See [Evaluation and Quality Gates](#evaluation-and-quality-gates).
751
890
  - **Stages are model stages** - Treat atomic workflow units as language model stages, not deterministic tools.
752
891
  - **Small deterministic-gate stages** - When deterministic gates are needed, create small dedicated stages that instruct a model to run a specific tool or perform a specific check. This keeps gates adaptive to the current codebase while preserving explicit workflow structure.
753
- - **Checkpoint workflow-owned side effects** - Prefer `ctx.tool(name, args, fn)` for filesystem writes, network mutations, external API actions, and other side effects orchestrated directly by the workflow definition. Atomic durably caches a completed call's serializable result, so resume returns that result without rerunning `fn`. Keep pure computation and side-effect-free transformations as ordinary TypeScript. Do not wrap agent-stage internals or every function call indiscriminately.
892
+ - **Checkpoint workflow-owned side effects** - Prefer `ctx.tool(name, args, fn)` for filesystem writes, network mutations, external API actions, and other side effects orchestrated directly by the workflow definition. Atomic durably caches a completed call's serializable result, so resume returns that result without rerunning `fn`. Keep pure computation and side-effect-free transformations as ordinary TypeScript. Do not wrap agent-stage internals or every function call indiscriminately. Do not retain `ctx.tool` for detached work after the workflow executor returns: terminal admission is closed first, and a later call rejects before its callback, retries, graph node, or checkpoint can begin.
754
893
 
755
894
  ### Context engineering guidance
756
895
 
@@ -930,12 +1069,24 @@ if (!decision.approved) {
930
1069
 
931
1070
  When the stage session is idle, `sendUserMessage()` starts the next user turn immediately and waits for that turn to finish under the normal workflow stage guard: it observes the stage concurrency limiter, workflow abort/cancellation signals, MCP scoping, readiness gates, and session metadata capture. If `sendUserMessage()` is the first live call on a `ctx.stage(...)` handle, Atomic records the stage as a normal running/completed graph node. If it is called after a prior `prompt()`/`complete()` has already completed the stage, the follow-on turn still uses internal abort/cancellation and concurrency protection while reusing the completed stage session.
932
1071
 
933
- The `content` argument mirrors the Atomic SDK and accepts either a string or text/image content blocks such as `[{ type: "text", text: "Describe this" }, { type: "image", data: "...", mimeType: "image/png" }]` when the underlying stage session supports native user-message delivery. Non-native fallback adapters only support string content and reject text/image block arrays instead of stringifying them. Idle non-native fallback delivery sends the follow-on string to the already-selected session directly, so workflow model fallback retries are not re-run for that injected turn.
1072
+ The `content` argument mirrors the Atomic SDK and accepts either a string or text/image content blocks such as `[{ type: "text", text: "Describe this" }, { type: "image", data: "...", mimeType: "image/png" }]` when the underlying stage session supports native user-message delivery. Non-native fallback adapters only support string content and reject text/image block arrays instead of stringifying them. Idle non-native fallback delivery sends the follow-on string to the already-selected session directly, so workflow model fallback retries are not re-run for that injected turn. During a controlled pause, the runner gates every `stage.sendUserMessage()` before selecting either native delivery or the `prompt()` fallback; therefore an adapter that omits optional `sendUserMessage()` is not prompted until explicit resume, and the admitted delivery runs once afterward.
934
1073
 
935
- When the stage is already streaming, the message is queued as a follow-up by default; pass `{ deliverAs: "steer" }` to steer the active turn instead, or `{ deliverAs: "followUp" }` to be explicit. `deliverAs` only affects streaming delivery and is a no-op for idle sessions. Follow-on turns preserve the stage's `mcp.allow` / `mcp.deny` scope for the injected user turn, just like the original `prompt()`. The older `stage.steer(text)` and `stage.followUp(text)` methods are still available for queueing while a turn is active, but they do not start a new idle turn.
1074
+ When the stage is already streaming, the message is queued as a follow-up by default; pass `{ deliverAs: "steer" }` to steer the active turn instead, or `{ deliverAs: "followUp" }` to be explicit. `deliverAs` only affects streaming delivery and is a no-op for idle sessions. Follow-on turns preserve the stage's `mcp.allow` / `mcp.deny` scope for the injected user turn, just like the original `prompt()`. The older `stage.steer(text)` and `stage.followUp(text)` methods are still available for queueing while a turn is active, but they do not start a new idle turn. If that stage is paused before delivery, Atomic preserves every queued item—type, optional data, duplicate entries, raw content, and order within its steering or follow-up queue—without starting a queued model turn or workflow continuation; late context-bearing traffic joins the hold, and the existing stage `resume` action releases the queue once.
936
1075
 
937
1076
  Custom `AgentSessionAdapter` implementations must make asynchronous idle-turn ownership observable through their public `subscribe()` stream: emit `{ type: "agent_start" }` when the submitted message has entered the turn, before waiting for that turn to finish, and emit `{ type: "agent_end", messages }` when that turn terminates. This applies both to native `sendUserMessage()` implementations and to the required `prompt()` fallback when `sendUserMessage` is omitted. Atomic retains the resulting logical ownership after releasing serialized message admission, so a concurrent second message is routed as steering/follow-up rather than another prompt even when the adapter publishes `isStreaming` asynchronously after `agent_start`. Correlated turn generations prevent a late end or older delivery settlement from clearing a newer owner. A subscription may replay earlier lifecycle state synchronously during registration; an untagged synchronous replay is treated as a snapshot and does not consume a later current-turn end. If an adapter can emit a delayed end for a replayed turn while a newer turn is active, it must attach the same stable string or numeric `turnId` to that replayed `agent_start` and its matching `agent_end`; Atomic then correlates the old end without disturbing current ownership. After `subscribe()` returns, adapters must emit `agent_start` only for newly started turns, never as a delayed replay of an earlier turn. Adapters that enter streaming synchronously are also detected through `isStreaming`; the bundled Atomic session additionally retains its internal handshake for compatibility. Implementations must not delay the current turn's `agent_start` until turn completion.
938
1077
 
1078
+ Native queue pause is an optional `StageSessionRuntime` optimization for custom adapters:
1079
+
1080
+ ```ts
1081
+ interface StageSessionRuntime {
1082
+ readonly queuedMessagesPaused?: boolean;
1083
+ pauseQueuedMessages?(): void;
1084
+ resumeQueuedMessages?(): boolean | Promise<boolean>;
1085
+ }
1086
+ ```
1087
+
1088
+ Existing adapters may omit all three members and continue using the runner's prior fallback pause behavior: the active call is aborted, the workflow objective remains suspended, and public deliveries admitted through the stage handle wait until explicit resume. Adapters that implement the native capability must provide both methods. `pauseQueuedMessages()` synchronously gates raw queued steer/follow-up work before `abort()` settles; `resumeQueuedMessages()` releases that hold without starting a provider turn and returns `true` only when raw held work was released. Atomic's bundled `AgentSession` implements this stronger native hold, which preserves already-queued and late native traffic verbatim.
1089
+
939
1090
  Externally produced traffic has a separate lifecycle rule. Intercom messages and async bash/subagent completion notices received while a workflow stage generation is still open are admitted through the stage AgentSession's native steering/follow-up queue. For a busy stage, admission into the generation boundary happens synchronously before the exact foreground subagent owner's probe/commit detach handshake; model-visible queue insertion waits inside that admitted delivery until the handshake is claimed or falls back after an unclaimed/vanished owner. A commit accepted within a parallel foreground group releases aggregate supervision for every active sibling while retaining their process and eventual-result ownership. Reserving admission before the asynchronous handshake prevents terminal close from overtaking an in-flight Intercom delivery, while waiting inside the reservation prevents a blocking child request from queueing behind either a single foreground tool call or a parallel aggregate still waiting on another child. The stage drains already-admitted work before publishing its terminal snapshot, including schema-backed turns that have already called `structured_output`.
940
1091
 
941
1092
  Closing the generation is atomic with admission: a notification admitted first belongs to that stage, while ordinary detached notifications arriving after close cannot reopen or mutate the completed stage and are surfaced once through the main-chat notification path instead. A blocking sibling `intercom.ask` is the deliberate exception: when the completed stage retains a valid conversation, Atomic schedules a post-mortem turn in that conversation so it can inspect the exact ask and reply without changing terminal workflow state. Failed running-stage admission and failed post-mortem admission return correlated actionable errors to the asker instead of consuming the full reply timeout.
@@ -992,6 +1143,8 @@ Control-signal probing is fail-closed. When the executor inspects an arbitrary t
992
1143
 
993
1144
  Use workflow composition when a workflow calls a reusable user-defined workflow from the project or package, or a bundled builtin workflow, and consumes its outputs as a tracked boundary stage. Import the child definition with a normal TypeScript import, then pass it directly to `ctx.workflow(workflowDefinition, options)`. `ctx.workflow(...)` does not accept registry names, path objects, or string aliases.
994
1145
 
1146
+ Compose nested workflows through these tracked boundaries; do not call a child definition's `run` function recursively. Each repeated child call must remain a distinct boundary with stable iteration identity and call order so execution, replay, and hydration preserve an acyclic parent/child topology.
1147
+
995
1148
  For workflows intended to be called by parent workflows, declare every field a parent should rely on in the child workflow's `outputs` object, including `result`. No output exists without declaration: a child exposes exactly its declared outputs, and returning an undeclared key fails the child call.
996
1149
 
997
1150
  #### Compose with a user-defined workflow
@@ -1053,107 +1206,75 @@ export default workflow({
1053
1206
 
1054
1207
  #### Compose with builtin workflows
1055
1208
 
1056
- Parent workflows can call exported builtin workflow definitions like user-defined workflows. Use the barrel export to import several builtins:
1209
+ Builtin workflow definitions work like user-defined child definitions. Import several from the barrel:
1057
1210
 
1058
1211
  ```ts
1059
- import { deepResearchCodebase, goal, openClaudeDesign, ralph } from "@bastani/workflows/builtin";
1212
+ import {
1213
+ adversarialVerification,
1214
+ classifyAndAct,
1215
+ fanOutAndSynthesize,
1216
+ generateAndFilter,
1217
+ goal,
1218
+ loopUntilDone,
1219
+ openClaudeDesign,
1220
+ ralph,
1221
+ tournament,
1222
+ } from "@bastani/workflows/builtin";
1060
1223
  ```
1061
1224
 
1062
- Or import one builtin from its individual module path:
1225
+ Or import one individual module:
1063
1226
 
1064
1227
  ```ts
1065
- import deepResearchCodebase from "@bastani/workflows/builtin/deep-research-codebase";
1066
1228
  import goal from "@bastani/workflows/builtin/goal";
1067
- import openClaudeDesign from "@bastani/workflows/builtin/open-claude-design";
1068
1229
  import ralph from "@bastani/workflows/builtin/ralph";
1069
1230
  ```
1070
1231
 
1071
- Common builtin import targets:
1072
-
1073
- | Workflow name | TypeScript export | Individual module path | Typical use inside another workflow |
1074
- |---|---|---|---|
1075
- | `deep-research-codebase` | `deepResearchCodebase` | `@bastani/workflows/builtin/deep-research-codebase` | Gather broad repo research before planning, synthesis, or implementation. |
1076
- | `goal` | `goal` | `@bastani/workflows/builtin/goal` | Run a bounded implementation/check loop with receipts and reviewer-gated completion; pass `create_pr=true` to authorize only the final PR-creation stage after approval. |
1077
- | `ralph` | `ralph` | `@bastani/workflows/builtin/ralph` | Run an autonomous job that benefits from Ralph's durable research/orchestrate/review loop; pass `create_pr=true` to authorize only the final PR-creation stage. |
1078
- | `open-claude-design` | `openClaudeDesign` | `@bastani/workflows/builtin/open-claude-design` | Generate and refine a UI/design artifact and handoff spec. |
1079
-
1080
- Example parent workflow that runs builtin deep research, then chooses either `goal` or `ralph` as the nested implementation runner:
1232
+ Example parent that maps a repository and verifies the synthesis:
1081
1233
 
1082
1234
  ```ts
1083
1235
  import { workflow } from "@bastani/workflows";
1084
1236
  import { Type } from "typebox";
1085
- import { deepResearchCodebase, goal, ralph } from "@bastani/workflows/builtin";
1237
+ import { adversarialVerification, fanOutAndSynthesize } from "@bastani/workflows/builtin";
1086
1238
 
1087
1239
  export default workflow({
1088
- name: "research-then-implement",
1089
- description: "Run deep research, then dispatch to goal or Ralph.",
1090
- inputs: {
1091
- topic: Type.String(),
1092
- runner: Type.Union([Type.Literal("goal"), Type.Literal("ralph")], {
1093
- default: "goal",
1094
- description: "Use goal for a durable ledger and reviewer gates, or Ralph for a durable research-first pipeline.",
1095
- }),
1096
- },
1240
+ name: "research-and-verify",
1241
+ description: "Map repository slices, synthesize evidence, and verify the report.",
1242
+ inputs: { topic: Type.String() },
1097
1243
  outputs: {
1098
- research_doc_path: Type.Optional(Type.String({ description: "Path to the deep-research document used for implementation." })),
1099
- runner: Type.String({ description: "Which nested runner executed: \"goal\" or \"ralph\"." }),
1100
- // Genuinely dynamic: the nested runner (goal vs ralph) is chosen at runtime and
1101
- // each exposes a different declared output shape, so a loose object is appropriate here.
1102
- // When a child's outputs are known and fixed, declare the precise shape instead.
1103
- implementation: Type.Object({}, { additionalProperties: true, description: "Declared outputs from the nested implementation workflow." }),
1244
+ report_path: Type.String(),
1245
+ approved: Type.Boolean(),
1104
1246
  },
1105
1247
  run: async (ctx) => {
1106
- const topic = String(ctx.inputs.topic);
1107
- const research = await ctx.workflow(deepResearchCodebase, {
1108
- inputs: { prompt: topic, max_concurrency: 4 },
1109
- stageName: "deep research",
1248
+ const research = await ctx.workflow(fanOutAndSynthesize, {
1249
+ inputs: {
1250
+ prompt: `Partition repository research for: ${ctx.inputs.topic}. Save cited findings per slice and synthesize conflicts.`,
1251
+ max_branches: 6,
1252
+ },
1253
+ stageName: "repository research",
1110
1254
  });
1111
1255
  if (research.exited === true) {
1112
- return ctx.exit({ status: research.status, reason: research.exitReason ?? "deep research stopped early" });
1256
+ return ctx.exit({ status: research.status, reason: research.exitReason ?? "research stopped early" });
1113
1257
  }
1114
1258
 
1115
- if (String(ctx.inputs.runner) === "ralph") {
1116
- const implementation = await ctx.workflow(ralph, {
1117
- inputs: {
1118
- prompt: `Use the research document at ${String(research.outputs.research_doc_path)} to plan, implement, and review: ${topic}`,
1119
- create_pr: true,
1120
- },
1121
- stageName: "ralph implementation",
1122
- });
1123
- if (implementation.exited === true) {
1124
- return ctx.exit({ status: implementation.status, reason: implementation.exitReason ?? "ralph stopped early" });
1125
- }
1126
-
1127
- return {
1128
- research_doc_path: research.outputs.research_doc_path,
1129
- runner: "ralph",
1130
- implementation: implementation.outputs,
1131
- };
1132
- }
1133
-
1134
- const implementation = await ctx.workflow(goal, {
1135
- inputs: {
1136
- objective: `Use the research document at ${String(research.outputs.research_doc_path)} to implement and validate: ${topic}`,
1137
- max_turns: 3,
1138
- },
1139
- stageName: "goal implementation",
1259
+ const verification = await ctx.workflow(adversarialVerification, {
1260
+ inputs: { task: `Verify the cited report at ${research.outputs.synthesis_path}` },
1261
+ stageName: "verify research report",
1140
1262
  });
1141
- if (implementation.exited === true) {
1142
- return ctx.exit({ status: implementation.status, reason: implementation.exitReason ?? "goal stopped early" });
1263
+ if (verification.exited === true) {
1264
+ return ctx.exit({ status: verification.status, reason: verification.exitReason ?? "verification stopped early" });
1143
1265
  }
1144
1266
 
1145
1267
  return {
1146
- research_doc_path: research.outputs.research_doc_path,
1147
- runner: "goal",
1148
- implementation: implementation.outputs,
1268
+ report_path: research.outputs.synthesis_path,
1269
+ approved: verification.outputs.approved,
1149
1270
  };
1150
1271
  },
1151
1272
  });
1152
1273
  ```
1153
1274
 
1154
- Passing a workflow definition directly to `ctx.workflow(...)` uses the child workflow's normalized name for replay metadata and default boundary labels (`shared-research` for the user-defined example above, or builtin names such as `deep-research-codebase`, `goal`, and `ralph`).
1275
+ Passing a definition directly to `ctx.workflow(...)` uses the child definition's normalized name for replay metadata and the default boundary label.
1155
1276
 
1156
- `ctx.workflow(workflowDefinition)` starts a nested workflow behind a parent boundary stage named `workflow:<workflow-name>` by default. User-facing status and graph views flatten that child into the parent run, so composition behaves like inlining the child workflow code: child stages, HIL prompt nodes, and deeper imported workflows appear in one expanded graph. The nested run id remains available internally for routing attach/pause/interrupt/resume to the correct live stage, but it is not shown as a separate top-level `/workflow status` entry. The returned child result has:
1277
+ `ctx.workflow(workflowDefinition)` starts a nested workflow behind a parent boundary stage named `workflow:<workflow-name>` by default. User-facing status and graph views flatten a valid child graph into the parent run recursively, so composition behaves like inlining the child workflow code: child stages, HIL prompt nodes, and deeper imported workflows appear in one expanded graph. When Atomic hides a valid import boundary, every boundary parent connects to every child root, and every child terminal connects to each downstream dependent of the boundary. Every visible child node keeps a distinct virtual graph ID and its exact `{ runId, stageId }` control target, even when sibling or repeated child workflows reuse local stage IDs or names. Attach, send, pause, interrupt, resume, stage selection, and post-mortem chat therefore route to the nested run and stage that actually own the node. Implementation-owned child runs are not shown as separate top-level `/workflow status` entries. The returned child result has:
1157
1278
 
1158
1279
  | Field | Meaning |
1159
1280
  |---|---|
@@ -1187,9 +1308,9 @@ A child exposes only outputs declared in `outputs` and returned from `run` or su
1187
1308
 
1188
1309
  Missing required outputs, schema type mismatches, and non-JSON-serializable returned values fail normal child completion before the parent continues; child `ctx.exit({ outputs })` allows missing required outputs but still validates every provided key and sets `child.exited === true` so parent code must handle the partial shape.
1189
1310
 
1190
- Pass only workflow definitions to `ctx.workflow(...)`. Import reusable workflows with TypeScript `import` statements first; use `/workflow` names such as `goal` only for launching named runs, not as `ctx.workflow(...)` arguments. If a module is missing or does not export a workflow definition, workflow discovery fails when loading that module. Nested child workflows count against `maxDepth` (default `4` total workflow levels).
1311
+ Pass only workflow definitions to `ctx.workflow(...)`. Import reusable workflows with TypeScript `import` statements first; registry names are only for top-level named runs, not `ctx.workflow(...)` arguments. If a module is missing or does not export a workflow definition, workflow discovery fails when loading that module. Nested child workflows count against `maxDepth` (default `4` total workflow levels).
1191
1312
 
1192
- The graph includes both the parent boundary node and the imported child workflow's own stages while the child is loading/running, so the user can observe progress and interrupt sub-workflows before they complete. Completed boundaries still retain the child workflow name, child run id prefix, and exposed output count for replay/debugging. Skipped or failed boundaries do not retain child-edge metadata (`workflowChild` / `workflowChildRun`), and graph expansion ignores any stale non-completed boundary metadata from older persisted sessions instead of flattening an unrelated child run.
1313
+ Atomic hides an import boundary only when the referenced child run is non-empty and reciprocally identifies that parent run and boundary stage. The same rule applies recursively at deeper nesting levels. If no valid child graph can stand in for the boundary—including a failed or skipped boundary, a missing or empty child graph, stale or mismatched ownership metadata, or a recursive link that cannot produce a valid expansion—the graph keeps the boundary summary node instead of flattening an unrelated or invalid child. Running and completed boundaries with valid child graphs are flattened; completed summaries still retain the child workflow name, child run id prefix, and exposed output count for replay/debugging when fallback is required.
1193
1314
 
1194
1315
  Use `stageName` when the parent needs a more specific label, but keep it concise so the child summary remains readable in the graph.
1195
1316
 
@@ -1199,6 +1320,412 @@ The child executor writes each skipped child `workflow.stage.end` exactly once b
1199
1320
 
1200
1321
  Continuation replay treats the parent child-workflow boundary as the durable checkpoint: a previously completed child boundary replays with the original exposed outputs and without re-running the child, while a child that failed or was interrupted before completion starts again from the beginning on continuation. If `ctx.exit(...)` wins while a completed boundary is being replayed but before replay finalization, the boundary is finalized as skipped and its preloaded child metadata is omitted from store, persistence, restore, and expanded graph views.
1201
1322
 
1323
+ ## Scope-Guard Starter Pattern
1324
+
1325
+ Use a scope guard when a worker may find valid adjacent work and a later reviewer or repair stage could treat that finding as part of the current task. The guard is an independent reviewer built from existing workflow composition. It controls scope only: code reviewers and deterministic checks still decide whether the candidate is correct.
1326
+
1327
+ Do not add a `watchdog` field, stage option, or custom runtime primitive for this pattern. Choose the lightest existing shape that fits the boundary:
1328
+
1329
+ | Need | Shape |
1330
+ |---|---|
1331
+ | One check at a plan, handoff, repair, or completion boundary | A fresh `ctx.task(...)` downstream of the worker |
1332
+ | One checker session that needs several prompts or explicit timing | A fresh `ctx.stage(...)`, with all of its turns completed before downstream dependency work starts |
1333
+ | Steering while the worker generation is open | Fresh guard and forked worker items in one `ctx.parallel(...)`, using inherited same-group Intercom |
1334
+
1335
+ ### Canonical scope contract
1336
+
1337
+ Create one inspectable contract artifact before guarded work starts. Treat it as immutable for that run and include:
1338
+
1339
+ - the literal objective;
1340
+ - required scope and allowed files or systems;
1341
+ - explicit non-goals;
1342
+ - stage boundaries and expected lifecycle order; and
1343
+ - acceptance criteria and required evidence.
1344
+
1345
+ Every worker, guard, reviewer, and repair continuation reads the same path. Do not copy the contract into several prompts that can drift, and do not let a stage overwrite it. If a human changes the objective, write a new versioned contract and start a new guarded unit of work instead of silently changing the active contract.
1346
+
1347
+ Large plans, diffs, logs, reviewer reports, and decision history belong in artifacts. Pass their paths with `reads` where the primitive supports it, tell fresh stages to read the needed sections, and keep Intercom messages short. A fresh guard must not rely on a sibling transcript or hidden graph state.
1348
+
1349
+ ### Decision contract and actions
1350
+
1351
+ For each proposed material expansion, the guard records one evidence-backed classification and action:
1352
+
1353
+ | Classification | Evidence threshold | Action |
1354
+ |---|---|---|
1355
+ | `required` | The literal objective, stated review feedback, acceptance criteria, or required validation directly demands it. | Permit the smallest change that satisfies that demand. |
1356
+ | `dependent` | The selected in-scope implementation would otherwise violate a cited existing contract or proven prerequisite. | Permit only the prerequisite and record the contract that makes it necessary. |
1357
+ | `follow-up` | The finding is valid but the current objective and selected implementation do not require it. | Record it once and continue without implementing it. It does not block this run. |
1358
+ | `unclear` | Evidence cannot decide a material product, public API, security, migration, or scope choice. | Block that expansion and request a supervisor or human decision through a blocking Intercom exchange or `ctx.ui`. |
1359
+
1360
+ Use a stable key for each proposal, such as `public-error-shape` or `transport-timeout`. Keep one row per key, merge repeated evidence into that row, and cap the log (the examples use 20 entries). Do not let the guard and worker echo the same finding back and forth. The persisted decision artifact is the source for later review and repair stages; chat messages only steer the open turn.
1361
+
1362
+ A useful decision record contains `key`, `classification`, concrete `evidence`, and `action`. A guard failure or missing coordination channel never means approval.
1363
+
1364
+ ### Fallback policy
1365
+
1366
+ Pick and document one policy before the run:
1367
+
1368
+ | Policy | When Intercom or the guard is unavailable |
1369
+ |---|---|
1370
+ | `warn` | Mark live steering unavailable, forbid unreviewed expansion, and run a fresh boundary `ctx.task(...)` before the next material change. |
1371
+ | `block` | Stop before expansion and request a decision with `ctx.ui`; in headless mode, fail with the unresolved decision instead of widening scope. |
1372
+ | `off` | Skip the guard only because the workflow author or user explicitly disabled it. Preserve the original scope and do not infer approval for adjacent work. |
1373
+
1374
+ Use `block` for risky public contracts, data changes, security behavior, releases, or publication. `warn` is a practical default when a boundary review can replace live steering. Never degrade silently from `block` to `warn` or from guarded execution to `off`.
1375
+
1376
+ Intercom capability is tool-gated. A stage with `noTools: "all"`, a `tools` allowlist that omits `intercom`, or `excludedTools: ["intercom"]` cannot use live steering. Use a boundary task or the selected fallback policy for that stage.
1377
+
1378
+ ### Lifecycle, topology, and context rules
1379
+
1380
+ - Keep the graph acyclic. A boundary guard is an ordinary downstream reviewer node. Live Intercom steering is activity inside already-running parallel stages, not a new graph edge.
1381
+ - Never make a guard watch itself, recursively start another guard, reopen a terminal task, or add a dependency from the current frontier to an ancestor. Complete all turns on a retained guard before starting downstream dependency work.
1382
+ - Messages admitted before a worker generation closes drain through that stage boundary. Late messages do not reopen or mutate its terminal workflow state. Give each live branch a bounded stop rule; `ctx.parallel(...)` releases downstream work only after all started branches settle, even when one finishes first.
1383
+ - Persist decisions under stable keys. Pause/resume, model fallback, durable replay, and nested workflows then reread the artifact instead of sending duplicate interventions.
1384
+ - Omit `group` for ordinary use. The worker, guard, nested workflows, and delegated subagents inherit the top-level workflow invocation's stable Intercom group. Set an explicit group only for intentional isolation; an override separates that stage from ordinary same-group peers.
1385
+ - Use `context: "fresh"` for guards, reviewers, and judges. They should see only the contract, candidate, decision artifacts, and current files.
1386
+ - Use `context: "fork"` plus `forkFromSessionFile` for implementation, debugging, and repair roles that need continuity with an owned earlier session. `context: "fork"` alone does not name a fork source; an initial worker with no prior lineage may start fresh. A later continuation should use the earlier worker's `sessionFile` when available. Do not fork an independent guard from the worker it judges.
1387
+ - Send a forked continuation only the delta after the fork point: new evidence, the decision artifact, any human answer, and the next action. Keep the full shared contract in its canonical file.
1388
+
1389
+ Expected lifecycle state is not a defect. If the contract says `candidate → validation → approval → push/publish`, a guard at the candidate or validation boundary must not reject the patch merely because it is unpushed or unpublished. Only the later publication stage owns that action.
1390
+
1391
+ ### Runnable boundary-task example
1392
+
1393
+ Use a fresh task when one check at a material boundary is enough. This complete project workflow keeps the worker lineage coherent, saves a structured decision log, and sends ambiguity to `ctx.ui` before the continuation:
1394
+
1395
+ ```ts
1396
+ // .atomic/workflows/scope-guard-boundary.ts
1397
+ import { workflow } from "@bastani/workflows";
1398
+ import { Type, type Static } from "typebox";
1399
+
1400
+ const decisionLogSchema = Type.Object(
1401
+ {
1402
+ decisions: Type.Array(
1403
+ Type.Object(
1404
+ {
1405
+ key: Type.String(),
1406
+ classification: Type.Union([
1407
+ Type.Literal("required"),
1408
+ Type.Literal("dependent"),
1409
+ Type.Literal("follow-up"),
1410
+ Type.Literal("unclear"),
1411
+ ]),
1412
+ evidence: Type.Array(Type.String(), { minItems: 1 }),
1413
+ action: Type.String(),
1414
+ },
1415
+ { additionalProperties: false },
1416
+ ),
1417
+ { maxItems: 20 },
1418
+ ),
1419
+ },
1420
+ { additionalProperties: false },
1421
+ );
1422
+
1423
+ type DecisionLog = Static<typeof decisionLogSchema>;
1424
+
1425
+ function continueWorker(sessionFile: string | undefined) {
1426
+ return sessionFile === undefined
1427
+ ? { context: "fork" as const }
1428
+ : { context: "fork" as const, forkFromSessionFile: sessionFile };
1429
+ }
1430
+
1431
+ export default workflow({
1432
+ name: "scope-guard-boundary",
1433
+ description: "Check scope at an implementation boundary.",
1434
+ inputs: {
1435
+ scope_contract: Type.String(),
1436
+ artifact_dir: Type.String({ default: ".atomic/workflows/runs/scope-guard-boundary" }),
1437
+ },
1438
+ outputs: {
1439
+ decision_log: Type.String(),
1440
+ },
1441
+ run: async (ctx) => {
1442
+ const contract = ctx.inputs.scope_contract;
1443
+ const candidate = `${ctx.inputs.artifact_dir}/candidate.md`;
1444
+ const decisionLog = `${ctx.inputs.artifact_dir}/scope-decisions.json`;
1445
+
1446
+ const worker = await ctx.task("prepare candidate", {
1447
+ context: "fresh",
1448
+ reads: [contract],
1449
+ prompt: [
1450
+ `Read the immutable scope contract at ${contract}.`,
1451
+ "Implement only the required scope and summarize changed files and evidence.",
1452
+ "Do not implement valid adjacent findings; include them in the candidate summary.",
1453
+ ].join("\n"),
1454
+ output: candidate,
1455
+ outputMode: "file-only",
1456
+ });
1457
+
1458
+ const checked = await ctx.task("scope boundary", {
1459
+ context: "fresh",
1460
+ reads: [contract, candidate],
1461
+ schema: decisionLogSchema,
1462
+ prompt: [
1463
+ `Read ${contract} and ${candidate}. Inspect the current candidate.`,
1464
+ "Classify each material expansion as required, dependent, follow-up, or unclear.",
1465
+ "Cite concrete evidence and state the action. Return at most 20 unique keys.",
1466
+ "Follow-up work must not block. Unclear expansion requires a human decision.",
1467
+ "Judge scope only; do not approve implementation correctness.",
1468
+ ].join("\n"),
1469
+ output: decisionLog,
1470
+ outputMode: "file-only",
1471
+ });
1472
+
1473
+ if (checked.structured === undefined) throw new Error("scope guard returned no decision log");
1474
+ const decisions = checked.structured as DecisionLog;
1475
+ const unclear = decisions.decisions.filter((item) => item.classification === "unclear");
1476
+ const humanDecision = unclear.length === 0
1477
+ ? "No unclear scope decisions."
1478
+ : await ctx.ui.editor([
1479
+ "Resolve these scope decisions before the worker continues:",
1480
+ ...unclear.map((item) => `- ${item.key}: ${item.evidence.join("; ")}`),
1481
+ ].join("\n"));
1482
+
1483
+ await ctx.task("continue worker", {
1484
+ ...continueWorker(worker.sessionFile),
1485
+ reads: [contract, decisionLog],
1486
+ prompt: [
1487
+ `Read the decision log at ${decisionLog}.`,
1488
+ `Human decision: ${humanDecision}`,
1489
+ "Apply only required and dependent actions. Record follow-up items without implementing them.",
1490
+ "The original contract and output rules remain unchanged.",
1491
+ ].join("\n"),
1492
+ });
1493
+
1494
+ return { decision_log: decisionLog };
1495
+ },
1496
+ });
1497
+ ```
1498
+
1499
+ The materialized order is `prepare candidate → scope boundary → optional human prompt → continue worker`. Each step is new downstream work; no edge points back to the original worker.
1500
+
1501
+ ### Runnable retained-stage example
1502
+
1503
+ Use `ctx.stage(...)` when one independent checker needs a retained conversation. Run its tracked `prompt()` once, then use `sendUserMessage(...)` for a bounded post-prompt turn on that same session; a second tracked `prompt()` on the finalized stage is invalid.
1504
+
1505
+ ```ts
1506
+ // .atomic/workflows/scope-guard-retained.ts
1507
+ import { workflow } from "@bastani/workflows";
1508
+ import { Type } from "typebox";
1509
+
1510
+ function continueWorker(sessionFile: string | undefined) {
1511
+ return sessionFile === undefined
1512
+ ? { context: "fork" as const }
1513
+ : { context: "fork" as const, forkFromSessionFile: sessionFile };
1514
+ }
1515
+
1516
+ export default workflow({
1517
+ name: "scope-guard-retained",
1518
+ description: "Retain one independent checker for a bounded multi-turn review.",
1519
+ inputs: {
1520
+ scope_contract: Type.String(),
1521
+ artifact_dir: Type.String({ default: ".atomic/workflows/runs/scope-guard-retained" }),
1522
+ },
1523
+ outputs: {
1524
+ decision_log: Type.String(),
1525
+ },
1526
+ run: async (ctx) => {
1527
+ const contract = ctx.inputs.scope_contract;
1528
+ const candidate = `${ctx.inputs.artifact_dir}/candidate.md`;
1529
+ const decisionLog = `${ctx.inputs.artifact_dir}/scope-decisions.md`;
1530
+
1531
+ const worker = await ctx.task("prepare candidate", {
1532
+ context: "fresh",
1533
+ reads: [contract],
1534
+ prompt: `Read ${contract}, prepare the scoped candidate, and summarize evidence.`,
1535
+ output: candidate,
1536
+ outputMode: "file-only",
1537
+ });
1538
+
1539
+ const guard = ctx.stage("retained scope guard", { context: "fresh" });
1540
+ await guard.prompt([
1541
+ `Read the immutable contract at ${contract} and candidate at ${candidate}.`,
1542
+ "Classify each material proposal as required, dependent, follow-up, or unclear.",
1543
+ "Write one deduplicated row per stable key, at most 20 rows, with evidence and action.",
1544
+ "Follow-up means record only; unclear means request a human decision.",
1545
+ "Judge scope only, not implementation correctness.",
1546
+ ].join("\n"), { output: decisionLog, outputMode: "file-only" });
1547
+ await guard.sendUserMessage([
1548
+ `Recheck the complete candidate against ${contract}.`,
1549
+ `If evidence changes a classification, use the write tool to replace ${decisionLog}.`,
1550
+ "Keep the artifact complete, deduplicated, and bounded to 20 rows; do not return a delta.",
1551
+ "If no decision changes, leave the artifact unchanged and say so.",
1552
+ ].join("\n"));
1553
+
1554
+
1555
+ const humanDecision = await ctx.ui.editor(
1556
+ `Review ${decisionLog}. Resolve each unclear row, or state that none remain.`,
1557
+ );
1558
+
1559
+ await ctx.task("apply retained decision", {
1560
+ ...continueWorker(worker.sessionFile),
1561
+ reads: [contract, decisionLog],
1562
+ prompt: [
1563
+ `Read ${decisionLog}.`,
1564
+ `Human decision: ${humanDecision}`,
1565
+ "Apply required and dependent actions only. Do not implement follow-up rows.",
1566
+ ].join("\n"),
1567
+ });
1568
+
1569
+ return { decision_log: decisionLog };
1570
+ },
1571
+ });
1572
+ ```
1573
+
1574
+ The tracked prompt creates the guard node and decision artifact. `sendUserMessage(...)` starts one retained follow-on turn after that node finalizes; it does not create or reopen graph work. The follow-on updates the artifact directly only when evidence changes, and it finishes before the human prompt or worker continuation starts.
1575
+
1576
+ ### Runnable live-parallel example
1577
+
1578
+ Use a live peer only when steering during generation adds clear value. Both branches omit `group`, so Atomic places them in the workflow invocation's same Intercom group. The guard first performs a bounded Intercom status handshake and returns; later blocking `intercom.ask` calls can reopen its retained conversation for classification. After both parallel branches settle, a fresh task reads that transcript and persists the final deduplicated decision artifact. Normal late sends are not part of this handshake.
1579
+
1580
+ ```ts
1581
+ // .atomic/workflows/scope-guard-live.ts
1582
+ import { workflow } from "@bastani/workflows";
1583
+ import { Type, type Static } from "typebox";
1584
+
1585
+ const coordinationSchema = Type.Object(
1586
+ {
1587
+ status: Type.Union([
1588
+ Type.Literal("available"),
1589
+ Type.Literal("unavailable"),
1590
+ Type.Literal("off"),
1591
+ ]),
1592
+ evidence: Type.String(),
1593
+ },
1594
+ { additionalProperties: false },
1595
+ );
1596
+
1597
+ type Coordination = Static<typeof coordinationSchema>;
1598
+
1599
+ function workerContext(sessionFile: string | undefined) {
1600
+ return sessionFile === undefined
1601
+ ? { context: "fresh" as const }
1602
+ : { context: "fork" as const, forkFromSessionFile: sessionFile };
1603
+ }
1604
+
1605
+ export default workflow({
1606
+ name: "scope-guard-live",
1607
+ description: "Run a worker with a live same-group scope peer.",
1608
+ inputs: {
1609
+ scope_contract: Type.String(),
1610
+ worker_session_file: Type.Optional(Type.String({
1611
+ description: "Earlier worker session to continue; omit when no worker lineage exists.",
1612
+ })),
1613
+ fallback_policy: Type.Union([
1614
+ Type.Literal("warn"),
1615
+ Type.Literal("block"),
1616
+ Type.Literal("off"),
1617
+ ], { default: "warn" }),
1618
+ artifact_dir: Type.String({ default: ".atomic/workflows/runs/scope-guard-live" }),
1619
+ },
1620
+ outputs: {
1621
+ decision_log: Type.String(),
1622
+ review: Type.String(),
1623
+ },
1624
+ run: async (ctx) => {
1625
+ const contract = ctx.inputs.scope_contract;
1626
+ const fallbackPolicy = ctx.inputs.fallback_policy;
1627
+ const candidate = `${ctx.inputs.artifact_dir}/candidate.md`;
1628
+ const coordinationPath = `${ctx.inputs.artifact_dir}/scope-coordination.json`;
1629
+ const decisionLog = `${ctx.inputs.artifact_dir}/scope-decisions.md`;
1630
+
1631
+ const branches = await ctx.parallel(
1632
+ [
1633
+ {
1634
+ name: "worker",
1635
+ ...workerContext(ctx.inputs.worker_session_file),
1636
+ reads: [contract],
1637
+ prompt: [
1638
+ `Read the immutable scope contract at ${contract}.`,
1639
+ `The declared Intercom fallback policy is ${fallbackPolicy}.`,
1640
+ "Unless policy is off, connect to Intercom and find the scope-guard peer in this workflow group.",
1641
+ "Before material expansion, send at most 20 blocking asks with a stable key and evidence.",
1642
+ "Apply required or dependent replies only. Record follow-up findings without implementing them.",
1643
+ "For an unclear reply, wait for human input instead of widening scope.",
1644
+ "If Intercom is unavailable: warn forbids expansion, block stops before expansion, and off keeps the original scope without a guard.",
1645
+ "Return the complete candidate summary; do not send a late ready notice.",
1646
+ ].join("\n"),
1647
+ output: candidate,
1648
+ outputMode: "file-only",
1649
+ },
1650
+ {
1651
+ name: "scope guard",
1652
+ context: "fresh",
1653
+ reads: [contract],
1654
+ schema: coordinationSchema,
1655
+ prompt: [
1656
+ `Read the immutable scope contract at ${contract}.`,
1657
+ `The declared fallback policy is ${fallbackPolicy}.`,
1658
+ "If policy is off, do not connect; return status off with evidence.",
1659
+ "Otherwise call intercom status once and return available or unavailable with evidence.",
1660
+ "When a later blocking ask reopens this conversation, classify its stable key as required, dependent, follow-up, or unclear.",
1661
+ "Reply with concrete evidence and one action. Do not approve implementation correctness.",
1662
+ "Never originate another guard or send a normal late message.",
1663
+ ].join("\n"),
1664
+ output: coordinationPath,
1665
+ outputMode: "file-only",
1666
+ },
1667
+ ],
1668
+ { concurrency: 2, failFast: true },
1669
+ );
1670
+
1671
+ const guardResult = branches[1];
1672
+ if (guardResult?.structured === undefined) throw new Error("scope guard returned no coordination status");
1673
+ const coordination = guardResult.structured as Coordination;
1674
+ const guardTranscript = coordination.status === "available"
1675
+ ? guardResult.sessionFile
1676
+ : undefined;
1677
+ const transcriptReads = guardTranscript === undefined ? [] : [guardTranscript];
1678
+ const effectiveStatus = fallbackPolicy === "off"
1679
+ ? "off"
1680
+ : coordination.status === "available" && guardTranscript !== undefined
1681
+ ? "available"
1682
+ : "unavailable";
1683
+ const humanDecision = effectiveStatus === "unavailable" && fallbackPolicy === "block"
1684
+ ? await ctx.ui.editor("Intercom is unavailable. Resolve scope before any blocked expansion continues.")
1685
+ : "No fallback human decision required.";
1686
+
1687
+ if (fallbackPolicy === "off") {
1688
+ await ctx.task("record scope guard off", {
1689
+ context: "fresh",
1690
+ prompt: "Record that the scope guard was explicitly off and that no expansion was approved.",
1691
+ output: decisionLog,
1692
+ outputMode: "file-only",
1693
+ });
1694
+ } else {
1695
+ await ctx.task("persist scope decisions", {
1696
+ context: "fresh",
1697
+ reads: [contract, candidate, coordinationPath, ...transcriptReads],
1698
+ prompt: [
1699
+ `Read ${contract}, ${candidate}, ${coordinationPath}, and any supplied guard transcript.`,
1700
+ `Effective coordination status: ${effectiveStatus}. Fallback policy: ${fallbackPolicy}.`,
1701
+ `Fallback human decision: ${humanDecision}`,
1702
+ "Persist one complete decision log with at most 20 unique stable keys.",
1703
+ "Classify each expansion as required, dependent, follow-up, or unclear with evidence and action.",
1704
+ "When warn has no transcript, perform the fresh boundary scope check here.",
1705
+ "Follow-up does not block. Unclear remains blocked unless the human decision resolves it.",
1706
+ ].join("\n"),
1707
+ output: decisionLog,
1708
+ outputMode: "file-only",
1709
+ });
1710
+ }
1711
+
1712
+ const review = await ctx.task("independent correctness review", {
1713
+ context: "fresh",
1714
+ reads: [contract, candidate, decisionLog],
1715
+ prompt: [
1716
+ `Read ${contract}, ${candidate}, and ${decisionLog}.`,
1717
+ "Inspect the current files and run the required checks.",
1718
+ "Review correctness independently; do not turn follow-up scope findings into blockers.",
1719
+ ].join("\n"),
1720
+ });
1721
+
1722
+ return { decision_log: decisionLog, review: review.text };
1723
+ },
1724
+ });
1725
+ ```
1726
+
1727
+ The parallel fan-out has one shared parent frontier and downstream persistence waits for both branches. Blocking asks use the guard's retained conversation; the fresh persistence task turns the final transcript into the bounded artifact before correctness review. If Intercom is unavailable, `warn` runs that task as a boundary check, `block` requires `ctx.ui`, and `off` records that no guard approval exists.
1728
+
1202
1729
  ## The `workflow()` Definition
1203
1730
 
1204
1731
  `workflow(spec)` is the only supported authoring API. It validates the schema maps, normalizes or infers the name, and returns a frozen branded definition that discovery and `ctx.workflow(...)` accept.
@@ -1520,28 +2047,46 @@ See [Lifecycle Notices and Human Input](#lifecycle-notices-and-human-input) for
1520
2047
  ### `ctx.tool(name, args, fn, options?)`
1521
2048
 
1522
2049
  ```typescript
2050
+ type WorkflowToolOutcome<TValue extends WorkflowSerializableValue> =
2051
+ | { ok: true; value: TValue; attempts: number; cached: boolean }
2052
+ | {
2053
+ ok: false;
2054
+ error: {
2055
+ name: string;
2056
+ message: string;
2057
+ exitCode?: number;
2058
+ stdout?: string;
2059
+ stderr?: string;
2060
+ };
2061
+ attempts: number;
2062
+ cached: boolean;
2063
+ };
2064
+
1523
2065
  ctx.tool<TValue extends WorkflowSerializableValue>(
1524
2066
  name: string,
1525
2067
  args: Readonly<Record<string, WorkflowSerializableValue>>,
1526
2068
  fn: () => Promise<TValue>,
1527
- options?: {
1528
- readonly retriesAllowed?: boolean;
1529
- readonly maxAttempts?: number;
1530
- readonly intervalMs?: number;
1531
- readonly backoffRate?: number;
1532
- },
2069
+ options?: WorkflowToolThrowOptions,
1533
2070
  ): Promise<TValue>;
2071
+
2072
+ ctx.tool<TValue extends WorkflowSerializableValue>(
2073
+ name: string,
2074
+ args: Readonly<Record<string, WorkflowSerializableValue>>,
2075
+ fn: () => Promise<TValue>,
2076
+ options: WorkflowToolOptions & { failureMode: "return" },
2077
+ ): Promise<WorkflowToolOutcome<TValue>>;
1534
2078
  ```
1535
2079
 
1536
- Runs arbitrary TypeScript code and durably caches its serializable result by call order plus the content hash of `name` and `args`. A completed call replays without rerunning `fn`, so use this primitive for durable side effects.
2080
+ Runs arbitrary TypeScript code as a tracked, non-attachable durable workflow graph node and caches its serializable result by call order plus the content hash of `name` and `args`. The node is created before `fn` runs and may appear before, between, after, or without model stages. A completed call replays without rerunning `fn`, so use this primitive for workflow-owned durable side effects; keep pure computation as ordinary TypeScript.
1537
2081
 
1538
2082
  **Options:**
2083
+ - `failureMode` — `"throw"` keeps the default throw-on-failure behavior; `"return"` returns a typed success or failure outcome after retries.
1539
2084
  - `retriesAllowed` — retries failures when `true`; default `false`.
1540
- - `maxAttempts` — maximum attempts when retries are enabled; default `3`.
2085
+ - `maxAttempts` — positive integer maximum when retries are enabled; default `3`. Invalid enabled retry bounds throw before the callback runs.
1541
2086
  - `intervalMs` — initial retry interval; default `1000`.
1542
2087
  - `backoffRate` — retry interval multiplier; default `2`.
1543
2088
 
1544
- See [`ctx.tool` — durable cached tool execution](#ctxtool--durable-cached-tool-execution) for the full example and cancellation behavior.
2089
+ See [`ctx.tool` — durable cached tool execution](#ctxtool--durable-cached-tool-execution) for durable failure replay, process-output safety, explicit repair handoffs, and cancellation behavior.
1545
2090
 
1546
2091
  ### `ctx.exit(options?)`
1547
2092
 
@@ -1606,13 +2151,13 @@ Select a clean session or a forked context, with `forkFromSessionFile` naming an
1606
2151
  readonly group?: string | true;
1607
2152
  ```
1608
2153
 
1609
- Sets the stage session's [Intercom](/intercom) home group so orchestrated stages can be isolated into coordination groups: a stage in group G can only intercom peers in G. Provide a named string to join that group, or boolean `true` to auto-generate one shared UUID group **per `ctx.parallel(...)` set** (minted once and shared across every item in that set — never a fresh id per item), so a whole level of reviewers lands in the same isolated group. Authored workflow values accept the trimmed, case-insensitive string sentinels `"true"` and `"auto"`. Those two names are reserved for automatic grouping; use a different name when you need a literal named group. Omit `group` to inherit per the precedence chain (ultimately `"default"`).
2154
+ Sets the stage session's [Intercom](/intercom) home group. Every top-level workflow invocation receives a stable, non-`"default"` runtime group derived from its persistent run identity. Intercom-capable stages inherit that group when `group` is omitted, including stages in nested workflows. The group stays stable across model fallback, pause/resume, and durable replay, while separate top-level invocations receive different groups.
1610
2155
 
1611
- `group` is accepted on `stage`/`task` options, on `ctx.parallel(...)` options, and per parallel step a step-level `group` overrides the parallel options' `group`. The resolved value is injected per-session (race-safe across concurrently running in-process stages, stable across model fallback). Group assignment is **gated on intercom capability**: a stage with `noTools`, a `tools` allowlist that omits `intercom`, or `excludedTools` containing `intercom` is never placed into a group (so an agent is never isolated into a group it cannot use). Subagents spawned by a grouped stage inherit that stage's group by default (see [subagents.md](/subagents)), so a reviewer level and its helper subagents form one isolated group. The subagent-only `contact_supervisor` channel still reaches the supervisor across group boundaries through a broker capability bound to the child/supervisor relationship and restored across reconnects; ordinary client `send` frames never gain cross-group authority from a channel flag.
2156
+ `group` is accepted on `stage`/`task` options, on `ctx.parallel(...)` options, and per parallel step. Explicit values override the workflow invocation group; a step-level value also overrides its parallel-set value. A named string joins that group, including `group: "default"` to opt into the shared default group. Boolean `true` auto-generates one shared UUID group **per `ctx.parallel(...)` set** (minted once for every item in that set), while `true` on a non-parallel stage creates a fresh stage-only group. The trimmed, case-insensitive string sentinels `"true"` and `"auto"` have the same automatic behavior and are reserved.
1612
2157
 
1613
- The builtin `goal` and `ralph` workflows use this to isolate each reviewer level into its own group (`goal-reviewers-turn-N` / `ralph-reviewers-iter-N`): same-level reviewers coordinate with each other but cannot reach the worker, orchestrator, parent chat, or other levels, which also keeps reviewer intercom chatter out of the main/parent context window.
2158
+ The full precedence is: explicit stage/task/parallel group > workflow invocation group > `ATOMIC_INTERCOM_GROUP` (or legacy `PI_INTERCOM_GROUP`) > Intercom config > `"default"`. Group assignment is **capability-gated**: a stage with `noTools: "all"`, a `tools` allowlist that omits `intercom`, or `excludedTools` containing `intercom` receives no group. `noTools: "builtin"` still keeps extension tools such as Intercom, so those stages inherit the workflow group unless they exclude Intercom. Subagents inherit their launching stage's resolved group by default (see [subagents.md](/subagents)). The subagent-only `contact_supervisor` channel keeps its broker-authorized cross-group route; ordinary client sends remain group-bound.
1614
2159
 
1615
- **Recommended default:** unless the user requests otherwise, give each workflow invocation its own intercom group. To share one group across every stage of the invocation, mint one invocation-scoped literal name inside the workflow's `run` function (for example `const group = "myflow-" + randomUUID();` from `node:crypto`) and pass it via the `group` option on each stage, task, or parallel step; note that `group: true` is only shared per `ctx.parallel(...)` set and mints a fresh UUID per non-parallel stage, so it isolates stages from each other rather than grouping the whole run. Ungrouped sessions all collapse into the shared `"default"` group, so an ungrouped workflow's stage and subagent intercom traffic — including async subagent-result notices — can reach the parent chat and other concurrent runs. The shipped workflow prompt guidance instructs agents to isolate invocations this way by default.
2160
+ Authors do not need to generate or pass a group through ordinary stages, tasks, parallel steps, nested workflows, or delegated subagents. Use an explicit named group or `group: true` only to create an intentional subgroup, such as isolating one reviewer level from another.
1616
2161
 
1617
2162
  ### `model`
1618
2163
 
@@ -1620,7 +2165,7 @@ The builtin `goal` and `ralph` workflows use this to isolate each reviewer level
1620
2165
  readonly model?: WorkflowModelValue; // string or supported SDK model object
1621
2166
  ```
1622
2167
 
1623
- Selects the primary stage model. String values can carry reasoning and context-window suffixes described under [Reasoning levels](#reasoning-levels) and [Context windows](#context-windows).
2168
+ Selects the primary stage model. String values can carry the reasoning suffix described under [Reasoning levels](#reasoning-levels).
1624
2169
 
1625
2170
  ### `fallbackModels` / `fallbackThinkingLevels`
1626
2171
 
@@ -1645,15 +2190,6 @@ readonly thinkingLevel?: WorkflowThinkingLevel;
1645
2190
 
1646
2191
  Sets the default reasoning effort for candidates without a suffix. A suffix on the model string wins.
1647
2192
 
1648
- ### `contextWindow` / `contextWindowStrict`
1649
-
1650
- ```typescript
1651
- readonly contextWindow?: number;
1652
- readonly contextWindowStrict?: boolean;
1653
- ```
1654
-
1655
- Applies a stage-wide context-window token budget. The runtime rejects unsupported values when `contextWindowStrict` is `true`; otherwise, the model keeps its default.
1656
-
1657
2193
  ### `scopedModels`
1658
2194
 
1659
2195
  ```typescript
@@ -1719,13 +2255,17 @@ readonly outputMode?: "inline" | "file-only";
1719
2255
 
1720
2256
  Writes stage/task output to a path or disables output persistence with `false`. `outputMode` defaults to `inline`; `file-only` keeps the parent result compact by returning an artifact reference instead of full text and requires an output path.
1721
2257
 
2258
+ The runner writes the stage's **final message** to `output` after the stage ends, so that path belongs to the runner. Never point `output` at a file the same stage's prompt asks the agent to author: the agent's file is overwritten by its closing message, and downstream stages read the leftover summary instead of the work. Pick one owner per artifact — either the stage returns the content as its final message and the runner saves it, or the prompt tells the agent to write a path the stage does not declare as `output`.
2259
+
1722
2260
  ### `reads`
1723
2261
 
1724
2262
  ```typescript
1725
2263
  readonly reads?: readonly string[] | false;
1726
2264
  ```
1727
2265
 
1728
- Provides files for the stage to read before running, or disables inherited reads with `false`. Paths are supplied as readonly strings.
2266
+ Names files for the stage to read before running, or disables inherited reads with `false`. Paths are supplied as readonly strings.
2267
+
2268
+ `reads` passes **paths, not content**. It prepends a `[Read from: <paths>]` directive to the prompt and the stage reads those files itself with its own read tool, so a stage sees whatever is on disk when it runs — not a snapshot taken when the path was passed. Any stage that rewrites an artifact between producer and consumer changes what the consumer reads. This keeps large artifacts out of the prompt; state the expectation in the prompt too, for example `Read the file at ${artifactPath} before continuing.`
1729
2269
 
1730
2270
  ### `maxOutput`
1731
2271
 
@@ -1890,31 +2430,6 @@ The standalone `thinkingLevel` stage option is deprecated. It still applies as a
1890
2430
 
1891
2431
  This applies everywhere a stage accepts a model: direct `ctx.task`/`ctx.chain`/`ctx.parallel` options, `ctx.stage` options, builtin workflow stage definitions, and workflow parameters. `fallbackThinkingLevels` is an optional compatibility helper aligned by index to `fallbackModels`; it applies only to fallback entries that do not already carry a suffix. Each `WorkflowModelAttempt` reports the resolved model and the effective reasoning effort used for that attempt.
1892
2432
 
1893
- ### Context windows
1894
-
1895
- A `model`/`fallbackModels` entry may also request a context-window budget with a parenthesized size token in the model-name portion. Place the token *before or after* the optional `:reasoning` suffix to prevent a conflict with the reasoning level. This mirrors GitHub Copilot's `Claude Opus 4.8 (1M context)` model-name convention:
1896
-
1897
- ```ts
1898
- await ctx.task("review", {
1899
- task: "Review the diff",
1900
- model: "anthropic/claude-fable-5:high",
1901
- // The copilot opus fallback runs at its largest advertised (long-context) window.
1902
- // Use (long) for a size-agnostic marker, or a rounded long-tier label like (1m).
1903
- fallbackModels: ["github-copilot/claude-opus-4.8 (long):xhigh", "anthropic/claude-opus-4-8:xhigh"],
1904
- });
1905
- ```
1906
-
1907
- The token accepts the same compact sizes as the `--context-window` flag (`1m`, `1.1m`, `936k`, `400k`, or a raw token count), plus a generic `(long)` marker, and the runtime resolves it against that specific candidate model's advertised windows:
1908
-
1909
- - `(long)` — a size-agnostic long-context marker that selects the model's advertised long tier regardless of its exact size, so the same token works across models with different long tiers;
1910
- - a request at or below the model's default window keeps the default;
1911
- - a request above the default selects the long tier — an exact supported window is used as-is, otherwise the smallest supported window at or above the request is selected, rounding **up** so a rounded marker like `(1m)` or `(1.1m)` lands on the long tier even when it sits slightly above or below the marker size (e.g. `(1m)` selects claude-opus-4.8's 1M tier and gpt-5.5's 1.05M tier; `(1.1m)` matches gpt-5.5's rounded long-tier label);
1912
- - when the model exposes no larger tier (or is unavailable), the runtime drops the request and the session keeps the model's default (short) window—a non-strict, automatic fallback.
1913
-
1914
- The budget applies only to the candidate that carries the token; other primary and fallback models in the same chain are unaffected. A parenthesized token that is not a valid size (for example `(preview)`) is left attached to the model id rather than being treated as a context window. Without the token, a tiered model **pins its natural default (short) window** in a workflow stage, so a persisted interactive long-context preference does not leak into workflow runs — use the `(1m)` token or the `contextWindow` stage option to opt into long context.
1915
-
1916
- For stage-wide selection you can instead set the `contextWindow` (and `contextWindowStrict`) stage option, which maps to the SDK `createAgentSession` options of the same name.
1917
-
1918
2433
  ## StageContext
1919
2434
 
1920
2435
  `ctx.stage(name, options?)` returns direct control of a tracked stage session. The executor owns session disposal and wraps stage operations with workflow lifecycle tracking.
@@ -1955,7 +2470,7 @@ stage.sendUserMessage(
1955
2470
  ): Promise<void>;
1956
2471
  ```
1957
2472
 
1958
- Sends a normal follow-on user turn to the retained stage session. This method starts a turn immediately when the session is idle; while streaming, it queues a follow-up by default or sends steering when `deliverAs: "steer"`.
2473
+ Sends a normal follow-on user turn to the retained stage session. This method starts a turn immediately when the session is idle and not controlled-paused; while streaming, it queues a follow-up by default or sends steering when `deliverAs: "steer"`. During controlled pause it joins the raw hold and does not start a turn.
1959
2474
 
1960
2475
  Native sessions accept strings or text/image content blocks. Non-native fallback adapters accept only strings and reject block arrays; `deliverAs` affects streaming delivery only, and follow-on turns retain the stage MCP scope.
1961
2476
 
@@ -1970,7 +2485,7 @@ stage.steer(text: string): Promise<void>;
1970
2485
  stage.followUp(text: string): Promise<void>;
1971
2486
  ```
1972
2487
 
1973
- Queues text while a turn is active. These methods do not start a new idle turn; use `sendUserMessage()` to start one.
2488
+ Queues text while a turn is active. These methods do not start a new idle turn; use `sendUserMessage()` to start one when the stage is not paused. A controlled pause holds queued steering and follow-up items without delivering them, and only the existing stage resume action makes them eligible again.
1974
2489
 
1975
2490
  ### `stage.subscribe(listener)`
1976
2491
 
@@ -2215,8 +2730,8 @@ List or inspect unfamiliar workflows before running them. If required inputs are
2215
2730
 
2216
2731
  ```ts
2217
2732
  workflow({ action: "list" })
2218
- workflow({ action: "get", workflow: "deep-research-codebase" })
2219
- workflow({ action: "inputs", workflow: "deep-research-codebase" })
2733
+ workflow({ action: "get", workflow: "fan-out-and-synthesize" })
2734
+ workflow({ action: "inputs", workflow: "fan-out-and-synthesize" })
2220
2735
  workflow({ action: "models" })
2221
2736
  ```
2222
2737
 
@@ -2225,7 +2740,7 @@ The workflow tool action surface is:
2225
2740
  - discovery: `list`, `get`, `inputs`, plus `models` for the configured model catalog
2226
2741
  - execution: named `run` with validated `workflow` and `inputs`
2227
2742
  - inspection: `status`, `stages`, `stage`, `transcript`
2228
- - messaging and run control: `send`, `pause`, `interrupt`, `quit`, `resume`
2743
+ - messaging on nonterminal root runs and run control: `send`, `pause`, `interrupt`, `quit`, `resume`
2229
2744
  - rediscovery: `reload`
2230
2745
 
2231
2746
  From interactive chat, named workflow launches run in the background so the parent chat stays available. Run `/workflow connect <run>` to see agents working and chat with and steer each stage. Inspection and control calls (`status`, `stages`, `stage`, `transcript`, `send`, `pause`, `resume`, `interrupt`, `quit`) remain available while work runs.
@@ -2241,15 +2756,15 @@ Run a named workflow with inputs:
2241
2756
  ```ts
2242
2757
  workflow({
2243
2758
  action: "run",
2244
- workflow: "deep-research-codebase",
2245
- inputs: { prompt: "map workflow runtime", max_concurrency: 4 },
2759
+ workflow: "fan-out-and-synthesize",
2760
+ inputs: { prompt: "map workflow runtime by subsystem", max_concurrency: 4 },
2246
2761
  })
2247
2762
  ```
2248
2763
 
2249
2764
  Slash equivalent:
2250
2765
 
2251
2766
  ```text
2252
- /workflow deep-research-codebase prompt="map workflow runtime" max_concurrency=4
2767
+ /workflow fan-out-and-synthesize prompt="map workflow runtime by subsystem" max_concurrency=4
2253
2768
  ```
2254
2769
 
2255
2770
  <p align="center"><img src="images/workflow-command.png" alt="Running a Workflow Command" width="600" /></p>
@@ -2304,9 +2819,10 @@ Surface behavior:
2304
2819
  - **Wheel and trackpad** - While the workflow graph is active, vertical wheel/trackpad gestures pan it up and down, and horizontal gestures pan wide graphs left and right when the terminal exposes horizontal wheel events; these gestures remain scoped to the graph instead of leaking into the main chat or terminal scrollback. Attached stage chats capture mouse/trackpad wheel events by default so scrolling stays inside the active stage transcript or prompt instead of falling through to terminal/main-chat scrollback.
2305
2820
  - **Tool and node detail** - Attached stage chats match main chat's tool-detail expansion behavior while keeping expansion state local to the workflow UI context. Press Ctrl+O (the configurable `app.tools.expand` binding) to expand every visible workflow node and tool card, including single, parallel, and chain subagent progress, current tool activity, and artifact paths; press it again to collapse them. The toggle works for active, completed, and archived stage views, including at the supported 40-column terminal minimum. A mounted prompt, custom question, or other input-owning overlay keeps the key instead of changing expansion.
2306
2821
  - **Footer context** - An attached live stage chat carries the main chat's current-folder and Git-branch identity into its themed footer and mirrors live extension status lines such as the MCP server indicator. Branch changes trigger a repaint through the host's cached footer provider, and extension status changes are read from that same provider rather than recomputed by the workflow UI.
2822
+ - **Working animation lifecycle** - Ordinary attached-stage work keeps the same exact one-cell `∀` visible while following the active workflow theme's dark → accent → bright/bold → accent → dark luminance ramp every 88ms. Every agent and SDK turn resets to the dark regular phase with a fresh lifecycle-relative cadence; turn, terminal, error, replacement, and disposal cleanup stop the active timer without stale repaint. In an eligible retained terminal-stage chat, an accepted follow-up shows Working immediately while Atomic attaches the retained conversation and starts the prompt, then hands the same visible status to the agent turn without a gap. A no-turn result, prompt error, or terminal completion removes it; an accepted manual retry clears stale status from the prior prompt before showing new pre-stream activity. `NO_COLOR` retains regular/bold activity without foreground-color escapes. Reduced motion uses a static regular accent `∀` without an animation timer; factual automatic retry, fallback, compaction, cancellation, and error copy retains precedence.
2307
2823
  - **Async statusline** - If an async/background subagent is running while the fullscreen workflow graph is open, the graph statusline mirrors the async summary so the background run remains visible; hide the graph with `h`, leave it with `ctrl+x`, or reconnect later to return to the full below-editor async widget.
2308
2824
  - **Copy mode** - Press `ctrl+t` inside an attached stage chat to toggle **copy mode**: copy mode disables workflow-chat mouse reporting so normal terminal/tmux text selection can work; press `ctrl+t` again to leave copy mode and restore transcript or prompt scrolling. Archived read-only stage transcripts expose the same footer and copy-mode status, so their text can also be selected and copied; `esc` closes the transcript and `ctrl+x` returns to the graph. While copy mode is on, wheel/trackpad gestures are handled by the terminal/tmux and may scroll terminal scrollback, so leave copy mode before using the wheel again.
2309
- - **Run control** - Use `interrupt`, `pause`, and `resume` for resumable live work; `resume` on a non-paused run reopens the saved snapshot or overlay. Use `quit` to pause a live run gracefully while preserving it for `/workflow resume`.
2825
+ - **Run control** - Use `interrupt`, `pause`, and `resume` for resumable live work. Pause/interrupt holds a stage's queued steering and follow-up items in place without dequeuing them or starting continuation; `resume` releases those items once in their existing per-queue order, but queue release alone does not start a model turn. `resume` on a non-paused run reopens the saved snapshot or overlay. Use `quit` to pause a live run gracefully while preserving it for `/workflow resume`.
2310
2826
  - **Rediscovery** - Use `/workflow reload` after adding, editing, installing, or removing workflow resources or package manifest workflow entries and you want Atomic to rediscover them in-process ([Reloading workflow resources](#reloading-workflow-resources)).
2311
2827
  - **Status listing** - `/workflow status` lists all retained active and terminal top-level runs by default; implementation-owned nested child runs are flattened into their parent workflow rather than listed separately. `/workflow status --all` is retained as a compatibility alias.
2312
2828
 
@@ -2337,6 +2853,7 @@ workflow({ action: "transcript", runId: "<id-or-prefix>", stageId: "review" })
2337
2853
  workflow({ action: "transcript", runId: "<id-or-prefix>", stageId: "review", tail: 40 })
2338
2854
  workflow({ action: "transcript", runId: "<id-or-prefix>", stageId: "review", limit: 20, includeToolOutput: true })
2339
2855
 
2856
+ // send is admitted only while the authoritative root workflow is nonterminal.
2340
2857
  workflow({ action: "send", runId: "<id-or-prefix>", stageId: "review", text: "please focus on tests" })
2341
2858
  workflow({ action: "send", runId: "<id-or-prefix>", stageId: "approval", promptId: "prompt-1", response: true, delivery: "answer" })
2342
2859
  workflow({ action: "send", runId: "<id-or-prefix>", stageId: "review", message: "continue with tests", delivery: "resume" })
@@ -2366,13 +2883,15 @@ Control behavior:
2366
2883
  - `stages` lists stage summaries, including flattened stages from nested `ctx.workflow(...)` imports and `sessionFile`/`transcriptPath` when a stage has a persisted session. Use `statusFilter: "all"` to include completed, failed, skipped, and pending stages.
2367
2884
  - `stage` returns details for one stage by stage id, unique prefix, or stage name, including nested child stages shown in the expanded graph and the persisted `sessionFile` when available. Abbreviated stage IDs printed in graph/control messages use this same unique-prefix resolver; collisions return an ambiguity diagnostic rather than selecting a stage.
2368
2885
  - `transcript` is reference-first with a small preview by default: it returns metadata, transcript paths, and up to 5 recent entries. For targeted lookup, quote the exact `sessionFile`/`transcriptPath` value without changing platform separators (preserve Windows backslashes), search it with `rg` or `grep`, then read only small surrounding ranges. Text results include JSON-escaped `sessionFileJson`/`transcriptPathJson` lines for copy-safe path literals. Pass explicit `tail` or `limit` to override the 5-entry preview; `tail` overrides `limit`; `includeToolOutput` includes captured snapshot tool output in snapshot transcript results.
2369
- - `send` delivery modes are `auto`, `answer`, `prompt`, `steer`, `followUp`, and `resume`.
2370
- - Prompt answers can include `promptId` and can carry answer content in `response`, `text`, or `message`; structured UI prompts usually prefer `response`.
2371
- - For a live idle stage, `prompt`, `followUp`, and eligible `auto` delivery all start a fresh prompt immediately; an actively streaming `followUp` remains queued and `steer` remains steering, so neither starts a concurrent prompt. The result's `delivery` and message describe the action actually taken (`prompt`, `followUp`, `steer`, `answer`, or `resume`), not merely the requested mode. Explicit `resume` against a stage that is not paused is a truthful no-op, and explicit message deliveries cannot bypass a paused stage; resume it first.
2372
- - Follow-up messaging to completed or failed stages reuses the retained `sessionFile` when available so the conversation resumes from the archived stage transcript instead of starting empty. If no session metadata was retained, Atomic refuses the follow-up rather than silently resetting.
2373
- - Explicit `delivery: "resume"` or `delivery: "steer"` against a completed post-mortem stage returns a structured `noop` with guidance to use `followUp` or `prompt`; it never appends the supplied text or mutates workflow execution.
2886
+ - `send` operates only while the authoritative root workflow is nonterminal; delivery modes are `auto`, `answer`, `prompt`, `steer`, `followUp`, and `resume`.
2887
+ - A terminal root (`completed`, `failed`, `skipped`, `cancelled`, `killed`, or terminal `blocked`) rejects every programmatic send with `status: "failed"`, `code: "WORKFLOW_TERMINAL"`, `delivery: "rejected"`, the requested root run id and terminal status, and guidance to start a new workflow. Proceed inline instead only when the remaining work is small, deterministic, and low risk.
2888
+ - Atomic checks an already-terminal root before stage resolution, nested-owner routing, prompt inspection, retained-session probing or revival, handle lookup, message admission, and delivery selection. That rejection creates no agent session or handle, appends no transcript, starts no model/tool/file work, answers no input, and mutates no workflow/stage snapshot. Missing or malformed retained sessions receive the same root-terminal error without being probed.
2889
+ - Atomic checks the same shared terminal authority again at the final synchronous SDK message-admission boundary. If a live root terminates while retained-session creation is pending, the send fails with `WORKFLOW_TERMINAL`, disposes its unclaimed provisional session/handle, and admits no prompt, model request, tool/file work, transcript append, or workflow-state mutation. A user-driven attach or Intercom claim remains independent and keeps the retained handle.
2890
+ - Prompt answers on a nonterminal root can include `promptId` and can carry answer content in `response`, `text`, or `message`; structured UI prompts usually prefer `response`.
2891
+ - For a live idle, non-paused stage, `prompt`, `followUp`, and eligible `auto` delivery all start a fresh prompt immediately; an actively streaming `followUp` remains queued and `steer` remains steering, so neither starts a concurrent prompt. During controlled pause, every context-bearing delivery remains held instead. The result's `delivery` and message describe the action actually taken (`prompt`, `followUp`, `steer`, `answer`, or `resume`), not merely the requested mode. Explicit `resume` against a stage that is not paused is a truthful no-op, and explicit message deliveries cannot bypass a paused stage; resume it first.
2892
+ - While the root remains nonterminal, follow-up messaging to an eligible completed child stage can reuse its retained `sessionFile`. After the root terminates, use explicit `/workflow attach <run-id> <stage>` post-mortem chat instead; `workflow send` never admits a retained-session turn after terminal publication.
2374
2893
  - Arbitrary `ctx.ui.custom<T>` widget prompts require the interactive workflow graph and return a clear unsupported message when targeted through `send`.
2375
- - `delivery: "auto"` first answers a pending prompt, then resumes paused work, then steers a streaming stage, and finally starts a fresh prompt when the live stage is idle.
2894
+ - On a nonterminal root, `delivery: "auto"` first answers a pending prompt, then resumes paused work, then steers a streaming stage, and finally starts a fresh prompt when the live stage is idle.
2376
2895
  - `pause`, `interrupt`, and `quit` can target one top-level run or `all: true`; `stageId` cannot be combined with `all: true`. Stage-scoped `pause` and `interrupt` controls can target a visible nested child stage from the expanded graph; `quit` remains run-level. Atomic routes stage controls to the owning nested run internally.
2377
2896
  - `interrupt` is resumable: it pauses live work when pausable stages exist and keeps the run in live history/status.
2378
2897
  - `pause` is useful for pausing a live run or a single live stage without treating it as a destructive abort.
@@ -2399,9 +2918,13 @@ When several paused stages resume together, Atomic settles every acknowledgement
2399
2918
 
2400
2919
  These are distinct operations. *Resuming workflow execution* (`/workflow resume`) is for paused, interrupted, recoverably failed, or unfinished durable work; it may replay checkpoints, continue an incomplete stage, and dispatch remaining DAG work. *Opening a post-mortem chat* reopens one terminal agent stage's retained conversation for follow-up only — it never resumes, retries, rewinds, or otherwise changes workflow execution.
2401
2920
 
2402
- Any eligible terminal agent stage with a valid retained session opens as an interactive post-mortem chat regardless of how you reach it: same-process `ctx.task`/`ctx.chain`/`ctx.parallel` stages, completed-workflow inspection, generic `/workflow attach` / `/workflow connect`, restored/replayed durable snapshots after a restart, and `workflow({ action: "send" })`. Explicit `/workflow attach <root-run> <nested-stage>` targets are resolved through the expanded graph and routed to the child run that owns the stage while the overlay remains rooted on the requested graph; the resolved owner is preserved when sibling child workflows reuse the same local stage ID.
2921
+ Any eligible terminal agent stage with a valid retained session opens as an interactive post-mortem chat through the explicit user-driven TUI path: completed-workflow inspection, `/workflow attach`, or `/workflow connect` followed by stage selection, including restored/replayed durable snapshots after a restart. Explicit `/workflow attach <root-run> <nested-stage>` targets are resolved through the expanded graph and routed to the child run that owns the stage while the overlay remains rooted on the requested graph; the resolved owner is preserved when sibling child workflows reuse the same local stage ID.
2922
+
2923
+ `workflow({ action: "send" })` is not a post-mortem path. Once the root is terminal, programmatic sends fail closed before retained-session probing or nested-stage routing. Start a new workflow if tracked work remains; proceed inline only for small, deterministic, low-risk work.
2924
+
2925
+ When a nested stage is reopened after a restart or from another checkout through the explicit TUI path, its session cwd comes from the durable root workflow (resolved workflow cwd first, then original invocation cwd) while stage-control ownership remains with the actual child run. Follow-up turns are appended in place to the stage's retained session (no separate fork), so the agent may still invoke its ordinary tools and cause side effects; only the workflow DAG, run/stage status, results, timings, checkpoints, and topology are immutable. Post-mortem chat does not resume or modify workflow execution state.
2403
2926
 
2404
- When a nested stage is reopened after a restart or from another checkout, its session cwd comes from the durable root workflow (resolved workflow cwd first, then original invocation cwd) while stage-control ownership remains with the actual child run. Follow-up turns are appended in place to the stage's retained session (no separate fork), so the agent may still invoke its ordinary tools and cause side effects; only the workflow DAG, run/stage status, results, timings, checkpoints, and topology are immutable.
2927
+ Pressing Escape during a live post-mortem turn pauses that retained conversation's queued messages without changing the terminal workflow snapshot. The next ordinary submission explicitly releases the conversation queue before it starts the new turn; clearing or restoring every visible queued item does not implicitly resume it.
2405
2928
 
2406
2929
  Every host session replacement or shutdown invalidates post-mortem handles, including a session whose lazy reopen is still pending: if creation finishes after the boundary, Atomic disposes the newly created session and rejects the already-submitted prompt before it can execute. A stage stays a **read-only transcript** when it has no valid retained agent session — prompt/HIL and boundary/summary nodes, skipped nodes without a completed conversation, non-terminal handle-less stages (another process may still own the session), and missing/malformed/deleted session files.
2407
2930
 
@@ -2420,7 +2943,21 @@ Passing a stage session's file path to `--session` still opens it explicitly. Cl
2420
2943
 
2421
2944
  ## Lifecycle Notices and Human Input
2422
2945
 
2423
- Atomic emits deduplicated main-chat notices when top-level workflow runs complete, fail, end blocked, or stop at an active recoverable provider/auth/rate-limit block. A recoverable block remains resumable (`status` surfaces and headless results report it as blocked even though the stored live snapshot stays active), is retained durably as blocked for cross-session resume, appears in the resume picker, and its notice says the workflow **is blocked** rather than implying terminal completion. Each blocked occurrence is deduped by its `blockedAt` timestamp, so a resumed workflow that hits another recoverable block re-notifies the invoking chat. Nested child workflow outcomes are reflected inside the expanded parent graph instead of producing separate top-level cards. Lifecycle notices are delivered through the coding-agent's native idle-prompt admission when the parent chat is idle, or persisted directly to the transcript when the parent chat is streaming, so a cleared steer queue or aborted turn cannot silently drop the card. Delivery is acknowledged before dedupe is committed: while the invoking chat remains active, a rejected admission retains its original payload and retries with capped backoff even if the run changes state or notification configuration is reinstalled. Session replacement cancels those attempts and clears their payloads rather than waking an unrelated chat with an uninspectable old run. Awaiting-input workflow states are tracked for dedupe/restore, but they do not enqueue main-chat connect cards or wake the model; prompt state remains visible through workflow status/connect surfaces.
2946
+ Atomic emits deduplicated main-chat notices when top-level workflow runs complete, fail, end blocked, or stop at an active recoverable provider/auth/rate-limit block. A recoverable block remains resumable (`status` surfaces and headless results report it as blocked even though the stored live snapshot stays active), is retained durably as blocked for cross-session resume, appears in the resume picker, and its notice says the workflow **is blocked** rather than implying terminal completion. Each blocked occurrence is deduped by its `blockedAt` timestamp, so a resumed workflow that hits another recoverable block re-notifies the invoking chat. Nested child workflow outcomes are reflected inside the expanded parent graph instead of producing separate top-level cards.
2947
+
2948
+ Previously, the streaming `persistWhenStreaming` path directly appended the visible card. It did not enqueue a native steer/follow-up or schedule a later model step. Therefore, an earlier provider context snapshot could finish with an uncorrected running claim.
2949
+
2950
+ Streaming lifecycle delivery now deliberately splits display from reconciliation. Before send admission resolves, Atomic appends one `display: true`, `excludeFromContext: true` lifecycle card to agent state and `SessionManager`; that same durable entry atomically carries the recovery marker for its hidden turn. Atomic separately submits the same raw notice text as a `display: false` internal reconciliation through the native steer boundary. This fixes the former direct-context race: a visible entry cannot become provider input between an assistant `workflow` call and its required `status=running` result, while a notice that arrives during final text still causes a later correcting step. The lifecycle path never aborts the active chat itself.
2951
+
2952
+ | Parent state when the notice arrives | Card and prompt transition | Invariants |
2953
+ | --- | --- | --- |
2954
+ | Idle | Commits the display card, then starts one native prompt with the hidden reconciliation. | Admission already includes the durable card; only the hidden copy enters model context. |
2955
+ | Active between completed tool calls | Commits the card and queues the hidden steer for the next native provider step. | Existing completed tool ordering stays intact. |
2956
+ | Active with the workflow tool result pending | Waits for earlier event writes, commits the context-excluded card, then lets the hidden steer follow the matching result. | Provider and reopened-file order remains assistant tool call → `status=running` tool result → lifecycle reconciliation. |
2957
+ | Active final-text streaming | Commits the card without stopping the current text; the hidden steer then creates a safe continuation that can correct a stale progress claim. | The unrelated text finishes normally unless another caller aborts it, and an ordinary abort cannot clear the admitted reconciliation. |
2958
+
2959
+ The visible card preserves the lifecycle custom type, raw notice text, exact details payload (including omitted optional fields), and display behavior. Each deduplicated occurrence has exactly one visible/persisted lifecycle card; the internal reconciliation is hidden and persisted separately only after agent-core consumes it at the provider-safe boundary. If the process exits after card admission but before consumption, startup finds the unresolved marker and queues that hidden correction once; repeated startup binding skips an already queued intent, and the persisted hidden completion suppresses all later restores. Protection is registered before public card listeners run. Session replacement and shutdown fail closed while the hidden input remains queued, since persisting it before a pending tool result would break provider protocol order; host-owned invalidation work does not run on that failed teardown. A transient reconciliation write failure retries persistence without re-queueing model input or creating another card. Physical session appends restore the exact prior file length after a partial write failure, so a later card or reconciliation retry cannot inherit a malformed JSONL tail or phantom parent. Before session replacement or shutdown can discard consumed in-memory recovery state, Atomic flushes the reconciliation again; if that write still fails, disposal stops and keeps the current session recoverable. `clearQueue()` restores only protected references it actually removed, so a reference already drained into core-local in-flight state is not aliased. Stage-session delivery transfer moves protection only with transferred queued references and leaves in-flight ownership at the source. Delivery is acknowledged only after the display card append succeeds; while the invoking chat remains active, a rejected admission retains its original payload and retries with capped backoff even if the run changes state or notification configuration is reinstalled. Session replacement cancels those admission attempts and clears their payloads rather than waking an unrelated chat with an uninspectable old run. Awaiting-input workflow states are tracked for dedupe/restore, but they do not enqueue main-chat connect cards or wake the model; prompt state remains visible through workflow status/connect surfaces.
2960
+
2424
2961
  When an active recoverable block is resumed in-process, Atomic dispatches a fresh-ID continuation that replays the source's completed stages and re-runs the failed one. The durable source is left untouched (stays `blocked`/resumable) so it remains discoverable and recoverable — including a zero-checkpoint first-stage block — if the process dies before the continuation settles; the local source snapshot is killed so the same session will not re-resume it. A process-local claim prevents a concurrent same-session double-dispatch.
2425
2962
 
2426
2963
  Configure lifecycle behavior with `workflowNotifications.enabled` (default `true`) and `workflowNotifications.notifyOn` (default `["completed", "failed", "blocked", "awaiting_input"]`).
@@ -2438,7 +2975,7 @@ When a workflow needs human input, answer in the graph viewer or attached stage
2438
2975
  /workflow attach <run-id> <stage-id-or-name>
2439
2976
  ```
2440
2977
 
2441
- Agents can answer primitive and structured pending prompts programmatically with `workflow({ action: "send", delivery: "answer", ... })`; use `promptId` when it is present in the stage details, and provide answer content with `response`, `text`, or `message`. Arbitrary custom TUI widget prompts intentionally refuse this path in iteration 1 because a generic `T` cannot be reconstructed safely from a non-TUI payload.
2978
+ Agents can answer primitive and structured pending prompts programmatically with `workflow({ action: "send", delivery: "answer", ... })` only while the root workflow is nonterminal; use `promptId` when it is present in the stage details, and provide answer content with `response`, `text`, or `message`. Arbitrary custom TUI widget prompts intentionally refuse this path in iteration 1 because a generic `T` cannot be reconstructed safely from a non-TUI payload.
2442
2979
 
2443
2980
  `ctx.ui.custom<T>(factory, options?)` reuses Atomic's TUI component path: the factory receives the same real `(tui, theme, keybindings, done)` types as extension `ctx.ui.custom`, and the workflow resumes with the value passed to `done(value)`. Use `options.label` for a safe display-only graph/status label and `options.replayIdentity` when widget semantics can change without the callsite changing. Do not put secrets in labels or replay identities; only a hash of the identity is stored, and label text is not part of replay identity. Inline connected rendering is supported; `overlay: true` is rejected clearly because nested workflow graph overlays are not safely supported yet.
2444
2981
 
@@ -2472,26 +3009,38 @@ When two sessions race to resume the same paused workflow, a durable first-write
2472
3009
  ### How it works
2473
3010
 
2474
3011
  - **Only `ctx.*` blocks are checkpointed**: code outside `ctx.*` is not durable.
2475
- - **Durable side effects**: Atomic flushes `ctx.tool` and `ctx.ui` writes before exposing completed results, so resume does not repeat an already-completed effect.
2476
- - **Durable graph operations**: stage, task, chain, parallel, and child-workflow checkpoints include source-stage lineage plus owning-run/boundary metadata, timing, model, output, and retained chat-session references. Fresh-process resume and completed inspection reconstruct nested child runs and parallel DAG edges directly from DBOS.
3012
+ - **Durable side effects and graph nodes**: every `ctx.tool` invocation creates a tracked, non-chat graph node before its callback runs. Atomic flushes successful outputs and opt-in recoverable failure outcomes before exposing them, so resume does not repeat an already-settled callback. Tool nodes can appear before, between, after, or without model stages.
3013
+ - **Durable child identity before dispatch**: before a nested `ctx.workflow(...)` can run child code or a child side effect, Atomic persists and awaits a versioned boundary-start record containing its stable boundary and child run ids, root/parent ownership, source order and parents, composed replay scope, alias, workflow, lifecycle state, and a deterministic fingerprint of the definition plus exact validated inputs. Distinct-input parallel calls keep stable independent scopes even when restart reverses dispatch order; identical calls share that fingerprint and use their own ordinal. Replay validates and reuses that identity before allocating any UUID.
3014
+ - **Symmetric nested scopes**: child effects stay stored under the durable root, while every child sees only its own local checkpoint view. Each nesting layer strips exactly one scope and never suffix-matches sibling or root data, so the rule composes at any depth.
3015
+ - **Stable durable graph**: tool, stage, task, chain, parallel, and child-workflow checkpoints preserve stable source identity/order, parent DAG edges, actual status, owning-run/boundary metadata, timing, output summary, model, retained chat-session references, and exact `{ runId, stageId }` targets. Fresh-process resume and completed inspection reconstruct tool-only, nested-child, mixed, and parallel topology directly from DBOS.
2477
3016
  - **DBOS-only discovery**: `/workflow resume`, `/workflows`, completed inspection, deletion, and targeted lookup hydrate/query DBOS. Session JSONL remains only a chat transcript referenced by a current checkpoint; it is not a workflow catalog or discovery source.
2478
- - **Current format only**: Atomic encodes and decodes one current DBOS format. Prior local files and older DBOS records are not read, converted, or cleaned up. Unsupported or malformed records are ignored as foreign data.
2479
- - **Child side-effect scoping**: nested workflow effects are checkpointed under the durable root with stable child scopes.
3017
+ - **Fail-closed compatibility**: prior local and pre-current records are not converted. A completed current-format child boundary created before boundary-start or invocation-fingerprint identity is accepted only when child checkpoints reciprocally prove the same root, parent run, boundary, child, and scope. Active records without a provable invocation fingerprint, and malformed, duplicate, stale, nonreciprocal, mixed, aliased, cyclic, orphaned, or unsupported topology, are hidden or refused before cache/control/child dispatch without inventing a child link or executing repair work.
3018
+ - **Topology validation boundary**: authoring and discovery guidance cannot prove dynamic acyclicity. Runtime topology work must validate each materialized parent edge incrementally during execution and replay, and DBOS hydration must reject cyclic restored topology before exposing cache, control, or child dispatch.
2480
3019
  - **Cross-session safety**: per-process executor identity, owner/heartbeat liveness on running handles, and claim-guarded status transitions prevent double dispatch when several Atomic sessions share the database.
2481
3020
 
2482
3021
  **Privacy and retention.** DBOS persists workflow inputs, completed tool outputs, UI responses, stage outputs, and chat-session paths. Treat the configured database as sensitive. History does not automatically delete records by age or count; confirmed picker deletion removes inactive DBOS workflow state while preserving independent chat transcripts.
2483
3022
 
2484
- **Resume after editing a workflow.** Replay identity combines the workflow id with stable content hashes and call order. Editing, inserting, or reordering `ctx.*` calls can intentionally invalidate matches. Finish or delete retained runs before deploying incompatible workflow changes.
3023
+ **Resume after editing a workflow.** Replay identity combines the workflow id with stable content hashes and call order. Child calls additionally bind the child definition to the exact validated input value, with a per-identical-invocation ordinal. Editing definitions, inputs, or `ctx.*` call structure can intentionally invalidate matches. Finish or delete retained runs before deploying incompatible workflow changes. Atomic refuses a stored child boundary whose fingerprint, replay scope, alias, workflow, ownership, source order, or parentage no longer matches instead of attaching it to the changed call site.
2485
3024
 
2486
- Durable `/workflow resume` preserves completed stage metadata, active-stage elapsed time, total run elapsed time, and graph topology. While an LM stage or task is active, repeated durable checkpoints refresh its accumulated pause-adjusted duration even when its session file does not change, and refresh the run's total accumulated elapsed time alongside it. Graceful quit forces an exact stage and run timing checkpoint even inside the ordinary 30-second update bucket; normal completion also persists the final accumulated run total.
3025
+ Durable `/workflow resume` preserves completed stage metadata, active-stage elapsed time, total run elapsed time, source order and parent edges, actual lifecycle status, nested ownership, and exact control targets. A completed nested boundary, its completed child stages, `ctx.tool` effects, and answered `ctx.ui` responses are cache hits; only incomplete child or downstream parent work continues. Raw stage-chat prompt answers represented by `StageSnapshot.promptAnswerState` remain live-memory-only and are not DBOS-persisted. While an LM stage or task is active, repeated durable checkpoints refresh its accumulated pause-adjusted duration even when its session file does not change, and refresh the run's total accumulated elapsed time alongside it. Graceful quit forces an exact stage and run timing checkpoint even inside the ordinary 30-second update bucket; normal completion also persists the final accumulated run total.
2487
3026
 
2488
- Each new Atomic process that reopens unfinished work starts from the latest saved baseline, so repeated process-boundary resumes keep status, graph, and lifecycle duration cumulative without double-counting pauses. A stage paused at ten seconds resumes at ten seconds, and the main-chat dashboard reports prior-session elapsed plus current-session elapsed. Completed inspection uses that same accumulated run timing rather than DBOS record wall-clock age.
3027
+ Each new Atomic process that reopens unfinished work starts from the latest saved baseline, so repeated process-boundary resumes keep stable boundary/child ids, status, graph, and lifecycle duration cumulative without double-counting pauses. A stage paused at ten seconds resumes at ten seconds, and the main-chat dashboard reports prior-session elapsed plus current-session elapsed. Completed inspection uses that same accumulated run timing rather than DBOS record wall-clock age.
2489
3028
 
2490
- Replayed `ctx.stage`, `ctx.task`, `ctx.chain`, `ctx.parallel`, and child-workflow checkpoints keep their original summaries, timing, session/model metadata, nested owning-run boundaries, and parallel fanout parentage instead of appearing as freshly flattened replay nodes. If a project-local workflow created and reloaded during a chat is absent from a fresh process's registry, resume rediscovers it from the persisted original invocation directory.
3029
+ Repeated, sibling, sequential, parallel, and multi-level child calls keep independent composed scopes and stable boundary order. The expanded graph routes attach, send, pause, interrupt, and resume through each stage's ordinary owning `{ runId, stageId}`. Exact expanded ids resolve first; local ids, prefixes, and names resolve only when unique, so collisions never select the first match silently.
2491
3030
 
2492
3031
  ### `ctx.tool` — durable cached tool execution
2493
3032
 
2494
- The `ctx.tool(name, args, fn, options?)` primitive runs arbitrary TypeScript code and caches the result durably. On resume, if that ordinal tool call already completed (matched by call order plus content hash of `name` + `args`), the runtime returns the cached result without re-executing the function ensuring completed side effects are not repeated while still allowing two intentional same-name/same-args calls in one workflow.
3033
+ The `ctx.tool(name, args, fn, options?)` primitive runs arbitrary TypeScript code as a first-class durable graph node and caches the result durably. The node is non-attachable and has no stage chat controls. It is valid before, between, after, or without model stages, so a tool-only workflow completes normally; a workflow that returns normally without any stage, child, tool, or explicit exit remains invalid. On resume, if that ordinal tool call already completed (matched by call order plus content hash of `name` + `args`), the runtime returns the cached result without re-executing the function—ensuring completed side effects are not repeated while still preserving two intentional same-name/same-args calls as distinct ordered nodes. Legacy child checkpoints without topology keep that cached output authoritative even if the additive ownership-migration write is temporarily unavailable: current replay uses inferred child ownership, a later replay retries the metadata write, and fresh completed inspection falls back to root ownership with topology unavailable until a migration succeeds.
3034
+
3035
+ When the workflow body fulfills but one or more admitted tool calls failed, Atomic promotes the first observed failure to the terminal run failure, regardless of admission order, and persists that selected tool-node identity for status inspection and lifecycle output. A direct uncaught `await ctx.tool(...)` rejection keeps the original error and persists its failed-node link through session and durable restore. First-event arbitration also preserves the selected node when concurrent failures throw the same object or primitive; unrelated later stage or body errors do not inherit a caught tool's origin. Tool admission remains open while author code can catch a failure and continue. Once the body settles and failure has won before any real cancellation, Atomic closes admission, cancels remaining non-failed tool nodes, waits for observed failed nodes to finish publication, and publishes the failed root without waiting for callbacks that ignore cancellation.
3036
+
3037
+ Set `failureMode: "return"` when a failed check is expected data for a later repair stage. Atomic runs all configured retries first, then returns a `WorkflowToolOutcome<TValue>`. A successful callback returns `{ ok: true, value, attempts, cached }`. An exhausted callback failure returns `{ ok: false, error, attempts, cached }`; `error` preserves integer `exitCode` and string or byte-buffer `stdout`/`stderr` when the thrown value exposes them. The live and restored tool node stays `failed`, while the workflow body may continue and complete. On replay, Atomic returns the same stored outcome with `cached: true` and does not run the callback again.
3038
+
3039
+ Recoverable output is explicit data flow. Atomic does not add a failed tool outcome to a later stage prompt. The workflow author must place the needed fields in `prompt`, `previous`, an output, or an artifact. Each persisted error text field is best-effort secret-redacted with the workflow persistence rules and limited to 16 KiB of UTF-8; truncated fields keep the final bytes with a marker. Keep the database sensitive even with this filter.
3040
+
3041
+ Cancellation, closed tool admission, and durable-storage faults still throw. They never become ordinary `{ ok: false }` callback outcomes. Omitting `failureMode: "return"` also keeps the existing behavior: an exhausted callback error rejects `ctx.tool` and fails the workflow unless author code catches it. Atomic persists that failed node and the root's selected tool link for later inspection, but excludes the failure record from the replay cache, so a resume or rerun calls the function again. Command failures that expose `exitCode`, `stdout`, or `stderr` remain failures even when a wrapper also uses cancellation-like text or codes; only a real run cancellation that wins the terminal race produces a killed/cancelled root.
3042
+
3043
+ Tool admission stays open while the workflow body runs and while already-admitted tools drain, including immediate promise-settlement continuations. Before any completed, failed, blocked, exited, or cancelled executor outcome is published, admission closes atomically. A detached call through a retained `ctx.tool` function after that point returns a rejected native promise without starting its callback, retries, graph node, or durable checkpoint; ignoring that promise does not emit an unhandled rejection.
2495
3044
 
2496
3045
  ```ts
2497
3046
  export default workflow({
@@ -2516,6 +3065,26 @@ export default workflow({
2516
3065
  });
2517
3066
  ```
2518
3067
 
3068
+ A bounded repair loop can pass only the needed failure evidence and use distinct arguments for each real rerun:
3069
+
3070
+ ```ts
3071
+ for (let iteration = 1; iteration <= 2; iteration += 1) {
3072
+ const tests = await ctx.tool(
3073
+ "run-tests",
3074
+ { iteration },
3075
+ async () => runCommand(["bun", "test"]),
3076
+ { failureMode: "return", retriesAllowed: true, maxAttempts: 2 },
3077
+ );
3078
+
3079
+ if (tests.ok) break;
3080
+ await ctx.task("repair-tests", {
3081
+ prompt: `Fix these test failures:\n${tests.error.stderr ?? tests.error.message}`,
3082
+ });
3083
+ }
3084
+ ```
3085
+
3086
+ Changing `iteration` makes each loop pass a distinct durable call. Reusing the same call position and arguments during resume replays its stored outcome instead of running it again.
3087
+
2519
3088
  ### `/workflow resume` — cross-session resume selector
2520
3089
 
2521
3090
  The `/workflow resume` command mirrors `/resume` ergonomics and `/workflows` is its alias. With no id, it builds one newest-first picker from eligible live runs and current DBOS resumable/completed records. DBOS is the authoritative catalog; selected records are hydrated and revalidated before resume or inspection. Running workflows never appear: fresh-heartbeat rows are excluded in every session to prevent double dispatch, and stale ones surface as `crashed`.
@@ -2526,11 +3095,15 @@ Ctrl+D deletes a highlighted inactive durable or completed row after confirmatio
2526
3095
 
2527
3096
  Only current-format DBOS records are selectable. Atomic hides unsupported or malformed records without reinterpreting them.
2528
3097
 
2529
- Selecting a paused, failed, blocked, or crash-recovery target follows the existing resume path unchanged: Atomic re-dispatches the workflow with its cached inputs and the **original workflow id**, so previously completed `ctx.tool`, `ctx.ui`, stage/task/chain/parallel items, and child workflow boundaries replay from durable checkpoints rather than executing again. Selecting a completed target follows a separate open path.
3098
+ Selecting a paused, resumable failed, blocked, or crash-recovery target follows the existing resume path unchanged: Atomic re-dispatches the workflow with its cached inputs and the **original workflow id**. Every nested invocation validates and reuses its durable boundary and child identity before dispatch. Previously completed `ctx.tool`, `ctx.ui`, stage/task/chain/parallel items, and child boundaries replay from checkpoints instead of executing again; only incomplete work continues.
2530
3099
 
2531
- Atomic reconstructs completed root and nested child-run snapshots from authoritative checkpoints, remaps persisted source-stage and boundary references to reconstructed stage ids, and opens the full expanded hierarchy without calling the durable resume dispatcher or re-running workflow stages, tools, tasks, prompts, or workflow code.
3100
+ Selecting a completed target—or a checkpointed failed target marked non-resumable—follows a separate read-only open path. Atomic reconstructs root and reciprocal nested child-run snapshots from authoritative checkpoints, remaps persisted source-stage, boundary, and tool references into a stable expanded hierarchy, and never calls the resume dispatcher or runs workflow code, tools, tasks, or prompts. These graphs remain inspectable even when no retained chat transcript survives, including tool-only graphs.
2532
3101
 
2533
- Completed detail state is read-only. A retained stage chat may be reopened for follow-up without resuming workflow execution or mutating its DBOS handle. Current checkpoints always include supported topology; foreign checkpoints are excluded rather than displayed with inferred edges.
3102
+ A terminal child stage with a valid retained session may be reopened for detached post-mortem conversation through `/workflow attach` or completed graph inspection. Follow-up is routed to that real child `{runId, stageId}` and may append chat, but it cannot pause, resume, retry, mutate root or child execution state, write a terminal checkpoint, or emit a duplicate lifecycle notice. Programmatic `workflow send` rejects the terminal root before nested-owner routing or session probing. Tool nodes never offer chat attachment.
3103
+
3104
+ New tool checkpoints persist topology. A current-format tool checkpoint created before that additive topology existed still replays safely: its cached output remains authoritative and its callback is never rerun. Root-level inspection derives deterministic fallback identity/order from checkpoint identity and record order. If a topology-less cached tool replays inside a child workflow, Atomic first appends awaited topology metadata with the current child/boundary ownership, without replacing the original output checkpoint. Foreign or malformed checkpoint formats remain excluded.
3105
+
3106
+ Fresh completed inspection does not currently persist the workflow's declared root output. Live `run()` results still expose the declared output, and this output-persistence limit does not block durable tool topology or read-only graph inspection.
2534
3107
 
2535
3108
  ```text
2536
3109
  /workflow resume # Mixed picker: resumable + completed
@@ -2539,13 +3112,13 @@ Completed detail state is read-only. A retained stage chat may be reopened for f
2539
3112
  /workflows <workflow-id-or-prefix> # Alias for targeted resume/open
2540
3113
  ```
2541
3114
 
2542
- Explicit full IDs take precedence, while prefixes resolve across top-level live, resumable durable, and completed targets as one namespace. An exact loadable paused top-level live target resumes directly from in-session state without enumerating the durable completed-history catalog; this keeps explicit live resume responsive even when retained durable history is large and preserves live-over-durable precedence for duplicate IDs. Nested child runs remain excluded from this top-level target namespace even when addressed by an exact ID.
3115
+ Explicit full IDs take precedence, while prefixes resolve across top-level live, resumable durable, and completed targets as one namespace. An exact loadable paused top-level live target resumes directly from in-session state without enumerating the durable completed-history catalog; this keeps explicit live resume responsive even when retained durable history is large and preserves live-over-durable precedence for duplicate IDs. If a stale or concurrent catalog view presents the same failed root as both resumable and read-only history, the resumable durable target wins for exact and prefix routing. Nested child runs remain excluded from this top-level target namespace even when addressed by an exact ID.
2543
3116
 
2544
3117
  The non-interactive `workflow({ action: "resume", runId: "<id-or-prefix>" })` surface uses the same durable resumable-target lookup behavior for explicit targets. If the target is absent locally, Atomic loads workflow resources, queries the authoritative DBOS resumable catalog, and only then reports a missing run. This targeted hydration does not change `workflow({ action: "status" })`: an empty session-local status before explicit resume does not imply that DBOS deleted the workflow.
2545
3118
 
2546
- Prefixes and other targets continue through the combined catalog so ambiguity and completed-inspection behavior remain unchanged. Ambiguous prefixes use the existing-style ambiguity diagnostic. A completed backend row with no checkpoints or no usable retained stage conversation is hidden from the picker; an explicit target reports that it is stale or missing required durable checkpoint/session data. A completed run remains inspectable when at least one stage has a usable transcript; missing, empty, directory, context-empty, or partially malformed transcript paths are omitted from stage chat attachment.
3119
+ Prefixes and other targets continue through the combined catalog so ambiguity and read-only inspection behavior remain unchanged. Ambiguous prefixes use the existing-style diagnostic. A current completed or non-resumable failed backend row with valid graph checkpoints remains inspectable even if every retained stage conversation is unavailable. Missing, empty, directory, context-empty, or partially malformed transcript paths are stripped from chat attachment while the graph stays read-only and visible.
2547
3120
 
2548
- Validation uses the final retained transcript for a repeated stage replay key, so an obsolete superseded checkpoint path does not hide an otherwise valid completed run. Reopening inspection refreshes a changed authoritative retained-chat handle. Session-cache-only rows are likewise hidden because the backend is authoritative. Cancelled, killed, non-resumable failed, and other terminal non-success states are never added. Normal `/resume`, `atomic -r`, and `--continue` behavior for internal workflow stage sessions is unchanged.
3121
+ Validation uses the final retained transcript for a repeated stage replay key, so an obsolete superseded checkpoint path does not hide an otherwise valid read-only graph. Reopening inspection refreshes a changed authoritative retained-chat handle. Session-cache-only rows are hidden because the backend is authoritative. Checkpointed non-resumable failed roots appear only in read-only history; cancelled, killed, blocked non-resumable, failed roots without saved progress, and other terminal non-success states are never added. Normal `/resume`, `atomic -r`, and `--continue` behavior for internal workflow stage sessions is unchanged.
2549
3122
 
2550
3123
  ### Cancellation, failure, and retry semantics
2551
3124
 
@@ -2553,9 +3126,10 @@ Validation uses the final retained transcript for a repeated stage replay key, s
2553
3126
  | --- | --- |
2554
3127
  | **Internally cancelled workflow** | Marked `cancelled` in durable state and excluded from `/workflow resume` discovery. Start a new workflow run if you intentionally want to retry cancelled work. |
2555
3128
  | **Stage failure (recoverable)** | Workflow marked `failed` or `blocked` and remains resumable by default. `/workflow resume <id>` continues from the last completed checkpoint unless durable metadata explicitly sets `resumable: false`. |
2556
- | **Stage failure (non-recoverable)** | Workflow marked `failed` or `blocked` with `resumable: false`, so it is excluded from resume discovery. |
3129
+ | **Stage failure (non-recoverable)** | Workflow marked `failed` or `blocked` with `resumable: false`, so it cannot resume execution. A failed root with saved checkpoint progress may still appear in read-only history for inspection; a blocked root does not. |
2557
3130
  | **Process crash** | Workflow remains `running` in durable state. On next session start, it appears in resume discovery when it has a durable checkpoint or pending prompt. Resume re-executes from the last completed checkpoint. |
2558
- | **`ctx.tool` retry** | When `retriesAllowed: true`, the tool function is retried with exponential backoff. Cancellation is checked before each attempt and during retry backoff, so later attempts do not run after the workflow is cancelled. After exhausting retries, the error propagates and the workflow fails. |
3131
+ | **`ctx.tool` retry/default failure** | When `retriesAllowed: true`, the tool function is retried with exponential backoff. Cancellation is checked before each attempt and during retry backoff. Without `failureMode: "return"`, an exhausted callback error propagates and the workflow fails. |
3132
+ | **Recoverable `ctx.tool` failure** | With `failureMode: "return"`, exhausted callback failures are durably returned after retries. The tool node remains failed, downstream handoff is explicit, and replay returns the same outcome with `cached: true`. Cancellation and storage faults still throw. |
2559
3133
  | **`ctx.ui` pending prompt** | If a UI prompt was not answered before interruption, resume leaves off on that prompt — the user must answer it to continue. |
2560
3134
 
2561
3135
  ### Configuring DBOS/Postgres
@@ -3100,14 +3674,19 @@ This runtime migration stub exists only so old modules fail at the callsite with
3100
3674
 
3101
3675
  ```typescript
3102
3676
  import {
3103
- deepResearchCodebase,
3677
+ adversarialVerification,
3678
+ classifyAndAct,
3679
+ fanOutAndSynthesize,
3680
+ generateAndFilter,
3104
3681
  goal,
3682
+ loopUntilDone,
3105
3683
  openClaudeDesign,
3106
3684
  ralph,
3685
+ tournament,
3107
3686
  } from "@bastani/workflows/builtin";
3108
3687
  ```
3109
3688
 
3110
- Each builtin is a workflow definition. The barrel and individual module paths also export the six pattern workflows documented below. See [Compose with builtin workflows](#compose-with-builtin-workflows) for the import table and a parent workflow example.
3689
+ Each export is a workflow definition. All nine definitions are available through individual module paths. See [Compose with builtin workflows](#compose-with-builtin-workflows) for a parent workflow example.
3111
3690
 
3112
3691
 
3113
3692
  ## Fast Inference for Workflow Stages
@@ -3128,13 +3707,16 @@ A workflow is an information-flow system, not just a list of prompts. Most workf
3128
3707
 
3129
3708
  ### Locally Scoped Stage Prompts
3130
3709
 
3131
- Stage prompts should define local contracts, not describe the full workflow runtime. Write prompts as if the stage could be executed independently from a fresh session with only the listed inputs. Include:
3710
+ Stage prompts should define local contracts, not describe the full workflow runtime. Write prompts as if the stage could be executed independently from a fresh session with only the listed inputs. A useful compact shape is `Role · Goal · Success criteria · Constraints · Tools · Output · Stop rules`; omit sections that do not change behavior. Include:
3132
3711
 
3133
3712
  - the stage's current objective and what is out of scope for this stage
3134
- - the exact files, artifacts, child outputs, or user inputs it may use
3135
- - the expected output format, or the schema it must return when the workflow item is schema-enabled
3136
- - the checks, tools, or deterministic commands it should run when relevant
3137
- - the success criteria that let this stage stop
3713
+ - the exact files, artifacts, child outputs, or user inputs it may use; put long inputs before the final instruction
3714
+ - context-dependent tool routes and permission boundaries, without describing tools the stage cannot call
3715
+ - the expected output format and length, or the schema it must return when the workflow item is schema-enabled
3716
+ - the checks, tools, or deterministic commands it should run when relevant, plus evidence required for progress or completion claims
3717
+ - the success criteria and blocker conditions that let this stage stop
3718
+
3719
+ State important constraints once. Reserve absolute wording for safety, required fields, forbidden actions, gating derivations, and other true invariants; express search, iteration, and delegation choices as decision rules. Ask for conclusions, commands, observed results, and citations—not private reasoning or generic self-verification.
3138
3720
 
3139
3721
  Avoid unrelated workflow internals such as reducer algorithms, future PR stages, sibling reviewer names, loop implementation details, or project-specific nicknames unless they are explicitly part of the current stage contract. If a term such as a gate name, ledger field, or workflow nickname is necessary, define it in the prompt before using it.
3140
3722
 
@@ -3149,7 +3731,7 @@ Context mode is an execution property configured with `context`/`forkFromSession
3149
3731
  - **Forked continuation prompts send only the delta.** A forked stage already carries the role, contracts, guidance, and output format from its own earlier prompts, so repeating them uses more tokens and can make the two copies diverge. Send what changed since the fork point — new artifacts, updated state, the next action — plus a one-line pointer back ("the contracts and report format established earlier in this thread still apply unchanged") instead of re-injecting the full text.
3150
3732
  - **Keep one canonical copy of shared contracts.** When fresh and forked variants of a stage share guidance, render the full contract only in the prompt that first establishes it and reference it from continuations. If a continuation needs a contract restated (for example, after a schema change), that is a new contract version, not a repeat.
3151
3733
 
3152
- The builtin `goal` and `ralph` workflows follow this pattern: their first worker/orchestrator prompts include the full contracts, while forked continuation turns send only the per-turn state (new receipts, the latest review artifacts, the rewritten research file) with a pointer back to the established guidance.
3734
+ Long-running worker/reviewer workflows should follow this pattern: establish the complete contract once, then send forked continuation turns only the latest state and artifact paths with a pointer back to the established guidance.
3153
3735
 
3154
3736
  ### Context Fundamentals
3155
3737
 
@@ -3171,10 +3753,10 @@ Watch for these failure modes in long or multi-stage workflows:
3171
3753
 
3172
3754
  | Pattern | Symptom | Mitigation |
3173
3755
  |---------|---------|------------|
3174
- | Lost in the middle | Important constraints are ignored in long prompts | Repeat critical constraints near the end; shorten handoffs |
3756
+ | Lost in the middle | Important constraints are ignored in long prompts | Shorten the handoff; place documents first and the final query/critical contract last |
3175
3757
  | Context poisoning | Bad or obsolete information steers later stages | Validate sources, overwrite stale artifacts, cite evidence |
3176
3758
  | Distraction | Irrelevant context crowds out useful context | Pass only stage-specific files and summaries |
3177
- | Confusion | Similar instructions or duplicate facts conflict | Consolidate instructions and name artifacts clearly |
3759
+ | Confusion | Similar instructions or duplicate facts conflict | Consolidate each shared contract into one canonical copy and name artifacts clearly |
3178
3760
  | Clash | User, system, or stage instructions disagree | Resolve conflicts before launching downstream stages |
3179
3761
 
3180
3762
  Use compaction, file references, and bounded loops before context fills with transcript noise. In attached workflow stage chat, manual compaction shows `Compacting context...`, threshold compaction shows `Auto-compacting...`, and overflow recovery shows `Context overflow detected. Auto-compacting...` in the same animated status row used for normal model work. A successful compaction leaves the normal expandable `✻ Context compacted` boundary in the transcript; the boundary is reconstructed from the durable session and has a typed live fallback if the refreshed session snapshot is temporarily unavailable.
@@ -3192,14 +3774,20 @@ A compressed handoff includes:
3192
3774
  - rejected alternatives when they matter
3193
3775
  - next action expected from the downstream stage
3194
3776
 
3195
- Use `output`, `outputMode: "file-only"`, and `reads` for large research bundles, logs, or reviewer outputs. Keep summaries compact and let downstream stages read full artifacts only when needed. In the downstream stage prompt, say `Read the file at ${artifactPath} before continuing.` Do not inject full session tails, all previous stage outputs, or every prior review round into later prompts by default; pass the latest relevant artifact paths and make older history discoverable from a ledger or index file.
3777
+ Pass file references, not content. This is the strongly encouraged default for every handoff — between stages and back to the caller — and it is what keeps a multi-stage run affordable. Use `output` with `outputMode: "file-only"` and `reads` for research bundles, logs, plans, diffs, reviewer reports, and any other stage product that can grow. In the downstream stage prompt, say `Read the file at ${artifactPath} before continuing.` Do not inject full session tails, all previous stage outputs, or every prior review round into later prompts by default; pass the latest relevant artifact paths and make older history discoverable from a ledger or index file.
3778
+
3779
+ Three rules make that work in practice:
3196
3780
 
3197
- Substantial handoffs should travel through files or durable artifacts instead of hidden transcript assumptions. This keeps stage prompts small, makes review/audit possible, and lets later stages reread the authoritative material without depending on what a previous model summarized.
3781
+ 1. **One owner per artifact.** The runner writes the stage's final message to `output` after the stage ends. Do not also ask that stage's prompt to author the same path, or the agent's file is overwritten by its closing message. Either the stage returns the content and the runner saves it, or the prompt writes a path the stage does not declare as `output`.
3782
+ 2. **Do not read an artifact back just to return it.** `outputMode: "file-only"` exists so the parent receives a compact reference. Calling `readFile` on that artifact and returning its text as a workflow output cancels the saving and drops the whole report into the caller's context window. Return the reference and a `*_path` output instead.
3783
+ 3. **Return paths from the workflow.** Declared outputs are consumed by the calling session, so a workflow's `result` should be a reference plus explicit `*_path` outputs. Callers that need the body read the path; callers that only need the outcome pay nothing for it.
3784
+
3785
+ Substantial handoffs should travel through files or durable artifacts instead of hidden transcript assumptions. This keeps stage prompts small, makes review/audit possible, and lets later stages reread the authoritative material without depending on what a previous model summarized. Remember that `reads` passes paths rather than content: a stage reads the file when it runs, so the artifact must hold the real report at that moment.
3198
3786
 
3199
3787
  ```ts
3200
3788
  const researchPath = ".atomic/workflows/runs/context-demo/research.md";
3201
3789
  await ctx.task("researcher", {
3202
- task: "Map the subsystem and save the report.",
3790
+ task: "Map the subsystem and return the report as your final message; the workflow saves it.",
3203
3791
  output: researchPath,
3204
3792
  outputMode: "file-only",
3205
3793
  });
@@ -3259,11 +3847,11 @@ Build validation into the workflow instead of waiting for a final manual check.
3259
3847
  - reviewer stages: fresh-context reviewers that inspect artifacts and current files
3260
3848
  - LLM-as-judge stages: direct scoring, pairwise comparison, or rubric-based grading for subjective outputs
3261
3849
 
3262
- Prefer schema-enabled workflow items for model review and gate decisions. Atomic passes the schema directly to the final-answer tool and captures the tool arguments; it no longer adds separate structured-output parsing, object-root restrictions, or sidecar validation. Object-shaped decision schemas with explicit booleans/enums, findings arrays, confidence, evidence fields, and error reporting are usually easiest to consume, but array or primitive schemas are valid when they fit the handoff. Avoid brittle regular-expression matching against free-form prose such as “looks good”, “approved”, or “PASS”.
3850
+ Prefer schema-enabled workflow items for model review and gate decisions. Atomic passes the schema directly to the final-answer tool and captures the tool arguments; it no longer adds separate structured-output parsing, object-root restrictions, or sidecar validation. Object-shaped decision schemas with explicit booleans/enums, findings arrays, confidence, evidence fields, and error reporting are usually easiest to consume, but array or primitive schemas are valid when they fit the handoff. Avoid brittle regular-expression matching against free-form prose such as “looks good”, “approved”, or “PASS”. Define each convergence field's derivation once and consume it deterministically rather than recomputing approval from narrative text.
3263
3851
 
3264
- Use small dedicated model stages for adaptive gates when deterministic code alone cannot decide what to check. For example, a stage can read an artifact, inspect the repo, run a named tool or command, and then emit a structured decision by configuring `schema` on that workflow item. Keep that stage's prompt narrow: tell it the specific check to perform, the files/tools it may use, and the structured decision it must return.
3852
+ Use small dedicated model stages for adaptive gates when deterministic code alone cannot decide what to check. For example, a stage can read an artifact, inspect the repo, run a named tool or command, and then emit a structured decision by configuring `schema` on that workflow item. Keep that stage's prompt narrow: tell it the specific check to perform, the files/tools it may use, the evidence to report, and the structured decision it must return. Require progress and completion claims to map to current tool results; when evidence is unavailable, the stage should identify the unverified claim or blocker rather than infer success.
3265
3853
 
3266
- When using LLM judges, reduce bias by defining score anchors, asking for evidence, calibrating against examples, and keeping length/order effects in mind. Track pass rates and failures over time for reusable workflows.
3854
+ When using LLM judges, reduce bias by defining score anchors, requesting observable evidence and criteria-based justification, calibrating against examples, and keeping length/order effects in mind. Do not ask for chain-of-thought or reconstructed internal reasoning. Track pass rates and failures over time for reusable workflows.
3267
3855
 
3268
3856
  ### Tools, MCP, Memory, and Hosted Execution
3269
3857
 
@@ -3416,6 +4004,8 @@ Before implementing or shipping a non-trivial workflow, answer these questions:
3416
4004
  - **Output contract:** Which outputs should be declared in `outputs`, which stage/task/child results should `run` return for those keys, and what runtime type must each value have? If another workflow may call this workflow as a child, which non-default outputs should the parent rely on?
3417
4005
  - **Context size:** Can downstream stages succeed from the handoff alone? Should large transcripts, logs, or research bundles be summarized or saved as artifacts?
3418
4006
  - **Control flow:** Should the workflow use `ctx.chain`, `ctx.parallel`, `ctx.ui`, bounded loops, `failFast`, or `fallbackModels`?
4007
+ - **Acyclic topology:** What node and dependency shape can each branch, bounded loop, and nested workflow boundary materialize? Which stages repeat, does each iteration create distinct tracked work with stable identity and call order, and what is the current frontier before each repeat? Could any proposed parent edge target the node itself or an ancestor? Are nested children composed through `ctx.workflow(...)` boundaries rather than recursive `run` invocation? Redesign or stop before launch if any self-edge or back-edge remains.
4008
+ - **Scope control:** Could valid adjacent findings expand the patch? If so, where will a fresh scope guard read the immutable contract, how will it classify and persist bounded decisions, which `warn`/`block`/`off` fallback applies, and which worker session owns any forked continuation?
3419
4009
  - **User experience:** Are stage names readable in status and graph views? Is the final output compact? Are important artifacts saved with stable paths?
3420
4010
  - **Validation:** What success criteria, review gates, deterministic checks, or evaluator stages prove the workflow did the right thing? Are model gates schema-backed instead of regex/prose-matched, and do adaptive gates run as focused model stages with explicit tool/check instructions?
3421
4011
  - **Final actions:** Does the workflow distinguish implementation/review convergence from post-approval final actions such as PR/MR/review creation, release tagging, deployment, or publication? Are reviewers and reducers prompted to approve and hand off when implementation and validation criteria are proven and only an explicitly authorized final action remains?
@@ -3428,16 +4018,20 @@ Good workflows are information-flow systems, not just prompt sequences. Keep sta
3428
4018
  - Do not guess input keys; inspect with `inputs` or `get` first.
3429
4019
  - Do not call `create`, `update`, or `delete` on the workflow tool; definitions are code-authored.
3430
4020
  - Do not use legacy workflow tool fields like `agent`, `stage`, or run-control `name`.
3431
- - Do not pass strings such as `"goal"` or path objects to `ctx.workflow(...)`; import the workflow definition from `@bastani/workflows/builtin` or another TypeScript module first.
4021
+ - Do not pass strings or path objects to `ctx.workflow(...)`; import the workflow definition from `@bastani/workflows/builtin` or another TypeScript module first.
4022
+ - Do not create a self-edge or a dependency edge from the current frontier to an existing ancestor. Cyclic workflow graphs are unsupported; redesign or stop before launch when a cycle cannot be removed.
4023
+ - Do not model a bounded loop by reopening an earlier node beneath its downstream work. Create distinct tracked work per iteration and keep retained-session follow-up as non-topological activity when it adds no dependency work.
4024
+ - Do not claim TypeScript or workflow discovery proves a dynamic workflow acyclic. Discovery diagnoses imports and definition shape; execution, replay, and DBOS hydration are the runtime topology boundary.
3432
4025
  - Do not rely on undeclared child outputs; returning a key that is not declared in `outputs` fails the run. Declare every child-workflow field you expose in `outputs` — including `result` — and return values matching those schemas from `run` (see [Outputs](#outputs)).
3433
4026
  - Do not expect to select or rename child outputs at the call site; parent workflows receive the child's declared output contract as `child.outputs` after checking `child.exited === false`, and a partial declared-output map when `child.exited === true`.
3434
4027
  - Do not expect named workflow runs to block the chat turn; they are background tasks.
3435
4028
  - Use `interrupt` or `pause` when the user asks to pause specific live work resumably; use `quit` for a graceful run-level process boundary.
3436
4029
  - Keep stage names readable because they appear in workflow status and UI.
3437
- - Do not ask a stage to reason from workflow or stage names that are only orchestration labels. Model stages see their local prompt/artifacts/tools; describe the action to perform and the evidence to use (`review the current code delta`, `create/update the review request`) instead of relying on labels such as `this Goal run` or `the Ralph reviewer` — see the prompt-vocabulary item in the [Design Checklist](#design-checklist).
4030
+ - Do not ask a stage to reason from workflow or stage names that are only orchestration labels. Model stages see their local prompt, artifacts, tools, and reads; describe the concrete action and evidence instead of referring to an implementation-specific nickname.
3438
4031
  - Do not write stage prompts that depend on hidden workflow-wide awareness; make each model stage locally scoped and self-described ([Locally Scoped Stage Prompts](#locally-scoped-stage-prompts)).
3439
4032
  - Do not parse model gate decisions from ad-hoc prose with regular expressions; configure `schema` on a focused workflow item and consume `result.structured`.
3440
4033
  - Do not make reviewers fail an implementation gate solely because an authorized final action has not run yet. Represent that remainder as a post-approval next action (for example `finalActionRemaining` / `nextAction`) and let the final stage perform it.
4034
+ - Do not let scope guards approve correctness or turn follow-up findings into blockers. Keep scope decisions separate from code review and deterministic validation, and do not reject expected pre-publication state assigned to a later lifecycle stage.
3441
4035
  - Return compact structured decisions and save large artifacts to files; artifact handoffs should still use files when the next stage does not need the whole payload in context.
3442
4036
 
3443
4037
  These mistakes cover workflow tool usage and authoring. For run-prompt anti-patterns, see the [Anti-patterns](#anti-patterns) table in [Workflow Best Practices](#workflow-best-practices).
@@ -3462,6 +4056,8 @@ The core workflow pattern is:
3462
4056
  Objective -> Scope -> Done criteria -> Run -> Inspect -> Steer -> Validate -> Summarize
3463
4057
  ```
3464
4058
 
4059
+ Apply this loop per independently verifiable implementation item. When a request contains several items, first use the [task-queue triage and bounded per-item dispatch rule](#task-queues-and-software-factories); do not make one item's inspect/steer/validate cycle block an unrelated item.
4060
+
3465
4061
  Use this sequence:
3466
4062
 
3467
4063
  1. Define the end state.
@@ -3636,7 +4232,9 @@ Summarize root cause, proposed fix, files involved, validation plan, and remaini
3636
4232
 
3637
4233
  For workflows larger than one tracked task, choose a small control-flow pattern before writing prompts. **Workflow authors should favor these common patterns by default:** naming the pattern up front keeps the stage graph understandable, makes validation gates explicit, and helps reviewers see why work is split across model sessions. Reach for a bespoke structure only when none of these patterns fit.
3638
4234
 
3639
- These patterns are composable and the headings below link to runnable builtins. For example, a migration workflow can nest [**fan-out-and-synthesize**](#six-composable-pattern-builtins) for call-site fixes, [**adversarial-verification**](#six-composable-pattern-builtins) per patch, and [**loop-until-done**](#six-composable-pattern-builtins) while tests still fail. Import and compose the builtin definitions instead of copying their prompts/graphs.
4235
+ The first six patterns below have runnable builtins. For example, a migration workflow can nest [**fan-out-and-synthesize**](#six-composable-pattern-builtins) for call-site fixes, [**adversarial-verification**](#six-composable-pattern-builtins) per patch, and [**loop-until-done**](#six-composable-pattern-builtins) while tests still fail. Import and compose the builtin definitions instead of copying their prompts/graphs. **Scope guard** is an authoring starter pattern rather than a builtin; compose its [boundary-task, retained-stage, or live-parallel form](#scope-guard-starter-pattern) from current primitives.
4236
+
4237
+ These graph patterns organize work **inside one root lifecycle**. They do not replace the [task-queue rule](#task-queues-and-software-factories): independent whole implementation items normally get separate top-level runs and failure boundaries, while real dependency clusters may use these patterns inside each cluster run.
3640
4238
 
3641
4239
  | Pattern | Use it when | Atomic shape |
3642
4240
  |---|---|---|
@@ -3646,6 +4244,7 @@ These patterns are composable and the headings below link to runnable builtins.
3646
4244
  | **Generate-and-filter** | You need many candidate ideas, plans, names, fixes, or hypotheses before selecting the best few. | Generator fan-out → dedupe/filter stage → optional verifier/judge → final shortlist. |
3647
4245
  | **Tournament** | The whole task is subjective or approach-sensitive, and comparative judgment is more reliable than absolute scoring. | Several agents attempt the same task → pairwise judges compare results → bracket reducer returns winners. |
3648
4246
  | **Loop until done** | The amount of work is unknown up front, such as finding all failures, mining repeated issues, or iterating until checks pass. | Bounded loop with an explicit stop condition, progress ledger, per-iteration artifacts, and a max-iteration escape hatch. |
4247
+ | **Scope guard** | A worker or repair stage may turn valid adjacent findings into unplanned work. | Immutable contract artifact → fresh boundary or live scope checker → bounded decision artifact → forked worker continuation; correctness review stays separate. |
3649
4248
 
3650
4249
  #### Pattern diagrams
3651
4250
 
@@ -3710,23 +4309,24 @@ Builtin definition and contracts: [Six composable pattern builtins](#six-composa
3710
4309
  ┌─ 3 Adversarial verification ────────────────────────────┐
3711
4310
  │ │
3712
4311
  │ │
3713
- ┌──────────┐
3714
- ├────────────────▸│verifier A│
3715
- └──────────┘
3716
- ┌──────┐ ┌──────────┐
3717
- │worker│◂────┼────────────────▸│verifier B│
3718
- └──────┘ └──────────┘
3719
- ┌──────────┐
3720
- ├────────────────▸│verifier C│
3721
- └──────────┘
4312
+ ┌──────┐ ┌──────────┐
4313
+ │worker│───╮──▸│verifier A│──╮
4314
+ └──────┘ └──────────┘
4315
+ ┌──────────┐ ┌───────┐ │
4316
+ ├──▸│verifier B│──┼──▸│reducer
4317
+ └──────────┘ └───────┘ │
4318
+ ┌──────────┐
4319
+ ╰──▸│verifier C│──╯
4320
+ └──────────┘
3722
4321
  │ │
3723
4322
  └──────────────────────────────────────────────────────────┘
3724
4323
  ```
3725
4324
 
3726
4325
  Best practices:
3727
- - Give verifiers fresh context and a concrete rubric with pass/fail evidence requirements.
3728
- - Separate implementation or generation from independent judgment to reduce a model's bias toward its own output.
3729
- - Ask verifiers to find blockers and not rewrite the candidate unless you explicitly assign them to repair it.
4326
+ - Give verifiers fresh context and a concrete rubric with pass/fail evidence requirements. For task-specific contract risk, use a grumpy/skeptical-but-fair persona that seeks realistic counterexamples, stays within the literal objective, rejects hand-waving and circular worker-authored evidence, and reports only actionable evidence-backed defects.
4327
+ - Separate adversarial probe design from authoritative execution. Require a structured verifier plan with each exact probe, inputs, command/assertion, expected success condition, and covered requirement/risk; then run selected compile, test, schema generation/validation, runtime, or artifact checks through durable workflow-owned `ctx.tool(...)` calls. Actual tool results—not model self-report—feed judgment and consolidated repair.
4328
+ - Known contracts may use direct task-specific `ctx.tool(...)` gates designed before launch; uncertain risks may use model-selected probes executed by those deterministic tools. Rerun the tools after repair until the declared pass condition or iteration limit.
4329
+ - Ask verifiers to find blockers and not rewrite the candidate unless you explicitly assign them to repair it. Keep pure transformations as ordinary TypeScript rather than wrapping every model-stage action in `ctx.tool`.
3730
4330
 
3731
4331
  ##### 4. Generate-and-filter
3732
4332
 
@@ -3789,12 +4389,14 @@ Builtin definition and contracts: [Six composable pattern builtins](#six-composa
3789
4389
  ```text
3790
4390
  ┌─ 6 Loop until done ─────────────────────────────────────┐
3791
4391
  │ │
3792
- yes, spawn another
3793
- ╭────────────────╮
3794
-
3795
- ┌─────┐ ┌─────────────┐ no ┌────┐
3796
- agent│─────▸│new findings?│──────▸│done│ │
3797
- └─────┘ └─────────────┘ └────┘
4392
+ ┌───────┐ ┌─────────────┐ no ┌────┐
4393
+ agent 1│──▸│new findings?│──────▸│done│ │
4394
+ └───────┘ └──────┬──────┘ └────┘
4395
+ yes, spawn distinct work │
4396
+
4397
+ ┌───────┐ ┌────────────┐
4398
+ │ │agent 2│──▸│next check …│ │
4399
+ │ └───────┘ └────────────┘ │
3798
4400
  │ │
3799
4401
  └──────────────────────────────────────────────────────────┘
3800
4402
  ```
@@ -3803,6 +4405,7 @@ Best practices:
3803
4405
  - Define both success and escape conditions before the loop starts.
3804
4406
  - Keep a durable ledger of attempted work, findings, failures, and validation evidence.
3805
4407
  - Bound loops by iterations, budget, or convergence criteria so exhausting a bound produces an inspectable failure instead of letting the loop continue indefinitely.
4408
+ - Materialize every iteration as distinct tracked work with stable iteration identity and call order. Never represent repetition by a self-edge, a back-edge to an ancestor, or reopening an ancestor below its downstream work.
3806
4409
 
3807
4410
  #### Choosing a common workflow pattern
3808
4411
 
@@ -3812,6 +4415,7 @@ Best practices:
3812
4415
  - Pick **generate-and-filter** when output quality depends on exploring a large option space.
3813
4416
  - Pick **tournament** when multiple whole-solution strategies should compete under one rubric.
3814
4417
  - Pick **loop until done** when the workflow should continue until evidence says it is finished, not until a preselected number of stages completes.
4418
+ - Pick **scope guard** when valid adjacent findings could expand a worker or repair stage beyond its immutable contract; choose a boundary task by default and live parallel steering only when timing requires it.
3815
4419
 
3816
4420
  Record the selected pattern in your spec or workflow README, then adapt the diagram to the stage graph. If the final design does not resemble any common pattern, explain why in the workflow's design notes.
3817
4421
 
@@ -4138,6 +4742,7 @@ These anti-patterns target run prompts; [Common Mistakes](#common-mistakes) cove
4138
4742
  | Continuing stale runs | Pause, stop, or rerun with updated context. |
4139
4743
  | Reading every log | Inspect status, then stages, then only relevant details. |
4140
4744
  | Publishing without gates | Require release validation and explicit stop conditions. |
4745
+ | Serializing independent issues from list order | Triage dependencies, then launch separate top-level item runs under a concurrency bound. |
4141
4746
 
4142
4747
  ---
4143
4748
 
@@ -4153,6 +4758,7 @@ Before starting a workflow, include:
4153
4758
  - [ ] Validation command
4154
4759
  - [ ] Reporting requirements
4155
4760
  - [ ] Stop conditions
4761
+ - [ ] Queue dependency classification, concurrency bound, and item → run/worktree/branch map (when several implementation items are requested)
4156
4762
 
4157
4763
  Before accepting a workflow result, ask:
4158
4764