@ferris1225/pi-subagents 4.3.32 → 4.3.33

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,32 @@
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.33
7
+
8
+ - Add `subagent_workflow`: declare a graph of phases with `dependsOn` and the
9
+ runtime dispatches each node the moment its prerequisites settle and a process
10
+ slot frees, without a parent model turn between waves. The graph is validated
11
+ before the first child starts (unique ids, existing dependencies, no cycles,
12
+ resolvable `{{id}}` placeholders, no declared writer-scope overlap between
13
+ nodes no dependency orders), so an invalid plan costs zero child processes.
14
+ - Nodes are ordinary one-shot runs: same dispatcher, admission, isolation,
15
+ durable checkpointing, and usage accounting. A node's result registers only
16
+ after its worktree is integrated, so a dependent reads what its prerequisite
17
+ actually left behind.
18
+ - A node completion is quiet; the graph reports once. The summary names
19
+ completed, failed, and never-ran nodes with the reason, inlines each node's
20
+ answer (clipped, with a full-report artifact when anything was cut), and adds a
21
+ per-model tally. A failed node blocks only its dependents.
22
+ - Saved definitions: `.pi/workflows/<name>.json` or `.md` in a trusted project,
23
+ `~/.pi/agent/workflows/` for the user, and `code-review`, `research`, and
24
+ `migration` templates shipped with the package. Markdown definitions carry
25
+ prose plus one `json` fenced block.
26
+ - `subagent_status` accepts `workflow` and reports graph nodes, wait reasons, and
27
+ retained graphs; `subagent_stop` accepts `workflow` and stops a graph without
28
+ starting its idle dependents. An unfinished graph's shape is retained on disk
29
+ for the next session's notice instead of resuming automatically.
30
+ - Ship a `workflow` skill with the authoring guidance, and describe the graph
31
+ tool in the delegation contract.
6
32
  ## 4.3.32
7
33
 
8
34
  - Derive a role's tools from the live catalog instead of a hardcoded name list.
package/README.md CHANGED
@@ -13,6 +13,13 @@ self-contained — parallel phases usually beat a serialized main.
13
13
 
14
14
  ## What's new
15
15
 
16
+ **4.3.33** — dependency graphs for multi-phase work. `subagent_workflow` declares
17
+ nodes with `dependsOn`, validates the graph before any child starts, dispatches
18
+ each node as its prerequisites settle, and reports the whole graph once. Saved
19
+ definitions live in `.pi/workflows/` or `~/.pi/agent/workflows/`, three templates
20
+ ship with the package, and a `workflow` skill carries the authoring guidance.
21
+ `subagent_status` and `subagent_stop` accept a graph id.
22
+
16
23
  **4.3.32** — codemode-aware, tool-agnostic role policy and a minimal config.
17
24
  `scout` keeps every active tool the host proves read-only and can never keep a
18
25
  tool that reaches other tools, such as `codemode`, while `artisan` inherits the
