@ferris1225/pi-subagents 5.0.6 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +187 -97
  3. package/index.ts +1 -1
  4. package/package.json +4 -9
  5. package/src/configuration/role-migration.ts +2 -2
  6. package/src/configuration/setup.ts +4 -2
  7. package/src/configuration/ui.ts +144 -132
  8. package/src/delegation/agents.ts +15 -22
  9. package/src/delegation/dispatch.ts +17 -122
  10. package/src/delegation/prompt.ts +13 -12
  11. package/src/execution/cli-run.ts +112 -39
  12. package/src/execution/process-tree.ts +12 -8
  13. package/src/execution/run-control.ts +11 -3
  14. package/src/execution/spawn.ts +24 -7
  15. package/src/isolation/cleanup.ts +31 -12
  16. package/src/isolation/managed-paths.ts +6 -4
  17. package/src/isolation/manifest-mutation.ts +89 -0
  18. package/src/isolation/recovery.ts +33 -29
  19. package/src/isolation/temp-hygiene.ts +1 -1
  20. package/src/lifecycle/await-results.ts +114 -0
  21. package/src/lifecycle/dispatch-core.ts +7 -1
  22. package/src/lifecycle/durable.ts +83 -39
  23. package/src/lifecycle/runtime.ts +12 -4
  24. package/src/lifecycle/stop.ts +2 -2
  25. package/src/lifecycle/thread-lifecycle.ts +10 -5
  26. package/src/lifecycle/thread-restore.ts +26 -25
  27. package/src/lifecycle/thread-shared.ts +15 -3
  28. package/src/lifecycle/tools.ts +90 -33
  29. package/src/presentation/announcements.ts +8 -2
  30. package/src/presentation/monitor.ts +5 -3
  31. package/src/presentation/widget.ts +157 -113
  32. package/src/workflow/acceptance.ts +67 -0
  33. package/src/workflow/durable.ts +34 -14
  34. package/src/workflow/engine.ts +161 -51
  35. package/src/workflow/plan.ts +25 -4
  36. package/src/workflow/state.ts +6 -0
  37. package/src/workflow/templates.ts +156 -0
  38. package/src/workflow/tool.ts +65 -109
  39. package/skills/workflow/SKILL.md +0 -268
  40. package/src/workflow/files.ts +0 -236
  41. package/workflows/code-review.md +0 -38
  42. package/workflows/migration.md +0 -42
  43. package/workflows/research.md +0 -48
