@ferris1225/pi-subagents 4.3.32 → 4.3.34

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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,42 @@
3
3
  Release notes for `@ferris1225/pi-subagents`. Only the most recent releases
4
4
  are kept here; every published version is preserved as a GitHub Release.
5
5
 
6
+ ## 4.3.34
7
+
8
+ - Reject a workflow that would reuse a phase this session already owns, before
9
+ any node starts, and name each owning run with the way out. A settled phase
10
+ stays owned once it settles, and an interrupted one keeps its claim across
11
+ reloads, so "re-run it in a new session" was wrong: the graph previously failed
12
+ its first node and blocked the rest.
13
+ - Say the same thing for a per-run duplicate: a parked owner is told to retire
14
+ the phase with `subagent_stop({ id })` instead of being told to let it finish.
15
+
16
+ ## 4.3.33
17
+
18
+ - Add `subagent_workflow`: declare a graph of phases with `dependsOn` and the
19
+ runtime dispatches each node the moment its prerequisites settle and a process
20
+ slot frees, without a parent model turn between waves. The graph is validated
21
+ before the first child starts (unique ids, existing dependencies, no cycles,
22
+ resolvable `{{id}}` placeholders, no declared writer-scope overlap between
23
+ nodes no dependency orders), so an invalid plan costs zero child processes.
24
+ - Nodes are ordinary one-shot runs: same dispatcher, admission, isolation,
25
+ durable checkpointing, and usage accounting. A node's result registers only
26
+ after its worktree is integrated, so a dependent reads what its prerequisite
27
+ actually left behind.
28
+ - A node completion is quiet; the graph reports once. The summary names
29
+ completed, failed, and never-ran nodes with the reason, inlines each node's
30
+ answer (clipped, with a full-report artifact when anything was cut), and adds a
31
+ per-model tally. A failed node blocks only its dependents.
32
+ - Saved definitions: `.pi/workflows/<name>.json` or `.md` in a trusted project,
33
+ `~/.pi/agent/workflows/` for the user, and `code-review`, `research`, and
34
+ `migration` templates shipped with the package. Markdown definitions carry
35
+ prose plus one `json` fenced block.
36
+ - `subagent_status` accepts `workflow` and reports graph nodes, wait reasons, and
37
+ retained graphs; `subagent_stop` accepts `workflow` and stops a graph without
38
+ starting its idle dependents. An unfinished graph's shape is retained on disk
39
+ for the next session's notice instead of resuming automatically.
40
+ - Ship a `workflow` skill with the authoring guidance, and describe the graph
41
+ tool in the delegation contract.
6
42
  ## 4.3.32
7
43
 
8
44
  - Derive a role's tools from the live catalog instead of a hardcoded name list.
package/README.md CHANGED
@@ -13,6 +13,19 @@ self-contained — parallel phases usually beat a serialized main.
13
13
 
14
14
  ## What's new
15
15
 
16
+ **4.3.34** — a workflow that would reuse a phase this session already owns (a
17
+ settled run, or an interrupted one retained from an earlier session) is now
18
+ rejected before any node starts, naming each owning run and the way out; the
19
+ per-run duplicate message says the same for a parked owner instead of asking you
20
+ to "let it finish".
21
+
22
+ **4.3.33** — dependency graphs for multi-phase work. `subagent_workflow` declares
23
+ nodes with `dependsOn`, validates the graph before any child starts, dispatches
24
+ each node as its prerequisites settle, and reports the whole graph once. Saved
25
+ definitions live in `.pi/workflows/` or `~/.pi/agent/workflows/`, three templates
26
+ ship with the package, and a `workflow` skill carries the authoring guidance.
27
+ `subagent_status` and `subagent_stop` accept a graph id.
28
+
16
29
  **4.3.32** — codemode-aware, tool-agnostic role policy and a minimal config.
17
30
  `scout` keeps every active tool the host proves read-only and can never keep a
18
31
  tool that reaches other tools, such as `codemode`, while `artisan` inherits the
