返回 CodeWhale
WORKFLOW_AUTHORING.md
根目录 / docs / WORKFLOW_AUTHORING.md
1 # Workflow Authoring
2
3 > 阅读简体中文版:[zh_hans/WORKFLOW_AUTHORING.md](zh_hans/WORKFLOW_AUTHORING.md)。
4
5 > **Ordinary multi-agent work does not require this file.** In Operate, send
6 > normal messages. Small work stays direct; multiple delegated steps use a
7 > compact Workflow plan with dependencies, bounded scopes, and completion
8 > evidence. Fleet manages the same sub-agents and roles. One bounded,
9 > independent task can use a direct agent, with `followup` for continued work.
10 > Act/Agent may also use optional soft-auto launch. See
11 > [Automatic Workflows](AUTOMATIC_WORKFLOWS.md).
12
13 Workflow has one runtime boundary: authored source lowers to typed
14 Rust `WorkflowSpec`, Rust validates the IR, and the scheduler/headless worker
15 runtime executes leaves. Authoring languages do not get hidden authority to own
16 files, shell, network, providers, cancellation, or TUI state.
17
18 Compatibility launch paths on the `workflow` tool:
19
20 | Input | When to use |
21 |-------|-------------|
22 | `plan` | Structured goal / phases / children (preferred agent path) |
23 | `script` | Short inline JS the model owns |
24 | `source_path` | Checked-in `.workflow.js` / `.workflow.ts` in the workspace |
25
26 Use `agent(action="roster")` to inspect the saved Fleet models and roles before
27 assigning children. Native plan children accept `model` for a saved shortlist
28 selector, or `role`/`profile` for a saved assignment. Named Exact Fleets keep
29 their member routes fixed and reject per-step model overrides. Plan children
30 also accept `cwd`, a repository-relative working directory — required in
31 multi-repository workspaces so the child (and worktree isolation) resolves the
32 right repository, mirroring `task({cwd})`.
33
34 For a guided walkthrough from fleet task specs to Workflow authoring and
35 monitoring, see [fleet + Workflow Tutorial](FLEET_WORKFLOW_TUTORIAL.md).
36
37
38 ## Access model
39
40 The Workflow script is a **coordinator only**. It has no filesystem or shell of
41 its own. Real work happens in sub-agents the script launches.
42
43 | Layer | What it can access |
44 |-------|--------------------|
45 | Workflow script (JS VM) | Script variables, branching/loops, `task()` / `parallel()` / `pipeline()`, `phase` / `log`, `budget` / `args`. **No** direct FS, shell, network, env, imports, clock, or randomness. |
46 | Workflow-spawned sub-agents | Normal tool surface (read/search/edit/write, shell, web, MCP) subject to role posture, allowlists, and parent policy. File edits for write-capable roles auto-accept under Workflow; shell / web / MCP still require parent auto-approve or fail closed. |
47 | Parent session | Working directory, configured tools/MCP, permission mode, sandbox/network rules. |
48
49 ### Scale
50
51 - Up to **64 concurrent** live agents in one run by default (`[workflow] max_concurrent`, at most 128); additional spawns wait for a slot.
52 - No default cumulative child limit; `[workflow] max_children = 0` leaves total work uncapped.
53 - Owners can set a positive `max_children` limit and configure `max_concurrent`.
54 - Automatic launch is model-judged on scope; the host enforces configured owner limits and plan validation.
55 - Plan the population the work needs and let the host queue and clamp it.
56 These ceilings are enforcement, not a reason to pre-shrink a valid plan.
57
58 See the Workflow JS sandbox tests for the fail-closed host surface inventory.
59
60 ## Language Choice
61
62 | Surface | Strength | Tradeoff | Stance |
63 |---|---|---|---|
64 | YAML / JSON IR | Simple, reviewable, no runtime | Verbose for generated workflows | Keep as interchange/debug format |
65 | JavaScript | Familiar object syntax and easy agent generation | Unsafe if executed as a general runtime | First-class authoring through declarative compile-only subset |
66 | TypeScript | Best editor/types story for workflow SDK | Needs stripping/typechecking if full TS is supported | Same compile-only subset for now; richer SDK later |
67
68 The default high-capability path is TypeScript/JavaScript authoring, but only as
69 a compile step. The compiler accepts a JSON-compatible object inside
70 `workflow({...})` from `.workflow.js` or `.workflow.ts`, lowers it to
71 `WorkflowSpec`, and runs the Rust validation gate. (Starlark authoring was a
72 bootstrap reference and has been removed; Workflow authoring is JS-only.)
73
74 ## Contract
75
76 Accepted source shape:
77
78 ```js
79 export default workflow({
80 "id": "issue-audit-js",
81 "goal": "Audit an issue fix with parallel agents",
82 "nodes": [
83 {
84 "branch": {
85 "id": "parallel-audit",
86 "children": [
87 { "agent": { "id": "code-audit", "prompt": "Review code", "agent_type": "review" } },
88 { "agent": { "id": "test-audit", "prompt": "Review tests", "agent_type": "verifier" } }
89 ]
90 }
91 },
92 { "reduce": { "id": "summary", "inputs": ["code-audit", "test-audit"], "prompt": "Summarize" } }
93 ]
94 });
95 ```
96
97 Supported node wrappers: `agent`, `branch`, `sequence`, and `reduce`. Raw
98 `WorkflowNode` JSON IR with `kind` / `spec` also remains valid.
99
100 An `agent` node may declare `"profile": "reviewer"` to run as a named fleet
101 roster profile. The name is trimmed and lowercased at compile time and must be
102 a single token (no whitespace, quotes, or `=`); the saved roster is resolved at
103 dispatch time, and explicit fields on the agent override profile defaults.
104
105 The runtime `task()` surface also accepts `cwd` for an existing repository-
106 relative working directory. This is required when a workflow is launched from
107 a multi-repository workspace and the child needs shell or file access. `cwd`
108 is validated by the host, does not grant mutation authority, and should be
109 paired with `worktree: true` when the child needs an isolated checkout.
110
111 The compiler rejects effectful constructs such as `import`, `require`, `fetch`,
112 `process`, `Deno`, `Bun`, `child_process`, file reads/writes, `eval`, `async`,
113 and `await`. This is intentionally stricter than JavaScript: workflow source is
114 a familiar declaration format, not a second execution runtime. The denied
115 effects are not denied to the run — put them in a child worker, which has
116 the full tool surface, and keep the script to coordination.
117
118 ## Gates
119
120 A gate fires on a role's completion (`on: role_complete`) and blocks the role
121 named in `blocks_role` until the gate passes. That makes `blocks_role` a
122 **different** role from the one being gated — a gate that verifies phase 2's
123 work must block phase 3, never phase 2:
124
125 ```js
126 // Correct: verify the implementer, block the next stage.
127 gates: [{
128 id: "verify-fix",
129 gate: "verify",
130 on: "role_complete",
131 role: "implement",
132 blocks_role: "verify",
133 on_fail: "escalate",
134 max_retries: 1,
135 require_explicit_verdict: true,
136 }]
137 ```
138
139 Admission rejects a gate that blocks its own role, a cycle of role gates,
140 and a gate whose explicitly named prerequisite first occurs after its blocked
141 role in a sequential plan. Diagnostics name the contradictory gate and roles
142 before any child starts. Parallel structure, unknown profile roles and dynamic
143 raw JavaScript order are not assigned a total order; runtime gates still enforce the prerequisite at dispatch.
144
145 Native singleton and sequence steps use the same settled behavior as parallel
146 steps. Ordinary failures retain partial results and let independent work
147 continue. A step whose required input failed or is missing is skipped with a
148 named reason; it never receives an empty substitute and never launches a child.
149 Raw JavaScript `task()` remains fail-fast unless the author uses the existing
150 settled combinators. Reducers can explicitly summarize partial inputs; they
151 must disclose missing inputs instead of claiming that blocked work ran.
152
153 Let workers finish their assigned outcome. Legacy model task limits are accepted
154 for compatibility but ignored, and token hints are not spend caps. Actual owner
155 limits belong in operator, role/Fleet, parent or saved-runtime configuration.
156 Preserve partial findings and exact blockers for a follow-up instead of discarding
157 completed work. Schema repair cannot invent a deadline from a legacy task field.
158
159 ## Verification
160
161 - `cargo test -p codewhale-workflow --locked javascript`
162
163 Current example: `.codewhale/workflows/issue_audit.workflow.js`.
164
165 `codewhale workflow run <name>` looks for `workflows/<name>.workflow.js`, then,
166 in a trusted workspace, `.codewhale/workflows/<name>.workflow.js` (the same
167 project store the TUI offers as `/<name>`), trying the name as typed and with
168 `-` as `_`. A path or
169 `--source-path` is used as given. The source must sit inside the execution
170 root, so the CLI does not run workflows from the user store
171 `~/.codewhale/workflows`.
172
173 ## Agent-Written fleet Workflows
174
175 The primary product flow is not "ask the user to write a script." The main
176 agent should decide when a task deserves workflow orchestration, draft the
177 Workflow source, show the plan for the current permission mode, and then let
178 the runtime compile and monitor it.
179
180 Workflow owns the plan: phases, branches, loops, reducers, and intermediate
181 results. fleet owns the durable roster, member identity, semantic role, and
182 saved provider/model pins or inheritance. Runtime owns tool posture, launch
183 concurrency, leases, heartbeats, logs, receipts, and resume/stop/restart
184 controls. In other words, a workflow selects fleet members and monitors their
185 Runtime runs; it isn't an executor, because the script has no shell or
186 filesystem of its own — effects live in the workers.
187
188 Workflow-to-Runtime launch validation applies a conservative default shape
189 before any Workflow IR is lowered to selected workers:
190
191 - no default total worker limit; a positive owner-configured `max_children` still applies;
192 - up to 64 live worker agents at once by default (at most 128); larger populations queue (block) on the
193 host's per-run concurrency gate until a live slot frees, then select through
194 fleet and execute through Runtime;
195 - no default structural nesting cap; positive owner `workflow.max_depth` values apply;
196 - no default Runtime delegation depth cap; explicit owner restrictions remain
197 independent of Workflow IR shape.
198
199 Those limits distinguish population from instantaneous launch concurrency. A
200 long-running Workflow can still drain through a smaller Runtime worker
201 pool. Model selection stays per member: a DeepSeek preset can suggest
202 `deepseek-v4-pro` for the orchestrator and `deepseek-v4-flash` for nearby
203 workers, but users and agents may override any slot when the task calls for it.
204
205 ## Experimental search is a Workflow option
206
207 Experimental search generalizes the existing best-of-N recipe without adding a
208 new product mode, scheduler, or sub-agent API. The proposed search spec would
209 freeze the objective, baseline, model request and resolved version, public
210 evidence, evaluator hash, hard gates, scoring rule, budgets, write scope,
211 rounds, and review-only integration policy before admission; it is a design,
212 not shipped code.
213
214 The current JS starter (`.codewhale/workflows/operate_best_of_n.workflow.js`) supports
215 structured generation and read-only review with `strategy: "search"`, and
216 exposes `task.verifyCandidate` when `args.evaluator` is provided so runtime-owned
217 command gates, held-out evaluation, and clean-baseline replay run through the
218 host evaluator (Linux bubblewrap). Benchmark scoring and automated promotion
219 remain separate; a candidate's self-verdict is never promoted into evaluator
220 truth. See [Workflow Experimental Search](WORKFLOW_EXPERIMENTAL_SEARCH.md).
221
221 lines MARKDOWN