@ferris1225/pi-subagents 5.0.6 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,18 @@
1
1
  /**
2
- * The subagent_workflow tool: declare a dependency graph of sub-agent phases
3
- * once and let the runtime dispatch dependents as prerequisites settle.
2
+ * The subagent_workflow tool runs a built-in plan with named task inputs.
3
+ * Scheduling, isolation, and independent acceptance are owned by the runtime.
4
4
  *
5
5
  * The graph is validated before anything starts (see plan.ts), so an invalid
6
6
  * plan costs zero child processes. A valid plan returns a launch receipt
7
7
  * immediately; one completion message summarises the whole graph.
8
8
  */
9
9
 
10
+ import { StringEnum } from "@earendil-works/pi-ai";
10
11
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
11
12
  import { Text } from "@earendil-works/pi-tui";
12
13
  import { Type } from "typebox";
13
14
  import { isWriteCapableAgent, loadBuiltinAgents } from "../delegation/agents.ts";
14
- import { defaultIsolationMode, IsolationSchema, PhaseIdSchema, ScopeSchema } from "../delegation/dispatch.ts";
15
+ import { defaultIsolationMode } from "../delegation/dispatch.ts";
15
16
  import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
16
17
  import { loadConfig } from "../configuration/config.ts";
17
18
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
@@ -27,51 +28,15 @@ import {
27
28
  workflowStatus,
28
29
  type WorkflowStatusView,
29
30
  } from "./engine.ts";
30
- import { migrateWorkflowDefinition, resolveWorkflowDefinition } from "./files.ts";
31
- import { compileWorkflow, WORKFLOW_NODE_ID_MAX_LENGTH, type WorkflowPlanInput } from "./plan.ts";
31
+ import { compileBuiltinWorkflow } from "./templates.ts";
32
32
 