@@ -31,6 +44,7 @@ is preserved as a GitHub Release.
31
44
  - [Install](#install)
32
45
  - [The team](#the-team)
33
46
  - [Dispatching work](#dispatching-work)
47
+ - [Workflows](#workflows)
34
48
  - [Parallel edits](#parallel-edits)
35
49
  - [Runs: status and stop](#runs-status-and-stop)
36
50
  - [Live status and results](#live-status-and-results)
@@ -196,6 +210,82 @@ These defaults follow [OpenAI's GPT-6 Astra model guidance](https://developers.o
196
210
  and [Eric Provencher's skills and prompts guidance](https://x.com/pvncher/status/2095991462416490862).
197
211
  They simplify instructions without changing the configured models or thinking levels.
198
212
 
213
+ ## Workflows
214
+
215
+ A request sometimes has phases whose order is known before the work starts:
216
+ establish the facts, change independent slices at the same time, then run one
217
+ gate. `subagent_workflow` declares that graph once. The runtime starts each node
218
+ the moment its prerequisites settle and a process slot frees, so no parent model
219
+ turn sits between waves, and it wakes the main agent once with a summary of the
220
+ whole graph.
221
+
222
+ ```ts
223
+ subagent_workflow({
224
+ name: "auth-fix",
225
+ description: "Map the refresh race, fix it, gate it.",
226
+ nodes: [
227
+ { id: "map", agent: "scout", task: "Map the refresh race in src/auth. Cite path:line." },
228
+ { id: "fix", agent: "artisan", task: "Fix it. Evidence:\n{{map}}", dependsOn: ["map"],
229
+ scope: { paths: ["src/auth"] } },
230
+ { id: "tests", agent: "artisan", task: "Add regression tests. Evidence:\n{{map}}",
231
+ dependsOn: ["map"], scope: { paths: ["test/auth.test.ts"] } },
232
+ { id: "gate", agent: "artisan", task: "Run the checks.\nFix:\n{{fix}}\nTests:\n{{tests}}",
233
+ dependsOn: ["fix", "tests"] },
234
+ ],
235
+ });
236
+ ```
237
+
238
+ - `{{id}}` interpolates that node's final answer into a dependent's brief;
239
+ `{{id.status}}`, `{{id.runId}}`, and `{{id.error}}` interpolate facts. A
240
+ placeholder may only name a node the current one waits for, directly or through
241
+ its chain; anything else is rejected at compile time.
242
+ - The graph is validated before the first child starts: unique ids, existing
243
+ dependencies, no cycles, resolvable placeholders, and no declared writer-scope
244
+ overlap between nodes that no dependency orders.
245
+ - Nodes are ordinary one-shot runs: same admission, isolation, durable
246
+ checkpoints, and usage accounting as a `subagent` call. A node's result is
247
+ registered only after its worktree is integrated, so a dependent reads what its
248
+ prerequisite actually left behind.
249
+ - Failure is contained by the graph. A failed node blocks only its dependents,
250
+ independent branches keep running, and the summary names completed, failed, and
251
+ never-ran nodes with the reason. Nodes never retry: main finishes incomplete work
252
+ from the retained evidence.
253
+ - A workflow reports once. Node completions are quiet, and the single summary
254
+ carries each node's answer (clipped, with a full-report file when anything was
255
+ cut) plus a per-model tally.
256
+ - Write-capable nodes in a graph default to a detached worktree, which needs a
257
+ committed `HEAD`; pass `"isolation": "shared"` on a node to keep it in your
258
+ checkout and serialize it on the repository write lane.
259
+
260
+ Saved definitions run by name and can be reviewed before they run:
261
+
262
+ - Project: `.pi/workflows/<name>.json` or `.pi/workflows/<name>.md` (trusted projects only)
263
+ - User: `~/.pi/agent/workflows/`
264
+ - Shipped: the `code-review`, `research`, and `migration` templates in this package
265
+ - Precedence: project > user > built-in, where the same `name` wins
266
+
267
+ ```ts
268
+ subagent_workflow({ workflow: "code-review" });
269
+ subagent_workflow({ file: ".pi/workflows/code-review.md" });
270
+ ```
271
+
272
+ A Markdown definition carries prose plus one `json` fenced block holding the plan
273
+ object or a bare node array. The package also ships a `workflow` skill
274
+ (`skills/workflow/SKILL.md`) with the authoring guidance: when a graph is worth
275
+ its cost, how to slice phases, how to write briefs, and the anti-patterns.
276
+
277
+ Derived phase ids are `<workflow-slug>.<node-id>`, and a phase stays owned after it
278
+ settles and across reloads — an interrupted run keeps its claim until it is retired.
279
+ A graph that reuses one is rejected before any node starts, naming each owning run;
280
+ retire the owner with `subagent_stop({ id })`, or give those nodes different ids or
281
+ `phaseId`s, or run the graph under a different name.
282
+
283
+ `subagent_status({ workflow: id })` reports nodes and their wait reasons;
284
+ `subagent_stop({ workflow: id })` stops a graph without starting its idle
285
+ dependents. An unfinished graph keeps its shape on disk, so the next session's
286
+ start notice and `subagent_status` report which nodes completed and which were
287
+ still running.
288
+
199
289
  ## Parallel edits
200
290
 
201
291
  `scope` is declarative admission metadata for expected writes, not access control. `paths`
@@ -256,8 +346,9 @@ deliverable needs a new phase and brief, not a recycled thread.
256
346
 
257
347
  | Tool | What it does |
258
348
  | ---- | ------------ |
259
- | `subagent_status` | Read-only progress check. Omit `id` to list this parent session's runs, or pass an exact numeric `id` to inspect one. |
260
- | `subagent_stop` | Destructively cancel/retire a run by id/prefix, or all active runs with `all: true`. Delivers partial output and finalizes isolated changes. |
349
+ | `subagent_workflow` | Run a dependency graph: declare `nodes` with `dependsOn` (or name a saved definition), get a launch receipt, and receive one summary when the graph settles. |
350
+ | `subagent_status` | Read-only progress check. Omit `id` to list this parent session's runs, or pass an exact numeric `id` to inspect one. Omit `workflow` to include graphs, or pass a graph id. |
351
+ | `subagent_stop` | Destructively cancel/retire a run by id/prefix, a whole graph with `workflow: id`, or all active runs with `all: true`. Delivers partial output and finalizes isolated changes. |
261
352
 
262
353
  ```ts
263
354
  subagent_status({});
@@ -481,6 +572,7 @@ that removes it, so this directory does not grow without bound:
481
572
  | `ferris-pi-subagents/<project>/sessions/` | Child sessions for in-run fallback and manual recovery | When the owning session ends and no recovery record claims them |
482
573
  | `ferris-pi-subagents/<project>/worktrees/` | Isolated checkouts for parallel writers | On integration, or when no thread/recovery record claims them |
483
574
  | `ferris-pi-subagents/<project>/results/` | Full text of truncated results | After 7 days, or beyond 50 per project |
575
+ | `ferris-pi-subagents/<project>/pi-subagents-workflows.json` | Shape and node state of unfinished workflow graphs | When the graph settles, or after 30 days |
484
576
  | `ferris-pi-subagents/<project>/tmp/` | Child prompt copies and the no-retry policy shim | When its owning process exits |
485
577
  | `ferris-pi-subagents/<project>/` | All of the above for one checkout | After 3 idle days unless a thread/recovery record claims it |
486
578
 
package/index.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * - configuration/ — persisted settings, model routes, and setup UI
8
8
  * - execution/ — process queue, RPC transport/control, and model handoff
9
9
  * - lifecycle/ — durable threads, restoration, controls, and delivery
10
+ * - workflow/ — dependency-graph plans, discovery, and the graph runner
10
11
  * - isolation/ — Git worktrees, recovery, and temporary-state hygiene
11
12
  * - presentation/ — announcements, formatting, monitor, and the active-run
12
13
  * widget
@@ -27,9 +28,11 @@ import { loadBuiltinAgents } from "./src/delegation/agents.ts";
27
28
  import { registerSubagentTool } from "./src/delegation/dispatch.ts";
28
29
  import { buildDelegationDirective, installDelegationSections } from "./src/delegation/prompt.ts";
29
30
  import { currentSubagentDepth } from "./src/execution/spawn.ts";
31
+ import { createDispatchCore } from "./src/lifecycle/dispatch-core.ts";
30
32
  import { createRuntime } from "./src/lifecycle/runtime.ts";
31
33
  import { bootstrapDurableState } from "./src/lifecycle/thread-restore.ts";
32
34
  import { registerLookupTools } from "./src/lifecycle/tools.ts";
35
+ import { registerWorkflowTool, restoreWorkflowState } from "./src/workflow/tool.ts";
33
36
  import { registerAnnouncements } from "./src/presentation/announcements.ts";
34
37
  import { clearActiveRunsWidget } from "./src/presentation/widget.ts";
35
38
 
@@ -64,7 +67,12 @@ export default function (pi: ExtensionAPI): void {
64
67
  await runtime.shutdown();
65
68
  });
66
69
 
67
- registerSubagentTool(pi, runtime);
70
+ // One dispatcher serves both delegation tools, so a workflow node is an
71
+ // ordinary managed run: same queue pacing, admission, isolation, and
72
+ // durable checkpointing.
73
+ const dispatchCore = createDispatchCore(runtime);
74
+ registerSubagentTool(pi, runtime, dispatchCore);
75
+ registerWorkflowTool(pi, runtime, dispatchCore);
68
76
  registerLookupTools(pi, runtime);
69
77
 
70
78
  pi.registerCommand("subagents-setup", {
@@ -76,6 +84,7 @@ export default function (pi: ExtensionAPI): void {
76
84
 
77
85
  pi.on("session_start", async (_event, ctx) => {
78
86
  await bootstrapDurableState(runtime, ctx.cwd);
87
+ await restoreWorkflowState(runtime, ctx);
79
88
  });
80
89
  registerAnnouncements(pi, runtime);
81
90
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "4.3.32",
3
+ "version": "4.3.34",
4
4
  "description": "A managed sub-agent team for pi: lightweight scout research and artisan implementation, one-shot runs, read-only status, and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -25,6 +25,8 @@
25
25
  "files": [
26
26
  "index.ts",
27
27
  "src",
28
+ "skills",
29
+ "workflows",
28
30
  "README.md",
29
31
  "CHANGELOG.md",
30
32
  "LICENSE"
@@ -32,6 +34,9 @@
32
34
  "pi": {
33
35
  "extensions": [
34
36
  "./index.ts"
37
+ ],
38
+ "skills": [
39
+ "./skills"
35
40
  ]
36
41
  },
37
42
  "scripts": {
@@ -0,0 +1,230 @@
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 a process slot frees, 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
+ A workflow is a forced choice, not a default. The user asking for "a workflow"
38
+ or naming a saved one is binding; otherwise apply the table.
39
+
40
+ ## 2. Shape
41
+
42
+ ```ts
43
+ subagent_workflow({
44
+ name: "auth-fix", // shown in the widget/status; namespaces phase ids
45
+ description: "Map the race, fix it, gate it.", // one line, becomes the summary's subtitle
46
+ nodes: [
47
+ { id: "map", agent: "scout", task: "Map the refresh race in src/auth. Cite path:line." },
48
+ { id: "fix", agent: "artisan", task: "Fix it. Evidence:\n{{map}}", dependsOn: ["map"],
49
+ scope: { paths: ["src/auth"] } },
50
+ { id: "tests", agent: "artisan", task: "Add regression tests for the race. Evidence:\n{{map}}",
51
+ dependsOn: ["map"], scope: { paths: ["test/auth.test.ts"] } },
52
+ { id: "gate", agent: "artisan", task: "Run the repository's checks and fix only what this change broke.\nFix:\n{{fix}}\nTests:\n{{tests}}",
53
+ dependsOn: ["fix", "tests"] },
54
+ ],
55
+ })
56
+ ```
57
+
58
+ - `id` — identifies the node in `dependsOn` and in placeholders. Unique per graph.
59
+ - `dependsOn` — start only after these complete. Omit for work that can begin now.
60
+ - `task` — the brief (section 5). Placeholders allowed only for nodes it waits for.
61
+ - `agent`, `scope`, `cwd`, `isolation`, `phaseId` — as for `subagent`.
62
+ - Or run a saved definition: `subagent_workflow({ workflow: "code-review" })` /
63
+ `subagent_workflow({ file: ".pi/workflows/code-review.md" })`.
64
+
65
+ The call returns a launch receipt and the graph runs in the background. One
66
+ completion message arrives when it settles. Do not poll it.
67
+
68
+ ## 3. Topology: fresh eyes, then deterministic proof
69
+
70
+ The shapes that are worth writing, in the order they usually appear:
71
+
72
+ - **Survey → act.** One read-only node establishes the facts; writers depend on it
73
+ and quote it. Never let a writer re-derive what a scout already established.
74
+ - **Fan-out with a join.** Independent slices of one plan run at the same time; a
75
+ join node depends on all of them. Declare disjoint `scope.paths` per slice —
76
+ the compiler rejects overlapping scopes between nodes with no dependency edge.
77
+ - **Independent confirmation.** A node that *produced* a finding cannot see its
78
+ own gap. Give every claim the user will act on a separate node that tries to
79
+ disprove it ("reproduce this, or say what the code actually does"), and a
80
+ different lens per reviewer rather than the same prompt twice.
81
+ - **A closing gate.** The last node runs the project's own checks. Prefer
82
+ commands over opinions: the repository's test suite, typecheck, build, or the
83
+ verification line its README names. Ask for the strongest tier it has, not the
84
+ fastest one.
85
+
86
+ One deliverable gets one confirmation mechanism. A reviewer loop plus a
87
+ confirmer plus a reader on the same artifact is four sessions re-reading one
88
+ piece of work.
89
+
90
+ ## 4. What the runtime guarantees, and what it does not
91
+
92
+ - **Dependents start on settlement, not on wall-clock.** A node's result is
93
+ registered only after its isolated worktree is integrated, so a dependent sees
94
+ the files its prerequisite actually left behind.
95
+ - **Failure is contained.** A failed node blocks only its dependents. Independent
96
+ branches keep running. The summary states completed, failed, and
97
+ never-ran-with-why.
98
+ - **No retries, no resumption.** Nodes are one-shot. Main finishes incomplete
99
+ work from the child's partial edits and retained artifacts; a different
100
+ deliverable needs a new graph. This mirrors the one-shot rule for `subagent`.
101
+ - **A stopped graph stops cleanly.** `subagent_stop({ workflow: id })` prevents
102
+ dependents from starting and cancels running nodes; the summary still reports
103
+ what had completed.
104
+ - **An interrupted graph is explained, not resumed.** If the session ends
105
+ mid-graph, the next session's start notice and `subagent_status({ workflow })`
106
+ report which nodes completed and which were still running, with their run ids.
107
+ - **Capacity is pacing, not refusal.** `maxConcurrentAgents` limits simultaneous
108
+ child processes; a wider graph queues and starts as slots free. Queue position
109
+ never changes dependency order.
110
+
111
+ ## 5. Briefs
112
+
113
+ A node has no access to your conversation. Its brief carries:
114
+
115
+ 1. the outcome and the done condition,
116
+ 2. the facts it needs, including upstream answers via placeholders,
117
+ 3. the boundary (what not to touch, what not to decide),
118
+ 4. the output you want back.
119
+
120
+ Write the brief the way you would brief a competent colleague who was not in the
121
+ meeting. Name paths and symbols; do not paste file contents — every node has its
122
+ own file tools, and a pasted file costs tokens it could have read.
123
+
124
+ Ask for failures, not approval. "Is this good?" gets a yes; "what would break
125
+ this, and what is missing?" gets findings. Say "do not edit any file" when a node
126
+ is only judging.
127
+
128
+ ## 6. Placeholders
129
+
130
+ | Placeholder | Expands to |
131
+ | --- | --- |
132
+ | `{{id}}` | that node's final answer (bounded; long answers are clipped with a pointer) |
133
+ | `{{id.status}}` | `completed` / `failed` / `blocked` / `stopped` |
134
+ | `{{id.runId}}` | that node's run id, for follow-up inspection |
135
+ | `{{id.error}}` | the failure reason, or `(no error reported)` |
136
+
137
+ A placeholder may only name a node the current node waits for — directly or
138
+ through the chain. That rule is enforced at compile time, because reading a
139
+ sibling's answer would mean reading something that may not have run yet. If you
140
+ want two branches to read each other, they are not independent: join them first.
141
+
142
+ Keep results narrow. A node that returns a whole file makes every dependent pay
143
+ for it; a node that returns paths and conclusions does not.
144
+
145
+ ## 7. Scope and isolation
146
+
147
+ `scope` is admission metadata, not access control. Declare the exact paths a
148
+ node expects to write:
149
+
150
+ - Two nodes with no dependency edge may not claim overlapping paths — the graph
151
+ is rejected before anything starts. A dependency edge makes the overlap
152
+ intentional (a fix, then its own test file).
153
+ - Externally, declared scopes are still checked against live runs at dispatch
154
+ time, so a node that conflicts with unrelated work fails alone.
155
+ - Write-capable nodes default to a detached Git worktree in a graph, and their
156
+ changes are integrated once, when the node settles. The checkout therefore
157
+ always looks like the graph's completed work — which is exactly what the next
158
+ node needs to read.
159
+
160
+ ## 8. Saved definitions
161
+
162
+ - Project: `.pi/workflows/<name>.json` or `.pi/workflows/<name>.md`
163
+ - User: `~/.pi/agent/workflows/`
164
+ - Shipped templates: this package's `workflows/` directory (`code-review`,
165
+ `research`, `migration`)
166
+
167
+ A Markdown definition carries prose plus one ```json fenced block with the plan
168
+ (or a bare node array); JSON carries the plan object. Project definitions load
169
+ only in a trusted project. Same-name precedence: project > user > builtin.
170
+
171
+ Save a graph when it will run again, when a reviewer should read the plan before
172
+ it runs, or when the phases are long enough that you want them in version
173
+ control. Run it by name; do not restate it inline.
174
+
175
+ **A phase stays owned after it settles, and across reloads.** Derived phase ids
176
+ are `<workflow-slug>.<node-id>`; an interrupted run keeps its claim until it is
177
+ retired. Re-running the same shape is therefore rejected **before any node
178
+ starts**, naming the owning runs. Three ways forward: retire the owner with
179
+ `subagent_stop({ id })` (destructive — it drops that run's retained session),
180
+ give the reused nodes different ids or `phaseId`s, or run the graph under a
181
+ different name. A new session alone does not help: a retained interrupted run is
182
+ restored with its claim intact.
183
+
184
+ ## 9. Cost
185
+
186
+ Every node is a full model session with its own context, and the summary carries
187
+ each node's answer. Budget accordingly:
188
+
189
+ - Prefer the fewest nodes that still give each phase one owner and each claim one
190
+ confirmer.
191
+ - Keep node answers short: conclusions, paths, `command → result`.
192
+ - Do not add a node to fill a free process slot, and do not split one tightly
193
+ coupled change across nodes.
194
+
195
+ ## 10. Anti-patterns
196
+
197
+ | What you wrote | What it costs |
198
+ | --- | --- |
199
+ | A graph for a task with no real ordering | A model turn saved, two sessions wasted |
200
+ | A node whose brief re-derives what a scout already established | Paying twice for the same reading |
201
+ | `{{sibling}}` from a node that does not wait for it | Compile error; add the dependency or join first |
202
+ | Two writers with overlapping `scope` and no edge between them | The whole graph is rejected before any node starts |
203
+ | A reviewer asked "is this good?" | It approves; ask what would break it |
204
+ | A gate node asked to judge quality instead of running the tests | An opinion where an exit code would have decided |
205
+ | Retrying a failed node inside another node | Duplicate phase; main finishes the work instead |
206
+ | Twenty nodes over one small change | Twenty contexts, one deliverable |
207
+ | Reporting unverified findings as facts | The summary cannot tell "seen" from "suspected" |
208
+
209
+ ## 11. Reading the summary
210
+
211
+ One completion message per graph:
212
+
213
+ ```text
214
+ ### workflow auth-fix completed (4/4 completed)
215
+ - map (scout) completed · run #12 · 1m02s
216
+ - fix (artisan) completed · run #13 · 4m11s
217
+ - tests (artisan) completed · run #15 · 2m40s
218
+ - gate (artisan) completed · run #16 · 6m05s
219
+
220
+ Node answers:
221
+ #### map
222
+ …
223
+ Totals: 4 nodes · anthropic/claude-sonnet-4: ↓48.0k $0.8200
224
+ ```
225
+
226
+ - Node answers are clipped here; the full report file is named when that happens.
227
+ - `failed` / `never ran (blocked)` lines say why, and each run keeps its own
228
+ retained artifacts.
229
+ - Main then does what children cannot: inspect the integrated diff, run the gate
230
+ if the graph's gate node could not, and report only checks that actually ran.
@@ -26,6 +26,7 @@ const BUILTIN_READ_ONLY_TOOL_NAMES = ["read", "grep", "find", "ls"] as const;
26
26
  const BUILTIN_READ_ONLY_TOOL_SET: ReadonlySet<string> = new Set(BUILTIN_READ_ONLY_TOOL_NAMES);
27
27
  export const SUBAGENT_TOOL_NAMES = [
28
28
  "subagent",
29
+ "subagent_workflow",
29
30
  "subagent_status",
30
31
  "subagent_stop",
31
32
  ] as const;
@@ -17,7 +17,6 @@ import { resolveSubagentConcurrency } from "../execution/background.ts";
17
17
  import { formatCompletionBlock, formatUsage } from "../presentation/format.ts";
18
18
  import {
19
19
  formatTaskSummary,
20
- formatToolActivity,
21
20
  monitor,
22
21
  statusIcon,
23
22
  statusLabel,
@@ -35,20 +34,16 @@ import {
35
34
  type PhaseScopeInput,
36
35
  } from "./phase-scope.ts";
37
36
  import type { SubagentRuntime, SubagentThread } from "../lifecycle/runtime.ts";
38
- import { createBackgroundDispatcher } from "../lifecycle/thread-lifecycle.ts";
37
+ import { createDispatchCore, type DispatchCore } from "../lifecycle/dispatch-core.ts";
39
38
  import {
40
- getResultError,
41
39
  getResultOutput,
42
40
  isFailedResult,
43
41
  type SingleResult,
44
42
  type SubagentDetails,
45
- type SubagentLiveEvent,
46
43
  } from "../execution/spawn.ts";
47
44
  import {
48
45
  isWorktreeCapableAgent,
49
- persistThreadCheckpoint,
50
46
  projectResultsRoot,
51
- type DispatchEnvironment,
52
47
  } from "../lifecycle/thread-shared.ts";
53
48
  import type { IsolationMode } from "../isolation/worktree.ts";
54
49
 
@@ -57,17 +52,17 @@ const NON_BLANK_TASK_OPTIONS = { minLength: 1, pattern: "\\S" } as const;
57
52
  const ISOLATION_DESCRIPTION =
58
53
  "Git isolation (not a sandbox): shared uses the caller's checkout; worktree creates a detached temporary worktree for write-capable agents only.";
59
54
 
60
- const IsolationSchema = Type.Optional(
55
+ export const IsolationSchema = Type.Optional(
61
56
  StringEnum(["shared", "worktree"] as const, { description: ISOLATION_DESCRIPTION }),
62
57
  );
63
58
 
64
- const PhaseIdSchema = Type.Optional(Type.String({
59
+ export const PhaseIdSchema = Type.Optional(Type.String({
65
60
  minLength: 1,
66
61
  maxLength: PHASE_ID_MAX_LENGTH,
67
62
  pattern: PHASE_ID_PATTERN_SOURCE,
68
63
  description: "Stable logical phase id. Reuse it when rewording the same phase; exact task+cwd is the fallback when omitted.",
69
64
  }));
70
- const ScopeSchema = Type.Optional(Type.Object({
65
+ export const ScopeSchema = Type.Optional(Type.Object({
71
66
  paths: Type.Optional(Type.Array(Type.String({
72
67
  ...NON_BLANK_TASK_OPTIONS,
73
68
  description: "Exact file or directory write claim resolved from the caller-facing cwd; wildcard * and ? are rejected, while other punctuation is literal.",
@@ -339,98 +334,12 @@ async function awaitRunResults(
339
334
  }
340
335
  }
341
336
 
342
- export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime): void {
343
- // Each dispatch refreshes the context, config, and agent catalog.
344
- const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
345
-
346
- // Terminal rows stay in the monitor until the next beginTurn so the footer
347
- // can count them beside siblings that are still live. The widget ignores
348
- // them. Repeated publication of the same settlement is a no-op.
349
- const publishedEndedAt = new Map<number, number>();
350
- const finishRun = (
351
- runId: number,
352
- status: "done" | "failed",
353
- opts?: { silent?: boolean },
354
- ): void => {
355
- const run = monitor.findRun(runId);
356
- if (!run) return;
357
- monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
358
- const endedAt = monitor.findRun(runId)?.endedAt;
359
- if (endedAt !== undefined && publishedEndedAt.get(runId) === endedAt) return;
360
- if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
361
- if (opts?.silent || !runtime.sessionActive) return;
362
- const icon = status === "done" ? "✓" : "✗";
363
- const result = runtime.threads.get(runId)?.lastResult;
364
- const error = status === "failed" ? result ? getResultError(result) : "No failure reason was recorded." : undefined;
365
- environmentRef.current?.ctx.ui.notify(
366
- `${icon} #${run.id} ${monitor.summarize(run)}${error ? ` · ${formatTaskSummary(error, 300, false)}` : ""}`,
367
- status === "done" ? "info" : "error",
368
- );
369
- };
370
-
371
- // Live sub-agent activity → concise one-line status ("thinking",
372
- // "read src/index.ts", ...), never a raw args blob. The live handler
373
- // only updates monitor state; the queue task owns terminal removal,
374
- // notification, and lifecycle decisions.
375
- const makeLiveHandler = (runId: number, generation?: number) => {
376
- // Every child turn reports "running"; the manifest is rewritten only when
377
- // what it records for recovery (session path, child pids) actually changed.
378
- let checkpointKey: string | undefined;
379
- return (e: SubagentLiveEvent): void => {
380
- if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
381
- switch (e.kind) {
382
- case "status":
383
- monitor.setStatus(runId, e.status);
384
- // A fresh running segment refreshes the durable checkpoint (session
385
- // path plus child pids) so a crash mid-generation still restores.
386
- if (e.status === "running") {
387
- const thread = runtime.threads.get(runId);
388
- if (thread?.sessionId && thread.sessionDir) {
389
- const key = `${thread.sessionDir}\0${thread.control.getChildPids().join(",")}`;
390
- if (key !== checkpointKey) {
391
- checkpointKey = key;
392
- persistThreadCheckpoint(runtime, thread, "parked");
393
- }
394
- }
395
- }
396
- break;
397
- case "model":
398
- monitor.setModel(runId, e.model, e.fallbackFrom);
399
- monitor.setThinking(runId, e.thinking);
400
- break;
401
- case "usage":
402
- monitor.setUsage(runId, e.usage, e.model);
403
- break;
404
- case "session": {
405
- runtime.retainSession({ sessionDir: e.sessionDir });
406
- const thread = runtime.threads.get(runId);
407
- if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
408
- thread.sessionId = e.sessionId;
409
- thread.sessionDir = e.sessionDir;
410
- persistThreadCheckpoint(runtime, thread, "parked");
411
- }
412
- break;
413
- }
414
- case "tool_start":
415
- monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
416
- break;
417
- case "tool_end":
418
- monitor.recordToolEnd(runId, e.toolName, e.isError);
419
- break;
420
- case "thinking":
421
- monitor.setActivity(runId, "thinking");
422
- break;
423
- case "text":
424
- // A text delta is model output, not a filesystem write.
425
- monitor.setActivity(runId, "responding");
426
- break;
427
- }
428
- };
429
- };
430
-
431
- const makeDetails =
432
- (mode: "single" | "parallel", background = false) =>
433
- (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
337
+ export function registerSubagentTool(
338
+ pi: ExtensionAPI,
339
+ runtime: SubagentRuntime,
340
+ core: DispatchCore = createDispatchCore(runtime),
341
+ ): void {
342
+ const { startBackground, makeDetails } = core;
434
343
 
435
344
  const phaseLeaseReceipt = (
436
345
  runIds: number[],
@@ -472,19 +381,6 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
472
381
  return ` Pacing: ${parts.join(" · ")}.`;
473
382
  };
474
383
 
475
- const startBackground = createBackgroundDispatcher({
476
- runtime,
477
- getEnvironment: () => {
478
- if (!environmentRef.current) {
479
- throw new Error("pi-subagents dispatch environment is not ready yet.");
480
- }
481
- return environmentRef.current;
482
- },
483
- finishRun,
484
- makeLiveHandler,
485
- makeDetails,
486
- });
487
-
488
384
  pi.registerTool({
489
385
  name: "subagent",
490
386
  label: "Subagent",
@@ -519,7 +415,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
519
415
  // One admission snapshot: role boundaries and writer capability must
520
416
  // describe the same catalog the batch is validated against.
521
417
  const toolInfos = runtime.getToolInfos();
522
- environmentRef.current = { ctx, config, agents };
418
+ core.setEnvironment({ ctx, config, agents });
523
419
 
524
420
  const hasTasks = (params.tasks?.length ?? 0) > 0;
525
421
  const hasSingle = Boolean(params.agent) && params.task !== undefined;