@@ -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.
@@ -1,236 +0,0 @@
1
- /**
2
- * Workflow definition discovery.
3
- *
4
- * A graph can be declared inline in the tool call or saved as a file so it can
5
- * be reviewed, versioned, and re-run. Files are read from three scopes with the
6
- * same override rule as agents — builtin < user < project, where the same name
7
- * wins at the higher scope:
8
- *
9
- * builtin : <package>/workflows (shipped templates)
10
- * user : <agentDir>/workflows (~/.pi/agent/workflows)
11
- * project : <cwd...>/.pi/workflows (nearest, walking up)
12
- *
13
- * Two file shapes are accepted: a JSON document, and Markdown with a `json`
14
- * fenced block holding the plan (so a template can explain itself in prose and
15
- * keep the graph machine-readable).
16
- */
17
-
18
- import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from "node:fs";
19
- import { chmod, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
20
- import { basename, dirname, join, resolve } from "node:path";
21
- import { fileURLToPath } from "node:url";
22
- import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
23
- import { migrateStoredAgentName, migrateStoredWorkflowRoles } from "../configuration/role-migration.ts";
24
- import type { WorkflowPlanInput } from "./plan.ts";
25
-
26
- /** Which workflow directories discovery reads. Same precedence as the templates
27
- * they ship with: project > user > built-in for the same name. */
28
- export type WorkflowScope = "user" | "project" | "both";
29
-
30
- export type WorkflowSource = "builtin" | "user" | "project";
31
-
32
- export interface WorkflowDefinition {
33
- name: string;
34
- description?: string;
35
- plan: WorkflowPlanInput;
36
- filePath: string;
37
- source: WorkflowSource;
38
- }
39
-
40
- const here = dirname(fileURLToPath(import.meta.url));
41
- /** <package>/workflows — templates shipped with this extension. */
42
- export const BUILTIN_WORKFLOWS_DIR = join(here, "..", "..", "workflows");
43
-
44
- function isDirectory(path: string): boolean {
45
- try {
46
- return statSync(path).isDirectory();
47
- } catch {
48
- return false;
49
- }
50
- }
51
-
52
- function findNearestProjectWorkflowsDir(cwd: string): string | null {
53
- let current = cwd;
54
- while (true) {
55
- const candidate = join(current, CONFIG_DIR_NAME, "workflows");
56
- if (isDirectory(candidate)) return candidate;
57
- const parent = dirname(current);
58
- if (parent === current) return null;
59
- current = parent;
60
- }
61
- }
62
-
63
- /** Accept either the full plan object or a bare node array. */
64
- function asPlan(value: unknown, fallbackName: string): WorkflowPlanInput | undefined {
65
- const raw = Array.isArray(value) ? { nodes: value } : value;
66
- if (!raw || typeof raw !== "object") return undefined;
67
- const record = raw as Record<string, unknown>;
68
- if (!Array.isArray(record.nodes)) return undefined;
69
- return {
70
- name: typeof record.name === "string" && record.name.trim() ? record.name.trim() : fallbackName,
71
- ...(typeof record.description === "string" && record.description.trim()
72
- ? { description: record.description.trim() }
73
- : {}),
74
- // The compiler validates every field; never sanitize away dependencies.
75
- nodes: record.nodes as WorkflowPlanInput["nodes"],
76
- };
77
- }
78
-
79
- const JSON_FENCE = /^[ \t]*```json[ \t]*\r?\n([\s\S]*?)^[ \t]*```/mu;
80
-
81
- function fencedJson(body: string): string | undefined {
82
- return JSON_FENCE.exec(body)?.[1];
83
- }
84
-
85
- /** Read one definition file. Returns an error string instead of throwing so a
86
- * broken file in a shared directory cannot hide the rest of the catalog. */
87
- export function readWorkflowFile(
88
- filePath: string,
89
- source: WorkflowSource,
90
- ): { definition?: WorkflowDefinition; error?: string } {
91
- const fallbackName = basename(filePath).replace(/\.(json|md)$/iu, "");
92
- let content: string;
93
- try {
94
- content = readFileSync(filePath, "utf8");
95
- } catch (error) {
96
- return { error: `${filePath}: ${error instanceof Error ? error.message : String(error)}` };
97
- }
98
- if (/\.json$/iu.test(filePath)) {
99
- let parsed: unknown;
100
- try {
101
- parsed = JSON.parse(content);
102
- } catch (error) {
103
- return { error: `${filePath}: invalid JSON (${error instanceof Error ? error.message : String(error)})` };
104
- }
105
- const plan = asPlan(parsed, fallbackName);
106
- if (!plan) return { error: `${filePath}: expected { name?, description?, nodes: [{ id, agent, task, dependsOn? }] }.` };
107
- return { definition: { name: plan.name ?? fallbackName, ...(plan.description ? { description: plan.description } : {}), plan, filePath, source } };
108
- }
109
- const { frontmatter, body } = parseFrontmatter<Record<string, string>>(content);
110
- const json = fencedJson(body);
111
- if (json === undefined) return { error: `${filePath}: a Markdown workflow needs a \`\`\`json fenced block holding the plan.` };
112
- let parsed: unknown;
113
- try {
114
- parsed = JSON.parse(json);
115
- } catch (error) {
116
- return { error: `${filePath}: invalid JSON in the fenced block (${error instanceof Error ? error.message : String(error)})` };
117
- }
118
- const name = typeof frontmatter.name === "string" && frontmatter.name.trim() ? frontmatter.name.trim() : fallbackName;
119
- const plan = asPlan(parsed, name);
120
- if (!plan) return { error: `${filePath}: expected a plan object or a node array in the fenced block.` };
121
- const description = typeof frontmatter.description === "string" && frontmatter.description.trim()
122
- ? frontmatter.description.trim()
123
- : plan.description;
124
- return {
125
- definition: { name: plan.name ?? name, ...(description ? { description } : {}), plan, filePath, source },
126
- };
127
- }
128
-
129
- /** Migrate an already trusted, selected saved definition on disk. Discovery
130
- * stays read-only; inline input is never translated into a different role. */
131
- export async function migrateWorkflowDefinition(definition: WorkflowDefinition): Promise<WorkflowDefinition> {
132
- if (definition.source === "builtin" || !definition.plan.nodes.some((node) =>
133
- typeof node?.agent === "string" && migrateStoredAgentName(node.agent.trim()) !== node.agent.trim(),
134
- )) return definition;
135
-
136
- return withFileMutationQueue(definition.filePath, async () => {
137
- const content = await readFile(definition.filePath, "utf8");
138
- const isJson = /\.json$/iu.test(definition.filePath);
139
- // parseFrontmatter normalizes newlines and trims the body; retain the raw
140
- // prefix here so migration changes only the JSON block.
141
- const bodyOffset = /^\uFEFF?---[\s\S]*?\r?\n---[^\r\n]*(?:\r?\n|$)/u.exec(content)?.[0].length ?? 0;
142
- const body = content.slice(bodyOffset);
143
- const json = isJson ? content : fencedJson(body);
144
- if (json === undefined) throw new Error(`Cannot migrate workflow ${definition.filePath}: missing JSON block.`);
145
- const parsed: unknown = JSON.parse(json);
146
- if (migrateStoredWorkflowRoles(parsed)) {
147
- const newline = content.includes("\r\n") ? "\r\n" : "\n";
148
- const serialized = JSON.stringify(parsed, null, 2).replace(/\n/gu, newline) + newline;
149
- const nextBody = body.replace(JSON_FENCE, (block, source: string) => block.replace(source, () => serialized));
150
- const next = isJson ? serialized : content.slice(0, bodyOffset) + nextBody;
151
- const temporary = `${definition.filePath}.${process.pid}.${Date.now()}.tmp`;
152
- try {
153
- const { mode } = await stat(definition.filePath);
154
- await writeFile(temporary, next, { encoding: "utf8", mode });
155
- await chmod(temporary, mode);
156
- await rename(temporary, definition.filePath);
157
- } finally {
158
- await rm(temporary, { force: true }).catch(() => undefined);
159
- }
160
- }
161
- const current = readWorkflowFile(definition.filePath, definition.source);
162
- if (!current.definition) throw new Error(current.error ?? `Cannot read migrated workflow ${definition.filePath}.`);
163
- return current.definition;
164
- });
165
- }
166
-
167
- function loadDefinitionsFromDir(dir: string, source: WorkflowSource): WorkflowDefinition[] {
168
- if (!existsSync(dir)) return [];
169
- let entries: Dirent[];
170
- try {
171
- entries = readdirSync(dir, { withFileTypes: true });
172
- } catch {
173
- return [];
174
- }
175
- const definitions: WorkflowDefinition[] = [];
176
- for (const entry of entries) {
177
- if (!/\.(?:json|md)$/iu.test(entry.name)) continue;
178
- if (!entry.isFile() && !entry.isSymbolicLink()) continue;
179
- const { definition } = readWorkflowFile(join(dir, entry.name), source);
180
- if (definition) definitions.push(definition);
181
- }
182
- return definitions;
183
- }
184
-
185
- export interface DiscoverWorkflowsOptions {
186
- scope?: WorkflowScope;
187
- projectTrusted?: boolean;
188
- builtinDir?: string;
189
- }
190
-
191
- /**
192
- * Every workflow definition visible from `cwd`, merged with project > user >
193
- * builtin precedence for the same name and sorted by name.
194
- */
195
- export function discoverWorkflows(cwd: string, options: DiscoverWorkflowsOptions = {}): WorkflowDefinition[] {
196
- const scope = options.scope ?? "both";
197
- const projectDir = findNearestProjectWorkflowsDir(cwd);
198
- const builtin = loadDefinitionsFromDir(options.builtinDir ?? BUILTIN_WORKFLOWS_DIR, "builtin");
199
- const user = scope === "project" ? [] : loadDefinitionsFromDir(join(getAgentDir(), "workflows"), "user");
200
- const project =
201
- scope === "user" || !projectDir || options.projectTrusted !== true
202
- ? []
203
- : loadDefinitionsFromDir(projectDir, "project");
204
-
205
- const byName = new Map<string, WorkflowDefinition>();
206
- for (const definition of builtin) byName.set(definition.name, definition);
207
- for (const definition of user) byName.set(definition.name, definition);
208
- for (const definition of project) byName.set(definition.name, definition);
209
- return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));
210
- }
211
-
212
- /** Resolve a name or file path to a definition; error text names what is available. */
213
- export function resolveWorkflowDefinition(
214
- cwd: string,
215
- request: { name?: string; path?: string },
216
- options: DiscoverWorkflowsOptions = {},
217
- ): { definition?: WorkflowDefinition; error?: string } {
218
- if (request.name?.trim() && request.path?.trim()) return { error: "provide a workflow name or file path, not both." };
219
- if (request.path) {
220
- if (options.projectTrusted !== true) return { error: "workflow files require a trusted project." };
221
- const filePath = resolve(cwd, request.path);
222
- if (!existsSync(filePath)) return { error: `workflow file not found: ${filePath}` };
223
- const read = readWorkflowFile(filePath, "project");
224
- if (read.error) return { error: read.error };
225
- return read;
226
- }
227
- const name = request.name?.trim();
228
- if (!name) return { error: "provide either inline nodes, a workflow name, or a workflow file path." };
229
- const available = discoverWorkflows(cwd, options);
230
- const match = available.find((definition) => definition.name.toLowerCase() === name.toLowerCase());
231
- if (!match) {
232
- const names = available.map((definition) => definition.name).join(", ");
233
- return { error: `no workflow named "${name}". Available: ${names || "none"}. Save one under .pi/workflows/ or ~/.pi/agent/workflows/.` };
234
- }
235
- return { definition: match };
236
- }
@@ -1,38 +0,0 @@
1
- ---
2
- name: code-review
3
- description: Inspect an implementation, then challenge only the reported findings.
4
- ---
5
-
6
- # Code review workflow
7
-
8
- Use one `sentinel` run for an ordinary review. This two-node template is for a
9
- substantial change where independent verification of findings earns another
10
- session. The sentinel inspects the implementation; the skeptic checks its named
11
- claims and returns the final review. They do not perform two general reviews.
12
-
13
- Copy this file to `.pi/workflows/code-review.md` and replace `<TARGET>` with the
14
- branch, commit range, or paths under review. Include any existing main research
15
- and checks in the review brief so the sentinel can reuse them. If the first
16
- result must decide whether a second phase is needed, dispatch only the sentinel
17
- and make that decision in main.
18
-
19
- Run with `subagent_workflow({ workflow: "code-review" })`, or use an explicit
20
- `file` path. Omit isolation overrides for these read-only reviews.
21
-
22
- ```json
23
- {
24
- "nodes": [
25
- {
26
- "id": "review",
27
- "agent": "sentinel",
28
- "task": "Review <TARGET> against the stated requirements and relevant callers. Establish the diff once, then inspect correctness, regressions, compatibility, and concrete failure paths within that target. Reuse existing research and valid checks; run a focused reproduction only to resolve a suspected defect. Stay read-only and do not change Git state. Return confirmed actionable findings with path:line, trigger, consequence, evidence, and smallest fix; include checks and material gaps. State clearly if no confirmed findings were found."
29
- },
30
- {
31
- "id": "verify",
32
- "agent": "skeptic",
33
- "dependsOn": ["review"],
34
- "task": "Test only the specific defect claims reported here:\n\n{{review}}\n\nTry to disprove each claim against its callers, invariants, or focused checks. Reuse valid evidence; do not repeat the general review. If there are no defect claims, report that and stop. Stay read-only and do not change Git state. Return the final review: surviving confirmed findings ordered by severity with trigger, consequence, evidence, and smallest fix; briefly state refuted or unresolved claims, checks, and remaining limits."
35
- }
36
- ]
37
- }
38
- ```
@@ -1,42 +0,0 @@
1
- ---
2
- name: migration
3
- description: Apply two already planned migration slices, then challenge the integrated result with the project gate.
4
- ---
5
-
6
- # Migration workflow
7
-
8
- Use this template after main has established the target, interface contract,
9
- and disjoint writer scopes. If discovery determines those boundaries, run that
10
- discovery first and decide in main; a static graph cannot rewrite its own nodes.
11
- Replace <TARGET>, <CONTRACT> (the shared interface contract or its file path),
12
- both slice briefs, and every example scope before running. Each child needs the
13
- contract in its own brief because it cannot see main's conversation.
14
- Each slice owns its implementation and regression tests. Keep coupled changes
15
- with one owner. Use sentinel for a separate implementation review or skeptic
16
- for a named assumption the gate cannot test; main owns final integration and release.
17
-
18
- ```json
19
- {
20
- "nodes": [
21
- {
22
- "id": "apply-core",
23
- "agent": "artisan",
24
- "task": "Migrate the core slice to <TARGET>. <CORE_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence rather than inventing a new scope.",
25
- "scope": { "paths": ["src/core", "test/core"] }
26
- },
27
- {
28
- "id": "apply-adapters",
29
- "agent": "artisan",
30
- "task": "Migrate the adapter slice to <TARGET>. <ADAPTER_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence rather than inventing a new scope.",
31
- "scope": { "paths": ["src/adapters", "test/adapters"] }
32
- },
33
- {
34
- "id": "gate",
35
- "agent": "artisan",
36
- "task": "Challenge the integrated migration using the project's documented required checks. Interface contract: <CONTRACT>. Verify both slices meet their done conditions before proceeding; report missing prerequisites instead of guessing. Run the required commands; inspect cross-slice call sites for mismatches. Fix failures caused by this migration within its authorized scope. Report commands, results, and unverified risks.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
37
- "dependsOn": ["apply-core", "apply-adapters"],
38
- "scope": { "paths": ["src/core", "test/core", "src/adapters", "test/adapters"] }
39
- }
40
- ]
41
- }
42
- ```
@@ -1,48 +0,0 @@
1
- ---
2
- name: research
3
- description: Research a question from independent angles, synthesise the answer, then verify its factual claims.
4
- ---
5
-
6
- # Research workflow
7
-
8
- Three researchers take different angles, a synthesis node turns them into one
9
- answer, and a verification node checks the claims that would embarrass you if
10
- they were wrong. This template deliberately separates synthesis from challenge;
11
- combine them for a bounded question when main can verify the decisive sources.
12
-
13
- Replace every <QUESTION> in a copy of this file (the first three nodes run concurrently), then
14
- run `subagent_workflow({ "workflow": "research" })`.
15
-
16
- ```json
17
- {
18
- "nodes": [
19
- {
20
- "id": "primary",
21
- "agent": "scout",
22
- "task": "Research <QUESTION> from first-party sources only: official documentation, specifications, release notes, and the project's own repository. Record versions and dates. Cite every fact you state. Mark anything you could only find second-hand."
23
- },
24
- {
25
- "id": "practice",
26
- "agent": "scout",
27
- "task": "Research <QUESTION> from practice: issue threads, migration notes, benchmarks, and post-mortems that describe what actually happened when people used it. Separate reported experience from vendor claims and cite each source."
28
- },
29
- {
30
- "id": "codebase",
31
- "agent": "scout",
32
- "task": "Establish what this repository already does about <QUESTION>: the relevant modules, configuration, and tests, with path:line citations. State where the code disagrees with the documentation if you find such a place."
33
- },
34
- {
35
- "id": "synthesis",
36
- "agent": "scout",
37
- "task": "Answer <QUESTION> from these three research passes. Reconcile disagreements explicitly instead of averaging them, and check dates, versions, and conditions when official claims conflict with observed practice; prefer the evidence that applies to this question.\n\nFirst-party:\n{{primary}}\n\nPractice:\n{{practice}}\n\nThis repository:\n{{codebase}}\n\nWrite: the answer, the evidence behind it, the open questions, and what would change the answer.",
38
- "dependsOn": ["primary", "practice", "codebase"]
39
- },
40
- {
41
- "id": "verify",
42
- "agent": "scout",
43
- "task": "Try to disprove the decisive claims in this answer: read the cited sources, seek counterexamples and conflicting versions, and distinguish factual mistakes from uncertainty. Return the corrected answer with citations, a concise list of changes, and claims that remain unverified. Do not claim execution-based reproduction; this role is read-only.\n\n{{synthesis}}",
44
- "dependsOn": ["synthesis"]
45
- }
46
- ]
47
- }
48
- ```