33
- const WorkflowNodeSchema = Type.Object({
34
- id: Type.String({
35
- minLength: 1,
36
- maxLength: WORKFLOW_NODE_ID_MAX_LENGTH,
37
- pattern: "^[A-Za-z][A-Za-z0-9._-]*$",
38
- description: "Stable node id. Dependents name it in dependsOn and in result placeholders.",
33
+ const WorkflowParams = Type.Object({
34
+ workflow: StringEnum(["code-review", "research", "migration"] as const, {
35
+ description: "Built-in plan: code-review inspects a target; research answers a question; migration applies two planned slices. Every plan ends with independent acceptance.",
39
36
  }),
40
- agent: Type.String({ minLength: 1, description: "Name of an enabled agent." }),
41
- task: Type.String({
42
- minLength: 1,
43
- pattern: "\\S",
44
- description:
45
- "Self-contained brief. {{<dependency-id>}} interpolates an upstream node's answer; {{<id>.status}}, {{<id>.runId}} and {{<id>.error}} interpolate facts. Only declared dependencies may be referenced.",
37
+ inputs: Type.Record(Type.String(), Type.String({ minLength: 1, pattern: "\\S" }), {
38
+ description: "Named inputs. code-review: TARGET. research: QUESTION. migration: TARGET, CONTRACT, CORE_CHANGE, ADAPTER_CHANGE, CORE_SCOPE, CORE_TEST_SCOPE, ADAPTER_SCOPE, ADAPTER_TEST_SCOPE. Scope values are exact paths relative to cwd. Include existing evidence and done conditions in task inputs.",
46
39
  }),
47
- dependsOn: Type.Optional(
48
- Type.Array(Type.String({ minLength: 1 }), {
49
- description: "Node ids that must complete before this one starts. Omit for a node that starts immediately.",
50
- }),
51
- ),
52
- phaseId: PhaseIdSchema,
53
- scope: ScopeSchema,
54
- cwd: Type.Optional(Type.String({ description: "Working directory for this node; defaults to the caller cwd." })),
55
- isolation: IsolationSchema,
56
- });
57
-
58
- const WorkflowParams = Type.Object({
59
- name: Type.Optional(
60
- Type.String({
61
- maxLength: 60,
62
- description: "Workflow name: shown in the widget and status, and the namespace for derived phase ids.",
63
- }),
64
- ),
65
- description: Type.Optional(Type.String({ description: "One line stating what the graph delivers." })),
66
- nodes: Type.Optional(
67
- Type.Array(WorkflowNodeSchema, { description: "Inline graph. Mutually exclusive with workflow/file." }),
68
- ),
69
- workflow: Type.Optional(
70
- Type.String({ description: "Name of a saved workflow under .pi/workflows/ or ~/.pi/agent/workflows/." }),
71
- ),
72
- file: Type.Optional(
73
- Type.String({ description: "Workflow definition file (JSON, or Markdown with a json fenced block)." }),
74
- ),
75
40
  });
76
41
 
77
42
  export interface WorkflowToolDetails {
@@ -88,14 +53,14 @@ function launchReceipt(status: WorkflowStatusView): string {
88
53
  "",
89
54
  "Nodes:",
90
55
  ...status.nodes.map((node) => {
91
- const parts = ["- " + node.id + " (" + node.agent + ")"];
56
+ const parts = ["- " + node.id + " (" + node.agent + ")" + (node.kind === "acceptance" ? " · required independent acceptance" : "")];
92
57
  if (node.runId !== undefined) parts.push("run #" + node.runId);
93
58
  else if (node.waitingFor) parts.push("waits for " + node.waitingFor.join(", "));
94
59
  else parts.push(node.state);
95
60
  return parts.join(" · ");
96
61
  }),
97
62
  "",
98
- "Every node is owned by this graph, including nodes waiting on dependencies. Do not perform or redispatch their work in main or another agent. The graph dispatches dependents automatically and sends one summary; continue only disjoint work or end your turn, and do not poll.",
63
+ "Every node is owned by this graph, including nodes waiting on dependencies. Do not perform or redispatch their work in main or another agent. Required independent acceptance runs after all authored work settles and integrates, including failed branches; the graph succeeds only when all work and acceptance pass. The graph sends one summary; continue only disjoint work or end your turn, and do not poll.",
99
64
  ];
100
65
  return lines.join("\n");
101
66
  }
@@ -135,7 +100,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
135
100
  name: "subagent_workflow",
136
101
  label: "Subagent Workflow",
137
102
  description:
138
- "Run a fixed dependency graph for substantial phases with known scopes. dependsOn starts a node after prerequisites finish and integrate. Pending nodes already own their work; main must not execute or redispatch it. Duplicate phases and external writer conflicts reject the graph before any child starts. Independent work without dependency edges uses subagent tasks. If a result must decide the next phase, dispatch it alone and decide in main. Omit isolation for automatic selection. One summary arrives after settlement; main checks outcomes, integrates, and releases.",
103
+ "Run a built-in workflow with named inputs: code-review, research, or migration. Custom graphs and workflow files are unsupported. The runtime schedules dependencies, integrates work, and requires an independent sentinel acceptance PASS. Pending nodes own their work; main must not duplicate it. Duplicate deliverables and writer conflicts reject the plan before dispatch. One final summary arrives automatically. Use subagent for a single phase or independent tasks.",
139
104
  exposure: "model-only",
140
105
  executionMode: "parallel",
141
106
  annotations: {
@@ -156,58 +121,15 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
156
121
  const toolInfos = runtime.getToolInfos();
157
122
  core.setEnvironment({ ctx, config, agents });
158
123
 
159
- const hasInline = params.nodes !== undefined;
160
- const hasReference = Boolean(params.workflow?.trim() || params.file?.trim());
161
- if (Number(hasInline) + Number(Boolean(params.workflow?.trim())) + Number(Boolean(params.file?.trim())) !== 1) {
162
- throw new Error(
163
- "Provide exactly one graph source: inline nodes, or a saved workflow/file. No nodes were started.",
164
- );
165
- }
166
-
167
- let plan: WorkflowPlanInput = {
168
- ...(params.name ? { name: params.name } : {}),
169
- ...(params.description ? { description: params.description } : {}),
170
- nodes: params.nodes ?? [],
171
- };
172
- let fallbackName = params.name ?? "workflow";
173
- if (hasReference) {
174
- const resolved = resolveWorkflowDefinition(
175
- ctx.cwd,
176
- { ...(params.workflow ? { name: params.workflow } : {}), ...(params.file ? { path: params.file } : {}) },
177
- { projectTrusted: ctx.isProjectTrusted?.() === true },
178
- );
179
- if (resolved.error || !resolved.definition) {
180
- throw new Error((resolved.error ?? "workflow definition could not be read") + ". No nodes were started.");
181
- }
182
- const definition = await migrateWorkflowDefinition(resolved.definition);
183
- plan = {
184
- name: params.name ?? definition.plan.name ?? definition.name,
185
- ...(params.description ?? definition.description
186
- ? { description: params.description ?? definition.description }
187
- : {}),
188
- nodes: definition.plan.nodes,
189
- };
190
- fallbackName = definition.name;
191
- }
192
-
193
- let workflow;
194
- try {
195
- workflow = compileWorkflow(plan, ctx.cwd, agents.map((agent) => agent.name), { fallbackName });
196
- } catch (error) {
197
- throw new Error(
198
- "Workflow rejected before any node started:\n" + (error instanceof Error ? error.message : String(error)),
199
- );
200
- }
201
-
124
+ // Ignore empty legacy placeholders, which previously triggered ambiguous
125
+ // source errors. A supplied custom definition is always rejected.
126
+ const unsupported = Object.entries(params as Record<string, unknown>).filter(([key, value]) =>
127
+ key !== "workflow" && key !== "inputs" && value !== undefined && value !== null && value !== ""
128
+ && !(Array.isArray(value) && value.length === 0),
129
+ ).map(([key]) => key);
130
+ if (unsupported.length) throw new Error(`Custom workflow fields are unsupported: ${unsupported.join(", ")}. Use only workflow and inputs. No nodes were started.`);
131
+ const workflow = compileBuiltinWorkflow(params.workflow, params.inputs, ctx.cwd, agents.map((agent) => agent.name));
202
132
  if (_signal?.aborted) throw new Error("Workflow cancelled before any node started.");
203
- if (hasReference) {
204
- const unfilled = [...new Set(workflow.nodes.flatMap((node) => node.task.match(/<(?:QUESTION|TARGET|CORE_CHANGE|ADAPTER_CHANGE)>/gu) ?? []))];
205
- if (unfilled.length) throw new Error(`Customize ${unfilled.join(", ")} in the saved template before running it. No nodes were started.`);
206
- }
207
- for (const node of workflow.nodes) {
208
- const agent = agents.find((candidate) => candidate.name === node.agent)!;
209
- if (node.isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) throw new Error(`Node "${node.id}" is read-only and cannot use worktree isolation. No nodes were started.`);
210
- }
211
133
 
212
134
  // Re-using a phase another owner holds fails the first node and blocks the
213
135
  // rest; reject the whole graph instead, with the owners named.
@@ -221,7 +143,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
221
143
  "Workflow \"" + workflow.name + "\" was not started: " + owned.length + " of " + workflow.nodes.length +
222
144
  " node" + (owned.length === 1 ? " reuses" : "s reuse") + " a phase this session already owns.\n" +
223
145
  lines.join("\n") +
224
- "\nInspect the owning run or workflow with subagent_status and reuse its evidence. Main handles follow-up work. Retire an interrupted run with subagent_stop({ id: <run id> }) only when discarding its retained session is intended. A genuinely different deliverable needs a distinct brief and phaseId. No nodes were started.",
146
+ "\nInspect the owning run or workflow with subagent_status and reuse its evidence. Main handles follow-up work. Retire an interrupted run with subagent_stop({ id: <run id> }) only when discarding its retained session is intended. Different deliverables need different task inputs. No nodes were started.",
225
147
  );
226
148
  }
227
149
 
@@ -257,11 +179,8 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
257
179
  },
258
180
 
259
181
  renderCall(args, theme) {
260
- const count = args.nodes?.length ?? 0;
261
- const label = args.name ?? args.workflow ?? args.file ?? "inline";
262
- const graph = count > 0 ? " " + count + " nodes" : "";
263
182
  return new Text(
264
- theme.fg("toolTitle", theme.bold("subagent_workflow ")) + theme.fg("accent", label) + theme.fg("dim", graph),
183
+ theme.fg("toolTitle", theme.bold("subagent_workflow ")) + theme.fg("accent", args.workflow ?? "?"),
265
184
  0,
266
185
  0,
267
186
  );
@@ -1,268 +0,0 @@
1
- ---
2
- name: workflow
3
- description: Plan and run a multi-phase sub-agent job as a dependency graph with subagent_workflow — deciding when a graph is worth it, slicing phases, wiring dependsOn, writing briefs that survive their own placeholders, and reading the one summary it returns. Use for requests with several ordered phases (survey, parallel changes, then a gate), or when a saved graph under .pi/workflows/ should run by name.
4
- ---
5
-
6
- # Planning multi-agent work as a workflow
7
-
8
- `subagent_workflow` runs a graph of ordinary sub-agent phases. You declare the
9
- nodes and their prerequisites once; the runtime starts each node the moment its
10
- prerequisites settle, and wakes you once with a summary
11
- of the whole graph. Nothing dispatches the next wave on your behalf except the
12
- runtime.
13
-
14
- Two things this changes about delegating: you stop paying a model turn between
15
- waves, and the graph — not your attention — is what remembers which phase is
16
- next. Two things it does not change: every node is still a one-shot leaf run
17
- with its own context, and main still owns architecture, integration, the final
18
- gate, and release.
19
-
20
- ## 1. Is a graph the right tool?
21
-
22
- | The request | The tool |
23
- | --- | --- |
24
- | One thing, one owner | `subagent` (single) |
25
- | A few independent lookups nobody reads before the end | `subagent` (`tasks`), in parallel |
26
- | One phase whose result you will read before deciding the next step | `subagent`; decide in main |
27
- | A small edit already understood in the current context | main, no child |
28
- | Several phases with real ordering, and the ordering is known now | `subagent_workflow` |
29
- | The same multi-phase job you will run again on another change | `subagent_workflow` with a saved definition |
30
-
31
- A graph earns its cost when **the dependency structure is already known** and
32
- **the phases are each substantial**. If you would have to look at phase one's
33
- answer to know what phase two is, you cannot write the graph yet: run phase one
34
- with `subagent` and write the graph afterwards. If every phase is a one-line
35
- read, the graph is overhead — do it in main.
36
-
37
- Choose proactively from task structure; the user does not need to name the
38
- tool. Use a graph for two or more substantial phases with known dependency
39
- edges and write scopes when scheduling saves coordination. Independent phases
40
- without edges use a parallel `subagent` batch. Honor an explicit user choice.
41
-
42
- After a discovery phase, reassess the remaining work: use a graph if its plan
43
- is now clear, or keep the next bounded step in main or a single child. A graph
44
- schedules a fixed plan; it does not decide what a discovery result means or
45
- change its nodes at runtime. Never add survey, implementation, review,
46
- confirmation, and gate nodes merely to follow a template.
47
-
48
- ## 2. Shape
49
-
50
- ```ts
51
- subagent_workflow({
52
- name: "auth-fix",
53
- description: "Fix the refresh race and inspect the implementation.",
54
- nodes: [
55
- { id: "map", agent: "scout", task: "Trace the refresh race in src/auth. Cite path:line and test coverage gaps." },
56
- { id: "fix", agent: "artisan", task: "Fix the race and add its regression tests. Evidence:\n{{map}}", dependsOn: ["map"],
57
- scope: { paths: ["src/auth", "test/auth.test.ts"] } },
58
- { id: "review", agent: "sentinel",
59
- task: "Inspect the implementation against the refresh contract and callers. Reuse completed checks; investigate concrete gaps and report confirmed defects. Do not edit files.\n{{fix}}",
60
- dependsOn: ["fix"] },
61
- ],
62
- });
63
- ```
64
-
65
- - `id` — identifies the node in `dependsOn` and in placeholders. Unique per graph.
66
- - `dependsOn` — start only after these complete. Omit for work that can begin now.
67
- - `task` — the brief (section 5). Placeholders allowed only for nodes it waits for.
68
- - `agent`, `scope`, `cwd`, `isolation`, `phaseId` — as for `subagent`.
69
- - Or run a saved definition: `subagent_workflow({ workflow: "code-review" })` /
70
- `subagent_workflow({ file: ".pi/workflows/code-review.md" })`.
71
-
72
- The call returns a launch receipt and the graph runs in the background. One
73
- completion message arrives when it settles. Do not poll it.
74
-
75
- ## 3. Topology: fresh eyes, then deterministic proof
76
-
77
- The shapes that are worth writing, in the order they usually appear:
78
-
79
- - **Survey → act.** One read-only node establishes the facts; writers depend on it
80
- and quote it. Reuse established evidence and verify decisive or conflicting claims.
81
- - **Fan-out with a join.** Independent slices of one plan run at the same time; a
82
- join node depends on all of them. Declare disjoint `scope.paths` per slice —
83
- the compiler rejects overlapping scopes between nodes with no dependency edge.
84
- - **Implementation review → claim verification.** A sentinel inspects the diff
85
- against requirements and callers. A skeptic tests only its named findings or a
86
- stated design assumption. Do not ask both for a general review. Reuse valid
87
- checks; add the second phase only when independent verification earns its cost.
88
- Both may run focused reproductions; scout cannot execute commands.
89
- - **A closing gate.** Run the project's required checks on the integrated result
90
- in main or one closing node. Keep focused regression checks with the writer;
91
- reuse a completed full gate unless later edits, failures, or unresolved
92
- concerns invalidate it. A separate gate node must justify its own session.
93
-
94
- Choose depth for the risk. Use sentinel for an implementation review, skeptic
95
- for a named assumption or finding, and both only for distinct questions. Every
96
- extra node should deliver new evidence. Keep a fix and its regression tests with
97
- one owner.
98
- A review request authorizes findings; apply fixes only when changes are also
99
- authorized. Request focused confirmation when material uncertainty remains.
100
-
101
- ## 4. What the runtime guarantees, and what it does not
102
-
103
- - **Dependents start on settlement, not on wall-clock.** A node's result is
104
- registered only after its isolated worktree is integrated, so a dependent sees
105
- the files its prerequisite actually left behind.
106
- - **Failure is contained.** A failed node blocks only its dependents. Independent
107
- branches keep running. The summary states completed, failed, and
108
- never-ran-with-why.
109
- - **No retries, no resumption.** Nodes are one-shot. Main finishes incomplete
110
- work from the child's partial edits and retained artifacts; a different
111
- deliverable needs a new graph. This mirrors the one-shot rule for `subagent`.
112
- - **A stopped graph stops cleanly.** `subagent_stop({ workflow: id })` prevents
113
- dependents from starting and cancels running nodes; the summary still reports
114
- what had completed.
115
- - **An interrupted graph is explained, not resumed.** If the session ends
116
- mid-graph, the next session's start notice and `subagent_status({ workflow })`
117
- report which nodes completed and which were still running, with their run ids.
118
- Checkpoints are written during execution, so a process crash also leaves the
119
- graph shape.
120
- - **Parent cancellation ends owned work.** Escape and conversation-tree navigation
121
- stop unfinished graphs and runs without completion wake-ups. Escape records
122
- stopped ids for the next user turn; do not send another stop or automatically
123
- restart cancelled work. New/resume/fork tears down the old Pi runtime and
124
- retains interruption evidence.
125
- - **Independent nodes start together.** There is no process-count limit or shared
126
- repository startup lock. Only dependencies delay ready work; final worktree
127
- integration into the original checkout remains serialized.
128
-
129
- ## 5. Briefs
130
-
131
- A node has no access to your conversation. Its brief carries:
132
-
133
- 1. the outcome and the done condition,
134
- 2. the facts it needs, including upstream answers via placeholders,
135
- 3. the boundary (what not to touch, what not to decide),
136
- 4. the output you want back.
137
-
138
- Include shared interface contracts or their file paths in every brief that needs
139
- them; saying main already established a contract does not transmit it. A settled
140
- run can still report a blocker: dependents must check prerequisite outputs, and
141
- main checks done conditions before claiming success.
142
-
143
- Write the brief the way you would brief a competent colleague who was not in the
144
- meeting. Name paths and symbols; do not paste file contents — every node has its
145
- own file tools, and a pasted file costs tokens it could have read.
146
-
147
- Ask for failures, not approval. "Is this good?" gets a yes; "what would break
148
- this, and what is missing?" gets findings. Say "do not edit any file" when a node
149
- is only judging.
150
-
151
- ## 6. Placeholders
152
-
153
- | Placeholder | Expands to |
154
- | --- | --- |
155
- | `{{id}}` | that node's final answer (bounded; long answers are clipped with a pointer) |
156
- | `{{id.status}}` | `completed` / `failed` / `blocked` / `stopped` |
157
- | `{{id.runId}}` | that node's run id, for follow-up inspection |
158
- | `{{id.error}}` | the failure reason, or `(no error reported)` |
159
-
160
- A placeholder may only name a node the current node waits for — directly or
161
- through the chain. That rule is enforced at compile time, because reading a
162
- sibling's answer would mean reading something that may not have run yet. If you
163
- want two branches to read each other, they are not independent: join them first.
164
-
165
- Keep results narrow. A node that returns a whole file makes every dependent pay
166
- for it; a node that returns paths and conclusions does not.
167
-
168
- ## 7. Scope and isolation
169
-
170
- `scope` is admission metadata, not access control. Declare the exact paths a
171
- node expects to write:
172
-
173
- - Two nodes with no dependency edge may not claim overlapping paths — the graph
174
- is rejected before anything starts. A dependency edge makes the overlap
175
- intentional (a fix, then its own test file).
176
- - External writer conflicts are rejected before any node starts. All pending
177
- nodes reserve their declared write scope, including while dependencies run.
178
- Main `edit`/`write` calls and other dispatches respect these reservations.
179
- Ordered nodes in the same graph may reuse a scope after their prerequisites
180
- settle. Arbitrary commands and undeclared writes are not sandboxed.
181
- - Usually omit `isolation`. Implementation nodes use a detached Git worktree,
182
- initialized from the caller's current tracked and non-ignored untracked files.
183
- Reading and review stay in the caller's directory. Without a Git repository or
184
- committed HEAD, automatic isolation uses the current directory and reports why.
185
- An explicit `worktree` override requires isolation and never falls back.
186
- Each isolated snapshot is also the integration base, so nodes see integrated
187
- prerequisites before commit and only their own delta is applied on settlement.
188
- - A stopped run retains phase and writer leases while its child or finalization
189
- can still change files, including after the stop call's bounded wait expires.
190
-
191
- ## 8. Saved definitions
192
-
193
- - Project: `.pi/workflows/<name>.json` or `.pi/workflows/<name>.md`
194
- - User: `~/.pi/agent/workflows/`
195
- - Shipped templates: this package's `workflows/` directory (`code-review`,
196
- `research`, `migration`)
197
-
198
- A Markdown definition carries prose plus one ```json fenced block with the plan
199
- (or a bare node array); JSON carries the plan object. Project definitions load
200
- only in a trusted project. Same-name precedence: project > user > builtin.
201
- Explicit file paths also require project trust. A call-level `name` overrides a
202
- saved graph's name. Customize unfilled question, target, and slice placeholders
203
- in a copy of a shipped template before execution.
204
-
205
- Save a graph when it will run again, when a reviewer should read the plan before
206
- it runs, or when the phases are long enough that you want them in version
207
- control. Run it by name; do not restate it inline.
208
-
209
- **Settled phases stay owned for the parent session; interrupted phases keep
210
- ownership across reloads.** Derived phase ids are `<workflow-slug>.<node-id>`.
211
- Re-running the same shape is rejected **before any node starts**, naming the
212
- owning runs. For a successfully completed phase, use `subagent_message` to
213
- continue the same deliverable with its retained context. Finish incomplete or
214
- interrupted work in main from the retained evidence. Retire the owner with
215
- `subagent_stop({ id })` only when intentionally discarding its retained session;
216
- give a different deliverable its own brief and phase id. Renaming the graph does
217
- not bypass exact task matching. A new session alone does not clear an interrupted
218
- run's claim.
219
-
220
- ## 9. Cost
221
-
222
- Every node is a full model session with its own context, and the summary carries
223
- each node's answer. Budget accordingly:
224
-
225
- - Give each phase one owner across main, subagent, and workflow, including
226
- pending nodes. Main continues only disjoint work. Pass completed main findings
227
- and checks into briefs; later nodes fill gaps instead of restarting research.
228
- - Use sentinel for implementation defects or skeptic for a named claim. Add both
229
- only for distinct questions; reuse valid checks across every owner.
230
- - Keep node answers short: conclusions, paths, `command → result`.
231
- - Choose nodes from independent work; do not split one tightly coupled change
232
- across nodes just to increase concurrency.
233
-
234
- ## 10. Anti-patterns
235
-
236
- | What you wrote | What it costs |
237
- | --- | --- |
238
- | A graph for a task with no real ordering | A model turn saved, two sessions wasted |
239
- | A node whose brief re-derives what a scout already established | Paying twice for the same reading |
240
- | `{{sibling}}` from a node that does not wait for it | Compile error; add the dependency or join first |
241
- | Two writers with overlapping `scope` and no edge between them | The whole graph is rejected before any node starts |
242
- | A reviewer asked "is this good?" | It approves; ask what would break it |
243
- | A gate node asked to judge quality instead of running the tests | An opinion where an exit code would have decided |
244
- | Retrying a failed node inside another node | Duplicate phase; main finishes the work instead |
245
- | Twenty nodes over one small change | Twenty contexts, one deliverable |
246
- | Reporting unverified findings as facts | The summary cannot tell "seen" from "suspected" |
247
-
248
- ## 11. Reading the summary
249
-
250
- One completion message per graph:
251
-
252
- ```text
253
- ### workflow auth-fix completed (3/3 completed)
254
- - map (scout) completed · run #12 · 1m02s
255
- - fix (artisan) completed · run #13 · 4m11s
256
- - review (sentinel) completed · run #15 · 2m40s
257
-
258
- Node answers:
259
- #### map
260
- …
261
- Totals: 3 nodes · anthropic/claude-sonnet-4: ↓48.0k $0.8200
262
- ```
263
-
264
- - Node answers are clipped here; the full report file is named when that happens.
265
- - `failed` / `never ran (blocked)` lines say why, and each run keeps its own
266
- retained artifacts.
267
- - Main then does what children cannot: inspect the integrated diff, run the gate
268
- if the graph's gate node could not, and report only checks that actually ran.