@@ -31,6 +38,7 @@ is preserved as a GitHub Release.
31
38
  - [Install](#install)
32
39
  - [The team](#the-team)
33
40
  - [Dispatching work](#dispatching-work)
41
+ - [Workflows](#workflows)
34
42
  - [Parallel edits](#parallel-edits)
35
43
  - [Runs: status and stop](#runs-status-and-stop)
36
44
  - [Live status and results](#live-status-and-results)
@@ -196,6 +204,80 @@ These defaults follow [OpenAI's GPT-6 Astra model guidance](https://developers.o
196
204
  and [Eric Provencher's skills and prompts guidance](https://x.com/pvncher/status/2095991462416490862).
197
205
  They simplify instructions without changing the configured models or thinking levels.
198
206
 
207
+ ## Workflows
208
+
209
+ A request sometimes has phases whose order is known before the work starts:
210
+ establish the facts, change independent slices at the same time, then run one
211
+ gate. `subagent_workflow` declares that graph once. The runtime starts each node
212
+ the moment its prerequisites settle and a process slot frees, so no parent model
213
+ turn sits between waves, and it wakes the main agent once with a summary of the
214
+ whole graph.
215
+
216
+ ```ts
217
+ subagent_workflow({
218
+ name: "auth-fix",
219
+ description: "Map the refresh race, fix it, gate it.",
220
+ nodes: [
221
+ { id: "map", agent: "scout", task: "Map the refresh race in src/auth. Cite path:line." },
222
+ { id: "fix", agent: "artisan", task: "Fix it. Evidence:\n{{map}}", dependsOn: ["map"],
223
+ scope: { paths: ["src/auth"] } },
224
+ { id: "tests", agent: "artisan", task: "Add regression tests. Evidence:\n{{map}}",
225
+ dependsOn: ["map"], scope: { paths: ["test/auth.test.ts"] } },
226
+ { id: "gate", agent: "artisan", task: "Run the checks.\nFix:\n{{fix}}\nTests:\n{{tests}}",
227
+ dependsOn: ["fix", "tests"] },
228
+ ],
229
+ });
230
+ ```
231
+
232
+ - `{{id}}` interpolates that node's final answer into a dependent's brief;
233
+ `{{id.status}}`, `{{id.runId}}`, and `{{id.error}}` interpolate facts. A
234
+ placeholder may only name a node the current one waits for, directly or through
235
+ its chain; anything else is rejected at compile time.
236
+ - The graph is validated before the first child starts: unique ids, existing
237
+ dependencies, no cycles, resolvable placeholders, and no declared writer-scope
238
+ overlap between nodes that no dependency orders.
239
+ - Nodes are ordinary one-shot runs: same admission, isolation, durable
240
+ checkpoints, and usage accounting as a `subagent` call. A node's result is
241
+ registered only after its worktree is integrated, so a dependent reads what its
242
+ prerequisite actually left behind.
243
+ - Failure is contained by the graph. A failed node blocks only its dependents,
244
+ independent branches keep running, and the summary names completed, failed, and
245
+ never-ran nodes with the reason. Nodes never retry: main finishes incomplete work
246
+ from the retained evidence.
247
+ - A workflow reports once. Node completions are quiet, and the single summary
248
+ carries each node's answer (clipped, with a full-report file when anything was
249
+ cut) plus a per-model tally.
250
+ - Write-capable nodes in a graph default to a detached worktree, which needs a
251
+ committed `HEAD`; pass `"isolation": "shared"` on a node to keep it in your
252
+ checkout and serialize it on the repository write lane.
253
+
254
+ Saved definitions run by name and can be reviewed before they run:
255
+
256
+ - Project: `.pi/workflows/<name>.json` or `.pi/workflows/<name>.md` (trusted projects only)
257
+ - User: `~/.pi/agent/workflows/`
258
+ - Shipped: the `code-review`, `research`, and `migration` templates in this package
259
+ - Precedence: project > user > built-in, where the same `name` wins
260
+
261
+ ```ts
262
+ subagent_workflow({ workflow: "code-review" });
263
+ subagent_workflow({ file: ".pi/workflows/code-review.md" });
264
+ ```
265
+
266
+ A Markdown definition carries prose plus one `json` fenced block holding the plan
267
+ object or a bare node array. The package also ships a `workflow` skill
268
+ (`skills/workflow/SKILL.md`) with the authoring guidance: when a graph is worth
269
+ its cost, how to slice phases, how to write briefs, and the anti-patterns.
270
+
271
+ Derived phase ids are `<workflow-slug>.<node-id>`, and a settled phase stays owned
272
+ for the parent session, so the same graph with identical briefs is rejected as a
273
+ duplicate. Re-run it in a new session, or change what the phases target.
274
+
275
+ `subagent_status({ workflow: id })` reports nodes and their wait reasons;
276
+ `subagent_stop({ workflow: id })` stops a graph without starting its idle
277
+ dependents. An unfinished graph keeps its shape on disk, so the next session's
278
+ start notice and `subagent_status` report which nodes completed and which were
279
+ still running.
280
+
199
281
  ## Parallel edits
200
282
 
201
283
  `scope` is declarative admission metadata for expected writes, not access control. `paths`
@@ -256,8 +338,9 @@ deliverable needs a new phase and brief, not a recycled thread.
256
338
 
257
339
  | Tool | What it does |
258
340
  | ---- | ------------ |
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. |
341
+ | `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. |
342
+ | `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. |
343
+ | `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
344
 
262
345
  ```ts
263
346
  subagent_status({});
@@ -481,6 +564,7 @@ that removes it, so this directory does not grow without bound:
481
564
  | `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
565
  | `ferris-pi-subagents/<project>/worktrees/` | Isolated checkouts for parallel writers | On integration, or when no thread/recovery record claims them |
483
566
  | `ferris-pi-subagents/<project>/results/` | Full text of truncated results | After 7 days, or beyond 50 per project |
567
+ | `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
568
  | `ferris-pi-subagents/<project>/tmp/` | Child prompt copies and the no-retry policy shim | When its owning process exits |
485
569
  | `ferris-pi-subagents/<project>/` | All of the above for one checkout | After 3 idle days unless a thread/recovery record claims it |
486
570
 
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.33",
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,226 @@
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
+ **Re-running a graph in the same session is a duplicate phase.** Derived phase
176
+ ids are `<workflow-slug>.<node-id>`, and a settled phase stays owned for the
177
+ session. To run the same shape on new work, either start a new session or vary
178
+ the briefs (a new commit, a new target) so the phases are genuinely different.
179
+
180
+ ## 9. Cost
181
+
182
+ Every node is a full model session with its own context, and the summary carries
183
+ each node's answer. Budget accordingly:
184
+
185
+ - Prefer the fewest nodes that still give each phase one owner and each claim one
186
+ confirmer.
187
+ - Keep node answers short: conclusions, paths, `command → result`.
188
+ - Do not add a node to fill a free process slot, and do not split one tightly
189
+ coupled change across nodes.
190
+
191
+ ## 10. Anti-patterns
192
+
193
+ | What you wrote | What it costs |
194
+ | --- | --- |
195
+ | A graph for a task with no real ordering | A model turn saved, two sessions wasted |
196
+ | A node whose brief re-derives what a scout already established | Paying twice for the same reading |
197
+ | `{{sibling}}` from a node that does not wait for it | Compile error; add the dependency or join first |
198
+ | Two writers with overlapping `scope` and no edge between them | The whole graph is rejected before any node starts |
199
+ | A reviewer asked "is this good?" | It approves; ask what would break it |
200
+ | A gate node asked to judge quality instead of running the tests | An opinion where an exit code would have decided |
201
+ | Retrying a failed node inside another node | Duplicate phase; main finishes the work instead |
202
+ | Twenty nodes over one small change | Twenty contexts, one deliverable |
203
+ | Reporting unverified findings as facts | The summary cannot tell "seen" from "suspected" |
204
+
205
+ ## 11. Reading the summary
206
+
207
+ One completion message per graph:
208
+
209
+ ```text
210
+ ### workflow auth-fix completed (4/4 completed)
211
+ - map (scout) completed · run #12 · 1m02s
212
+ - fix (artisan) completed · run #13 · 4m11s
213
+ - tests (artisan) completed · run #15 · 2m40s
214
+ - gate (artisan) completed · run #16 · 6m05s
215
+
216
+ Node answers:
217
+ #### map
218
+ …
219
+ Totals: 4 nodes · anthropic/claude-sonnet-4: ↓48.0k $0.8200
220
+ ```
221
+
222
+ - Node answers are clipped here; the full report file is named when that happens.
223
+ - `failed` / `never ran (blocked)` lines say why, and each run keeps its own
224
+ retained artifacts.
225
+ - Main then does what children cannot: inspect the integrated diff, run the gate
226
+ 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;
@@ -162,6 +162,7 @@ function delegationBody(agents: AgentConfig[]): string {
162
162
  ...(preferred ? [preferred] : []),
163
163
  "Children inherit this session's live tool surface: a role without an allowlist gets everything you have, including `codemode`, and a read-only role keeps only the tools the host proves read-only. Do not plan a phase that needs a tool its role cannot reach.",
164
164
  "Give each phase one owner, a stable `phaseId`, and exact writer `scope`. Parallelize independent phases in one call; never overlap writers or duplicate an owned phase. Dependent phases wait for prerequisites. Scope is conflict metadata, not permissions or a sandbox.",
165
+ "When the request is one deliverable spanning ordered phases (survey, then independent changes, then a single gate), declare the graph once with `subagent_workflow` instead of dispatching wave after wave: the runtime starts each node the moment its prerequisites settle and sends one summary when the graph does. Saved graphs under `.pi/workflows/` run by name.",
165
166
  "Children have no parent conversation; send a self-contained brief and reuse established evidence.",
166
167
  "One-shot runs return once. Main takes over failed or incomplete work from partial edits and artifacts; a different deliverable needs a new phase.",
167
168
  "Use `wait: true` for an immediate dependency or one-shot session; otherwise continue disjoint work and end your turn when none remains — completions arrive automatically and wake you; do not poll or sleep to wait. Conclude the overall task only after every run settles or is stopped.",