@pi-agents/orchid 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE +21 -0
  3. package/README.md +246 -0
  4. package/agents/AGENTS-MANIFEST.md +42 -0
  5. package/agents/brain.md +42 -0
  6. package/agents/context-builder.md +46 -0
  7. package/agents/delegate.md +12 -0
  8. package/agents/dev-1.md +42 -0
  9. package/agents/oracle.md +73 -0
  10. package/agents/planner.md +55 -0
  11. package/agents/researcher.md +52 -0
  12. package/agents/reviewer.md +79 -0
  13. package/agents/scout.md +50 -0
  14. package/agents/tester.md +45 -0
  15. package/agents/worker.md +55 -0
  16. package/extensions/ralph.ts +1 -0
  17. package/extensions/reviewer-extension.ts +125 -0
  18. package/extensions/task-orchestrator.ts +28 -0
  19. package/package.json +63 -0
  20. package/prompts/gather-context-and-clarify.md +13 -0
  21. package/prompts/parallel-cleanup.md +59 -0
  22. package/prompts/parallel-context-build.md +53 -0
  23. package/prompts/parallel-handoff-plan.md +59 -0
  24. package/prompts/parallel-research.md +50 -0
  25. package/prompts/parallel-review.md +54 -0
  26. package/prompts/review-loop.md +41 -0
  27. package/skills/orchid/SKILL.md +214 -0
  28. package/skills/orchid/orchid-cleanup/SKILL.md +122 -0
  29. package/skills/orchid/orchid-converge/SKILL.md +124 -0
  30. package/skills/orchid/orchid-decompose/SKILL.md +201 -0
  31. package/skills/orchid/orchid-doctor/SKILL.md +162 -0
  32. package/skills/orchid/orchid-investigate/SKILL.md +102 -0
  33. package/skills/orchid/orchid-launch/SKILL.md +147 -0
  34. package/skills/ralph/SKILL.md +73 -0
  35. package/skills/subagents/pi-subagents/SKILL.md +813 -0
  36. package/src/index.ts +7 -0
  37. package/src/orchestrator/abort.ts +534 -0
  38. package/src/orchestrator/agent-bridge-extension.ts +1020 -0
  39. package/src/orchestrator/agent-host.ts +954 -0
  40. package/src/orchestrator/cleanup.ts +776 -0
  41. package/src/orchestrator/config-loader.ts +1412 -0
  42. package/src/orchestrator/config-schema.ts +690 -0
  43. package/src/orchestrator/config.ts +81 -0
  44. package/src/orchestrator/context-window.ts +66 -0
  45. package/src/orchestrator/diagnostic-reports.ts +475 -0
  46. package/src/orchestrator/diagnostics.ts +394 -0
  47. package/src/orchestrator/discovery.ts +1833 -0
  48. package/src/orchestrator/engine-worker.ts +415 -0
  49. package/src/orchestrator/engine.ts +5940 -0
  50. package/src/orchestrator/execution.ts +3104 -0
  51. package/src/orchestrator/extension.ts +5934 -0
  52. package/src/orchestrator/formatting.ts +785 -0
  53. package/src/orchestrator/git.ts +88 -0
  54. package/src/orchestrator/index.ts +28 -0
  55. package/src/orchestrator/lane-runner.ts +1787 -0
  56. package/src/orchestrator/mailbox.ts +780 -0
  57. package/src/orchestrator/merge.ts +3414 -0
  58. package/src/orchestrator/messages.ts +1062 -0
  59. package/src/orchestrator/migrations.ts +278 -0
  60. package/src/orchestrator/naming.ts +117 -0
  61. package/src/orchestrator/path-resolver.ts +275 -0
  62. package/src/orchestrator/persistence.ts +2625 -0
  63. package/src/orchestrator/process-registry.ts +452 -0
  64. package/src/orchestrator/quality-gate.ts +1085 -0
  65. package/src/orchestrator/resume.ts +3488 -0
  66. package/src/orchestrator/sessions.ts +57 -0
  67. package/src/orchestrator/settings-loader.ts +136 -0
  68. package/src/orchestrator/settings-tui.ts +2208 -0
  69. package/src/orchestrator/sidecar-telemetry.ts +267 -0
  70. package/src/orchestrator/supervisor.ts +4548 -0
  71. package/src/orchestrator/task-executor-core.ts +675 -0
  72. package/src/orchestrator/tmux-compat.ts +37 -0
  73. package/src/orchestrator/tool-allowlist-constants.ts +37 -0
  74. package/src/orchestrator/types.ts +4465 -0
  75. package/src/orchestrator/verification.ts +547 -0
  76. package/src/orchestrator/waves.ts +1564 -0
  77. package/src/orchestrator/workspace.ts +707 -0
  78. package/src/orchestrator/worktree.ts +2725 -0
  79. package/src/ralph/index.ts +825 -0
  80. package/src/subagents/agents/agent-management.ts +648 -0
  81. package/src/subagents/agents/agent-scope.ts +6 -0
  82. package/src/subagents/agents/agent-selection.ts +23 -0
  83. package/src/subagents/agents/agent-serializer.ts +86 -0
  84. package/src/subagents/agents/agents.ts +832 -0
  85. package/src/subagents/agents/chain-serializer.ts +137 -0
  86. package/src/subagents/agents/frontmatter.ts +29 -0
  87. package/src/subagents/agents/identity.ts +30 -0
  88. package/src/subagents/agents/skills.ts +632 -0
  89. package/src/subagents/extension/config.ts +16 -0
  90. package/src/subagents/extension/control-notices.ts +92 -0
  91. package/src/subagents/extension/doctor.ts +199 -0
  92. package/src/subagents/extension/fanout-child.ts +170 -0
  93. package/src/subagents/extension/index.ts +573 -0
  94. package/src/subagents/extension/schemas.ts +168 -0
  95. package/src/subagents/intercom/intercom-bridge.ts +379 -0
  96. package/src/subagents/intercom/result-intercom.ts +377 -0
  97. package/src/subagents/runs/background/async-execution.ts +712 -0
  98. package/src/subagents/runs/background/async-job-tracker.ts +310 -0
  99. package/src/subagents/runs/background/async-resume.ts +345 -0
  100. package/src/subagents/runs/background/async-status.ts +325 -0
  101. package/src/subagents/runs/background/completion-dedupe.ts +63 -0
  102. package/src/subagents/runs/background/notify.ts +108 -0
  103. package/src/subagents/runs/background/parallel-groups.ts +45 -0
  104. package/src/subagents/runs/background/result-watcher.ts +307 -0
  105. package/src/subagents/runs/background/run-id-resolver.ts +83 -0
  106. package/src/subagents/runs/background/run-status.ts +269 -0
  107. package/src/subagents/runs/background/stale-run-reconciler.ts +336 -0
  108. package/src/subagents/runs/background/subagent-runner.ts +1808 -0
  109. package/src/subagents/runs/background/top-level-async.ts +13 -0
  110. package/src/subagents/runs/foreground/chain-clarify.ts +1333 -0
  111. package/src/subagents/runs/foreground/chain-execution.ts +938 -0
  112. package/src/subagents/runs/foreground/execution.ts +918 -0
  113. package/src/subagents/runs/foreground/subagent-executor.ts +2527 -0
  114. package/src/subagents/runs/shared/completion-guard.ts +147 -0
  115. package/src/subagents/runs/shared/long-running-guard.ts +175 -0
  116. package/src/subagents/runs/shared/mcp-direct-tool-allowlist.ts +365 -0
  117. package/src/subagents/runs/shared/model-fallback.ts +103 -0
  118. package/src/subagents/runs/shared/nested-events.ts +819 -0
  119. package/src/subagents/runs/shared/nested-path.ts +52 -0
  120. package/src/subagents/runs/shared/nested-render.ts +115 -0
  121. package/src/subagents/runs/shared/parallel-utils.ts +109 -0
  122. package/src/subagents/runs/shared/pi-args.ts +220 -0
  123. package/src/subagents/runs/shared/pi-spawn.ts +115 -0
  124. package/src/subagents/runs/shared/run-history.ts +60 -0
  125. package/src/subagents/runs/shared/single-output.ts +164 -0
  126. package/src/subagents/runs/shared/subagent-control.ts +226 -0
  127. package/src/subagents/runs/shared/subagent-prompt-runtime.ts +170 -0
  128. package/src/subagents/runs/shared/worktree.ts +577 -0
  129. package/src/subagents/shared/artifacts.ts +98 -0
  130. package/src/subagents/shared/atomic-json.ts +16 -0
  131. package/src/subagents/shared/file-coalescer.ts +40 -0
  132. package/src/subagents/shared/fork-context.ts +76 -0
  133. package/src/subagents/shared/formatters.ts +133 -0
  134. package/src/subagents/shared/jsonl-writer.ts +81 -0
  135. package/src/subagents/shared/model-info.ts +78 -0
  136. package/src/subagents/shared/post-exit-stdio-guard.ts +85 -0
  137. package/src/subagents/shared/session-identity.ts +10 -0
  138. package/src/subagents/shared/session-tokens.ts +44 -0
  139. package/src/subagents/shared/settings.ts +397 -0
  140. package/src/subagents/shared/status-format.ts +49 -0
  141. package/src/subagents/shared/types.ts +822 -0
  142. package/src/subagents/shared/utils.ts +450 -0
  143. package/src/subagents/slash/prompt-template-bridge.ts +397 -0
  144. package/src/subagents/slash/slash-bridge.ts +174 -0
  145. package/src/subagents/slash/slash-commands.ts +528 -0
  146. package/src/subagents/slash/slash-live-state.ts +292 -0
  147. package/src/subagents/tui/render-helpers.ts +80 -0
  148. package/src/subagents/tui/render.ts +1358 -0
  149. package/templates/agents/local/supervisor.md +33 -0
  150. package/templates/agents/local/task-merger.md +27 -0
  151. package/templates/agents/local/task-reviewer.md +30 -0
  152. package/templates/agents/local/task-worker.md +34 -0
  153. package/templates/agents/supervisor-routing.md +92 -0
  154. package/templates/agents/supervisor.md +229 -0
  155. package/templates/agents/task-merger.md +214 -0
  156. package/templates/agents/task-reviewer.md +260 -0
  157. package/templates/agents/task-worker-segment.md +44 -0
  158. package/templates/agents/task-worker.md +557 -0
  159. package/templates/tasks/CONTEXT.md +30 -0
  160. package/templates/tasks/EXAMPLE-001-hello-world/PROMPT.md +98 -0
  161. package/templates/tasks/EXAMPLE-001-hello-world/STATUS.md +73 -0
  162. package/templates/tasks/EXAMPLE-002-parallel-smoke/PROMPT.md +97 -0
  163. package/templates/tasks/EXAMPLE-002-parallel-smoke/STATUS.md +73 -0
@@ -0,0 +1,813 @@
1
+ ---
2
+ name: pi-subagents
3
+ description: |
4
+ Delegate work to builtin or custom subagents with single-agent, chain,
5
+ parallel, async, forked-context, and intercom-coordinated workflows. Use
6
+ for advisory review, implementation handoffs, and multi-step tasks where a
7
+ single agent should stay in control while other agents contribute context,
8
+ planning, or execution.
9
+ ---
10
+
11
+ # Pi Subagents
12
+
13
+ This skill is for the main parent orchestrator only. Do not inject or follow it inside spawned child subagents. The parent session owns delegation, orchestration, review fanout, and final fix-worker launches; child subagents should receive concrete role-specific tasks. Ordinary children should not run their own subagent workflows; the explicit exception is a delegated fanout child whose resolved builtin `tools` includes `subagent`, and that child may use `subagent` only for the fanout work the parent assigned.
14
+
15
+ Use this skill when the parent orchestrator needs to launch a specialized subagent, compose multiple agents into a workflow, or create/edit agents and chains on demand.
16
+
17
+ ## When to Use
18
+
19
+ - **Advisory review**: use fresh-context `reviewer` agents for adversarial code review, or fork to `oracle` when inherited decisions and drift matter
20
+ - **Implementation handoff**: have `oracle` advise, then `worker` implement only after an approved direction
21
+ - **Recon and planning**: use `scout` or `context-builder`, then `planner`
22
+ - **Parallel exploration**: run multiple non-conflicting tasks concurrently
23
+ - **Long-running work**: launch async/background runs and inspect them later
24
+ - **Subagent control**: watch needs-attention signals and soft-interrupt only when a delegated run is genuinely blocked
25
+ - **Agent authoring**: create, update, or override agents and chains for a project
26
+
27
+ ## Tool vs Slash Commands
28
+
29
+ Agents can use the `subagent(...)` tool directly for execution, management, status, and control.
30
+ Humans often use the slash-command layer instead:
31
+
32
+ - `/run` — launch a single agent
33
+ - `/chain` — launch a chain of steps
34
+ - `/parallel` — launch top-level parallel tasks
35
+ - `/run-chain` — launch a saved `.chain.md` workflow
36
+ - `/subagents-doctor` — diagnose setup, discovery, async paths, and intercom bridge state
37
+
38
+ Prefer the tool when you are writing agent logic. Prefer the slash commands when
39
+ you are guiding a human through an interactive flow.
40
+
41
+ Packaged prompt shortcuts are also available for repeatable workflows. Treat them as reusable orchestration recipes, not just human slash commands. When the user asks for one of these shapes, or when the workflow clearly fits, apply the same pattern directly with `subagent(...)` and other tools:
42
+ - `/parallel-review` — fresh-context reviewers with distinct review angles, then synthesis
43
+ - `/review-loop` — parent-orchestrated worker, fresh-reviewer, and fix-worker cycles until clean or capped
44
+ - `/parallel-research` — combine `researcher` and `scout` for external evidence plus local code context
45
+ - `/parallel-context-build` — parallel `context-builder` passes that produce planning handoff context and meta-prompts
46
+ - `/parallel-handoff-plan` — external-reference research plus local `context-builder` passes, followed by a synthesis handoff plan and implementation-ready meta-prompt
47
+ - `/gather-context-and-clarify` — scout/research first, then ask the user clarifying questions with `interview`
48
+ - `/parallel-cleanup` — two fresh-context reviewers (deslop + verbosity passes) for an adversarial cleanup review of the current diff
49
+
50
+ ## Applying Prompt Techniques Without Slash Commands
51
+
52
+ The prompt templates in `prompts/` encode workflows the parent agent can run on demand. If the user provides a URL, issue, PR, plan, local file, screenshot, or freeform target, treat that target as the primary scope: read or fetch it before launching children, then include it explicitly in every child task. Do not depend on the parent conversation history when the recipe calls for fresh context.
53
+
54
+ ### Parallel review technique
55
+
56
+ Use this when the user wants adversarial review of a diff, plan, issue, file, or implemented work. Launch fresh-context `reviewer` agents with distinct angles generated from the actual target. Common angles are correctness/regressions, tests/validation, and simplicity/maintainability; adapt for TypeScript, UI, security, docs, or large structural changes. Reviewers should inspect files and diffs directly, return concise evidence-backed findings with file/line references, and avoid edits unless the user explicitly asks for a writer pass. The parent synthesizes fixes worth doing now, optional improvements, and feedback to ignore/defer before applying anything.
57
+
58
+ ### Review-loop technique
59
+
60
+ Use this when the user wants implementation or current diff review to continue until reviewers stop finding fixes worth doing now. Keep the loop in the parent session: one async `worker` implements or fixes, fresh-context `reviewer` agents inspect the actual repo and diff, the parent synthesizes accepted fixes, and one async forked `worker` applies them. The parent can express the sequence up front as an async/background chain when the workflow is known, or continue with explicit follow-up subagent runs after each async completion. For an initial chain, pass `async: true` so the main chat is unblocked; do not set `clarify: true` unless the user explicitly wants the foreground clarify UI. Treat an async implementation worker handoff as an intermediate state, not final completion, unless the user explicitly asked for worker-only work, review-only output, or to stop after implementation. Stop when reviewers find no blockers or fixes worth doing now, remaining feedback is optional or deferred, an unapproved product/scope/architecture decision appears, or the max review-round cap is reached. Default to 3 review rounds unless the user sets a different cap. Do not loop for optional polish, and do not let children launch subagents or decide the loop outcome.
61
+
62
+ ### Parallel research technique
63
+
64
+ Use this when the question needs both external evidence and local implications. Combine `researcher` for official docs, specs, ecosystem behavior, recent changes, benchmarks, and primary sources with `scout` for repository files, patterns, constraints, tests, and likely integration points. Give each child a distinct angle: external evidence, local code context, and practical tradeoffs. Ask for source links or file ranges, confidence level, gaps, and decision implications. Do not ask these children to edit unless implementation was explicitly requested.
65
+
66
+ ### Parallel context-build technique
67
+
68
+ Use this before planning or implementation when a stronger handoff is needed. Run a chain with one parallel step of `context-builder` agents rather than top-level parallel tasks, so relative output files live under the temporary chain directory. Give every task a distinct output path such as `context-build/request-and-scope.md`, `context-build/codebase-and-patterns.md`, and `context-build/validation-and-risks.md`. Choose two or three builders: request/scope, codebase/patterns, and validation/risks. Each builder must read every relevant file needed to understand its slice, follow imports/callers/tests/docs/config, conduct tool-available web research when needed, and include a compact `meta-prompt` section. The parent synthesizes the outputs into important context, recommended next meta-prompt, open questions, assumptions, and artifact paths.
69
+
70
+ Example shape:
71
+
72
+ ```typescript
73
+ subagent({
74
+ chain: [{
75
+ parallel: [
76
+ { agent: "context-builder", task: "Build request/scope context for: ...", output: "context-build/request-and-scope.md" },
77
+ { agent: "context-builder", task: "Build codebase/pattern context for: ...", output: "context-build/codebase-and-patterns.md" },
78
+ { agent: "context-builder", task: "Build validation/risk context for: ...", output: "context-build/validation-and-risks.md" }
79
+ ]
80
+ }],
81
+ context: "fresh"
82
+ })
83
+ ```
84
+
85
+ ### Parallel handoff-plan technique
86
+
87
+ Use this when the user needs a solution brief or implementation-ready handoff from an external reference plus local code context, such as “study this library behavior, inspect our codebase, then produce a worker prompt.” Run a chain with a first parallel group and a second synthesis `context-builder` step. The first group usually includes `researcher` for external projects/docs/prompt guidance and `context-builder` for local code context; add a second `context-builder` for implementation strategy only when the scope is large enough to benefit. Use distinct output paths under `handoff/`, then have the synthesis `context-builder` read those outputs and write `handoff/final-handoff-plan.md` with the recommended approach, likely files, constraints, non-goals, validation, risks, unresolved questions, and final compact implementation-ready meta-prompt.
88
+
89
+ Example shape:
90
+
91
+ ```typescript
92
+ subagent({
93
+ chain: [
94
+ { parallel: [
95
+ { agent: "researcher", task: "Research the external reference and transferable implementation ideas for: ...", output: "handoff/external-reference.md" },
96
+ { agent: "context-builder", task: "Build local codebase context for: ...", output: "handoff/local-context.md" },
97
+ { agent: "context-builder", task: "Compare evidence and propose implementation strategy for: ...", output: "handoff/implementation-strategy.md" }
98
+ ] },
99
+ { agent: "context-builder", task: "Read {previous} and synthesize the final handoff plan and implementation-ready meta-prompt.", output: "handoff/final-handoff-plan.md" }
100
+ ],
101
+ context: "fresh"
102
+ })
103
+ ```
104
+
105
+ ### Gather-context-and-clarify technique
106
+
107
+ Use this at the start of non-trivial work. Launch `scout` for local context and `researcher` only when external docs, recent sources, ecosystem context, or primary evidence would materially improve understanding. Ask children for concise findings plus remaining clarification questions. Then synthesize what is known and use `interview` to ask the unresolved questions needed for shared understanding before planning or implementing.
108
+
109
+ ### Parallel cleanup technique
110
+
111
+ Use this after implementation when the user wants cleanup review or when a final pass would reduce AI-slop. Launch two fresh-context `reviewer` tasks with `output: false` and `progress: false`: one deslop pass and one verbosity pass. If the `deslop` or `verbosity-cleaner` skills are available, pass the relevant skill to that reviewer; otherwise inline the criteria. Both reviewers are review-only and should flag concrete issues with severity, file/line references, and smallest safe fixes. Phrase the constraint as “Do not modify project/source files; returning findings through the configured output artifact is allowed” when you use `output` or `outputMode: "file-only"`. The parent decides what to apply and asks before making changes unless cleanup was already authorized.
112
+
113
+ ### Staged fix orchestration technique
114
+
115
+ Use this when a broad diff has known reviewer findings across several items and the user wants the parent to “orchestrate subagents like a boss.” Keep the active worktree safe with a three-stage chain:
116
+
117
+ 1. A parallel read-only planning fanout, one planner/reviewer per issue cluster. Each child inspects the real diff and returns exact files, line refs, proposed fixes, and focused validation. They must not edit.
118
+ 2. One writer worker. It receives the planner summaries through `{previous}`, the parent’s accepted scope, stop rules, and verification contract. It is the only child allowed to edit the active worktree.
119
+ 3. A parallel read-only validation fanout. Validators inspect the worker diff from fresh context with distinct angles, report pass/fail, remaining blockers, and missing verification.
120
+
121
+ Prefer `async: true`, `context: "fresh"` for planners/validators, `outputMode: "file-only"` for large summaries, and per-stage output names that will not collide. Use this pattern instead of launching several writer workers into a dirty worktree. Include non-blocking suggestions in the writer prompt only when they are small, safe, and do not expand product scope; otherwise record them as deferred.
122
+
123
+ Example shape:
124
+
125
+ ```typescript
126
+ subagent({
127
+ async: true,
128
+ context: "fresh",
129
+ chain: [
130
+ { parallel: [
131
+ { agent: "reviewer", task: "Plan fixes for deploy docs/workflow. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/deploy.md", outputMode: "file-only" },
132
+ { agent: "reviewer", task: "Plan fixes for scheduler contract. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/scheduler.md", outputMode: "file-only" },
133
+ { agent: "reviewer", task: "Plan fixes for sandbox/security. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/sandbox.md", outputMode: "file-only" }
134
+ ], concurrency: 3 },
135
+ { agent: "worker", task: "Apply only the accepted fixes from these planning summaries. You are the sole writer for the active worktree. Run focused validation and report changed files, commands, failures, and remaining issues.\n\nPlanning summaries:\n{previous}", output: "worker/fixes.md", outputMode: "file-only", progress: true },
136
+ { parallel: [
137
+ { agent: "reviewer", task: "Validate the post-worker diff for deploy and scheduler fixes. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/deploy-scheduler.md", outputMode: "file-only" },
138
+ { agent: "reviewer", task: "Validate the post-worker diff for sandbox/security fixes. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/sandbox.md", outputMode: "file-only" }
139
+ ], concurrency: 2 }
140
+ ]
141
+ })
142
+ ```
143
+
144
+ ## Builtin Agents
145
+
146
+ Builtin agents load at the lowest priority. Project agents override user agents,
147
+ and user/project agents override builtins with the same name.
148
+
149
+ | Agent | Purpose | Model | Typical output / role |
150
+ |-------|---------|-------|------------------------|
151
+ | `scout` | Fast codebase recon | inherits default | Writes `context.md` handoff material |
152
+ | `planner` | Creates implementation plans | inherits default | Writes `plan.md` |
153
+ | `worker` | Implementation and approved oracle handoffs | inherits default | Single-writer implementation with decision escalation |
154
+ | `reviewer` | Review-and-fix specialist | inherits default | Can edit/fix reviewed code |
155
+ | `context-builder` | Requirements/codebase handoff builder | inherits default | Writes structured context files |
156
+ | `researcher` | Web research brief generator | inherits default | Writes `research.md` |
157
+ | `delegate` | Lightweight generic delegate | inherits default | No fixed output; generic delegated work |
158
+ | `oracle` | Decision-consistency advisory review | inherits default | Advisory review, intercom coordination |
159
+
160
+ Builtin agents inherit the current Pi default model unless a run, user setting, or project setting overrides `model`. Override builtin defaults before copying full agent files when a small tweak is enough.
161
+
162
+ For one run, use inline config:
163
+
164
+ ```text
165
+ /run reviewer[model=anthropic/claude-sonnet-4] "Review this diff"
166
+ ```
167
+
168
+ For persistent tweaks, edit `subagents.agentOverrides` in user or project settings. User overrides apply everywhere. Project overrides apply only in that repo and win over user overrides.
169
+
170
+ ## Prompting role subagents
171
+
172
+ Builtin role agents inherit the current Pi default model unless you override them. When launching them, write the task prompt as a compact contract, not a long procedural script. Define the destination and let the role choose the efficient path.
173
+
174
+ A strong subagent prompt usually includes:
175
+ - **Goal**: the concrete outcome the child should produce.
176
+ - **Context/evidence**: relevant plan paths, files, diffs, decisions, or user constraints already approved.
177
+ - **Success criteria**: what must be true before the child can finish.
178
+ - **Hard constraints**: true invariants only, such as no edits for review-only tasks, one writer thread, child must not run subagents unless it is an explicitly assigned `tools: subagent` fanout child, or escalation for unapproved decisions.
179
+ - **Validation**: targeted checks to run, or the next-best check when validation is impossible.
180
+ - **Output**: the expected summary shape, artifact path, or finding format.
181
+ - **Stop rules**: when to ask via `intercom`, when to stop after enough evidence, and when not to keep searching.
182
+
183
+ Avoid carrying over old prompt habits that over-specify every step. Use `must`, `always`, and `never` for real invariants; for judgment calls, give decision rules. For example, tell a reviewer to inspect the staged diff directly and report only evidence-backed findings, rather than prescribing every file or command. Tell a researcher the retrieval budget: start with broad targeted searches, fetch only the strongest sources, search again only when a required fact is missing, then stop.
184
+
185
+ For implementation handoffs, name the approved scope and success criteria more clearly than the process. Good prompts say what to change, what not to change, where the evidence lives, how to validate, and when to escalate. They should not ask the child to create another subagent plan or continue the parent conversation.
186
+
187
+ Settings locations:
188
+ - User scope: `~/.pi/agent/settings.json`
189
+ - Project scope: `.pi/settings.json`
190
+
191
+ Direct settings example:
192
+
193
+ ```json
194
+ {
195
+ "subagents": {
196
+ "agentOverrides": {
197
+ "reviewer": {
198
+ "model": "anthropic/claude-sonnet-4",
199
+ "thinking": "high",
200
+ "fallbackModels": ["openai/gpt-5-mini"]
201
+ }
202
+ }
203
+ }
204
+ }
205
+ ```
206
+
207
+ Useful override fields: `model`, `fallbackModels`, `thinking`,
208
+ `systemPromptMode`, `inheritProjectContext`, `inheritSkills`, `defaultContext`,
209
+ `disabled`, `skills`, `tools`, and `systemPrompt`. Create a user or project
210
+ agent with the same name only when you want a substantially different agent.
211
+
212
+ ## Discovery and Scope Rules
213
+
214
+ Agent files can live in:
215
+ - `~/.pi/agent/agents/**/*.md` — user scope
216
+ - `.pi/agents/**/*.md` — canonical project scope
217
+ - legacy `.agents/**/*.md` — still read for compatibility, but `.pi/agents/` wins on conflicts
218
+
219
+ Chains live in:
220
+ - `~/.pi/agent/chains/**/*.chain.md` — user scope
221
+ - `.pi/chains/**/*.chain.md` — project scope
222
+
223
+ Discovery is recursive. `.chain.md` files do not define agents. Agents and chains can set optional frontmatter `package: code-analysis`; `name: scout` plus `package: code-analysis` registers as runtime name `code-analysis.scout` while serialization keeps `name` and `package` separate.
224
+
225
+ Precedence is by parsed runtime name:
226
+ 1. project scope
227
+ 2. user scope
228
+ 3. builtin agents
229
+
230
+ ## Running Subagents
231
+
232
+ ### Single agent
233
+
234
+ ```typescript
235
+ subagent({
236
+ agent: "oracle",
237
+ task: "Review my current direction and challenge assumptions."
238
+ })
239
+ ```
240
+
241
+ ### Forked context
242
+
243
+ ```typescript
244
+ subagent({
245
+ agent: "oracle",
246
+ task: "Review my current direction and challenge assumptions."
247
+ })
248
+ ```
249
+
250
+ `context: "fork"` creates a branched child session from the current persisted
251
+ parent session. It does **not** create a fresh minimal review context or filter
252
+ history down to only the relevant parts. Use it when you want a separate review
253
+ or execution thread that can still reference the parent session history.
254
+
255
+ ### Parallel execution
256
+
257
+ ```typescript
258
+ subagent({
259
+ tasks: [
260
+ { agent: "scout", task: "Explore the auth module" },
261
+ { agent: "reviewer", task: "Review the API client" }
262
+ ]
263
+ })
264
+ ```
265
+
266
+ Top-level parallel tasks can override per-task behavior:
267
+
268
+ ```typescript
269
+ subagent({
270
+ tasks: [
271
+ { agent: "scout", task: "Map auth", output: "auth-context.md", progress: true },
272
+ { agent: "researcher", task: "Research OAuth best practices", output: "oauth-research.md" },
273
+ { agent: "reviewer", task: "Review auth tests", model: "anthropic/claude-sonnet-4" }
274
+ ],
275
+ concurrency: 3
276
+ })
277
+ ```
278
+
279
+ Avoid duplicate output paths in parallel tasks. Concurrent children should not write to the same file. For large saved outputs, set `outputMode: "file-only"` together with an `output` path. The parent result then contains only a compact reference like `Output saved to: /abs/report.md (48.2 KB, 2847 lines). Read this file if needed.` instead of the full saved content. Do not use `output: false` for this; `output: false` means no file output. When a task is review-only, say “do not modify project/source files” rather than “do not write files” if you also configured `output`; otherwise the child may treat the output artifact as forbidden. Failed runs and save errors still return inline details for debugging.
280
+
281
+ ### Chain execution
282
+
283
+ ```typescript
284
+ subagent({
285
+ chain: [
286
+ { agent: "scout", task: "Map the auth flow and summarize key files" },
287
+ { agent: "planner", task: "Create an implementation plan from {previous}" },
288
+ { agent: "worker", task: "Implement the approved plan based on {previous}" }
289
+ ]
290
+ })
291
+ ```
292
+
293
+ Chain steps can use templated variables such as `{task}`, `{previous}`, and
294
+ `{chain_dir}`. This is the main way to pass structured summaries between steps
295
+ without forcing each step to rediscover everything.
296
+
297
+ ### Async/background
298
+
299
+ Prefer async mode for every subagent launch. Set `async: true` no matter the task unless there is a specific reason to opt into a foreground/blocking run. This applies to scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, chains, and parallel groups. Keep the write path single-threaded even when the run is async.
300
+
301
+ Async does not mean parallel writes. Do not edit the same active worktree while an async worker is changing it. Parent-side overlap should be reading, validation prep, synthesis, command planning, or review of unaffected context unless the writer is isolated in a separate worktree.
302
+
303
+ Do not end your turn immediately after launching an async child if you promised to keep working. Continue the local inspection, synthesis, or validation prep, then check the async run when its result is needed. If there is no independent work left and you would only be running `sleep` or status polling commands to wait, end your turn instead. Pi will deliver the async completion when it arrives.
304
+
305
+ ```typescript
306
+ subagent({
307
+ agent: "worker",
308
+ task: "Run the full test suite",
309
+ async: true
310
+ })
311
+ ```
312
+
313
+ File-only output mode also works for async single runs, top-level parallel task items, sequential chain steps, and chain parallel task items. In chains, `{previous}` receives the compact saved-file reference when the prior step used file-only mode.
314
+
315
+ For review fanout where the parent continues a local audit:
316
+
317
+ ```typescript
318
+ const run = subagent({
319
+ agent: "reviewer",
320
+ task: "Review the current diff for correctness issues. Do not edit files.",
321
+ async: true,
322
+ context: "fresh"
323
+ })
324
+ // Continue local inspection, then later call status with the returned id.
325
+ ```
326
+
327
+ Inspect async runs with `subagent({ action: "status", id: "..." })` or `subagent({ action: "status" })` for active runs. If a delegated fanout child launches nested runs, the parent status view shows them as a tree and you can target a nested run directly with its nested id.
328
+
329
+ Use `resume` for follow-up work after a delegated run:
330
+
331
+ ```typescript
332
+ subagent({ action: "resume", id: "run-id", message: "Follow up on this point." })
333
+ subagent({ action: "resume", id: "run-id", index: 1, message: "Continue reviewer 2." })
334
+ subagent({ action: "resume", id: "nested-run-id", message: "Continue this nested reviewer." })
335
+ ```
336
+
337
+ Resume behavior:
338
+ - If an async child is still running and reachable, `resume` sends the follow-up to that live child over intercom.
339
+ - If an async child has completed, `resume` revives it by starting a new async child from the persisted child session file.
340
+ - Multi-child async runs require `index` unless only one running child is selectable.
341
+ - Completed foreground single, parallel, and chain runs can also be revived by `index` while their run metadata remains in extension state.
342
+ - Nested runs can be resumed by nested id when a live route or persisted nested session metadata is available.
343
+ - Revive starts a new child process from the old session context; it does not restart the same OS process.
344
+ - If the chosen child has no persisted `.jsonl` session file, resume fails and reports that directly.
345
+
346
+ Use diagnostics when setup or child startup looks wrong:
347
+
348
+ ```typescript
349
+ subagent({ action: "doctor" })
350
+ ```
351
+
352
+ Humans can use `/subagents-doctor` for the same read-only report. It checks runtime paths, discovery counts, async support, current session context, and intercom bridge state.
353
+
354
+ ### Subagent control
355
+
356
+ Subagent control is the runtime visibility and intervention layer for delegated runs. It is separate from lifecycle status. Lifecycle status says whether a child is `queued`, `running`, `paused`, `complete`, or `failed`. Activity reporting is factual: it tracks the last observed activity time and the current tool when known. It does not pretend to know that a child is truly stuck.
357
+
358
+ Default behavior is intentionally conservative. When no activity has been observed past the configured threshold, the run emits a `needs_attention` control event. Foreground runs can push this as a `subagent:control-event` event, and async runs persist it to `events.jsonl` so the parent tracker can surface it without constant manual polling. Notification-worthy control events are also inserted into the visible transcript so both the user and the parent agent can see them, with a proactive hint plus concrete `nudge`, `status`, and `interrupt` options. Visible notifications fire once per child run and attention state.
359
+
360
+ Use soft interrupt when a child is clearly blocked or drifting and the parent needs to regain control:
361
+
362
+ ```typescript
363
+ subagent({ action: "interrupt" })
364
+ ```
365
+
366
+ Pass `id` when targeting a specific controllable run, including a nested run shown in the parent status tree:
367
+
368
+ ```typescript
369
+ subagent({ action: "interrupt", id: "abc123" })
370
+ subagent({ action: "interrupt", id: "nested-run-id" })
371
+ ```
372
+
373
+ A soft interrupt cancels the current child turn and leaves the run paused. It does not mean the delegated task succeeded or failed. Bare `interrupt` does not target hidden nested descendants; use the explicit nested id. After an interrupt, decide the next explicit action: resume with clearer instructions, replace the task, ask the user, or stop the workflow.
374
+
375
+ Per-run control thresholds can be overridden when a task legitimately runs without observable output for longer than usual:
376
+
377
+ ```typescript
378
+ subagent({
379
+ agent: "worker",
380
+ task: "Run the slow migration test suite",
381
+ control: {
382
+ needsAttentionAfterMs: 300000,
383
+ notifyOn: ["needs_attention"]
384
+ }
385
+ })
386
+ ```
387
+
388
+ If the run already has an active intercom bridge target, needs-attention notifications can also prepare a compact intercom ping for the orchestrator. When a child route is available, the ping tells the orchestrator which agent needs attention and includes the exact `intercom({ action: "send", to: "..." })` target for a nudge. Do not invent a target or ask the child to self-report when no bridge exists.
389
+
390
+ ## Clarify TUI
391
+
392
+ Single and parallel runs support a clarification TUI when you want to preview or
393
+ edit parameters before launch:
394
+
395
+ ```typescript
396
+ subagent({
397
+ agent: "worker",
398
+ task: "Implement feature X",
399
+ clarify: true
400
+ })
401
+ ```
402
+
403
+ Chains default to clarify mode; set `clarify: false` to skip it. Clarify edits affect only the next run; use management actions, settings, or markdown files for persistent changes.
404
+ For programmatic background launches, use `async: true`. Set `clarify: false` when you want to bypass chain clarification explicitly; `clarify: true` keeps the run foreground for the clarify UI.
405
+
406
+
407
+ ## Worktree Isolation
408
+
409
+ When multiple agents might write concurrently, use worktrees instead of letting
410
+ them share one filesystem view.
411
+
412
+ ```typescript
413
+ subagent({
414
+ tasks: [
415
+ { agent: "worker", task: "Implement feature A" },
416
+ { agent: "worker", task: "Implement feature B" }
417
+ ],
418
+ worktree: true
419
+ })
420
+ ```
421
+
422
+ `worktree: true` gives each parallel task its own git worktree branched from
423
+ HEAD. This requires a clean git state and is mainly for intentionally parallel
424
+ write workflows. If you want one writer thread and several advisory agents,
425
+ prefer a single-writer pattern instead.
426
+
427
+ ## The Oracle Workflow
428
+
429
+ The intended oracle loop is:
430
+ 1. the main agent forks to `oracle`
431
+ 2. `oracle` reviews direction, drift, assumptions, and risks
432
+ 3. `oracle` can coordinate back through `contact_supervisor` when the bridge injects it
433
+ 4. the main agent decides what direction to approve
434
+ 5. only then should `worker` implement
435
+
436
+ ```typescript
437
+ // Advisory review in a branched thread. Oracle defaults to forked context.
438
+ subagent({
439
+ agent: "oracle",
440
+ task: "Review my current direction, challenge assumptions, and propose the best next move."
441
+ })
442
+
443
+ // Implementation only after explicit approval. Worker defaults to forked context.
444
+ subagent({
445
+ agent: "worker",
446
+ task: "Implement the approved approach: ..."
447
+ })
448
+ ```
449
+
450
+ `oracle` is not a fresh-context reviewer in the Cognition article sense. It is
451
+ a forked advisory thread that inherits the parent session history and uses that
452
+ history as a baseline contract.
453
+
454
+ Use `oracle` as a smart-friend escalation when the parent needs help with trajectory rather than diff inspection: architectural boundaries, model capability routing, merge conflicts, reviewer disagreement, context drift after long work, a worker about to invent a pattern, or fixes that require product/scope tradeoffs. Ask broad questions when the right concern is unclear, and let `oracle` point out missing context or files the parent should inspect before asking again. Keep `oracle` advisory unless it has been explicitly assigned the single writer role.
455
+
456
+ ## Subagent + Intercom Coordination
457
+
458
+ `pi-subagents` works without `pi-intercom`. When `pi-intercom` is installed and enabled, the intercom bridge can automatically give child agents a private coordination channel back to the parent session.
459
+
460
+ Most agents should not call generic `intercom` directly unless bridge instructions provide a target and `contact_supervisor` is unavailable. Do not invent a target. Prefer the tool from the injected bridge instructions.
461
+
462
+ Use `contact_supervisor` with `reason: "need_decision"` when:
463
+ - a subagent is blocked on a decision
464
+ - a child needs clarification instead of guessing
465
+ - an approval, product, API, or scope choice is required before continuing safely
466
+
467
+ Do not use `contact_supervisor` just to resolve review-only/no-project-edit versus progress-writing or output-artifact instructions. The child must not modify project/source files, but returning findings through its normal response or configured output artifact is allowed unless the parent explicitly set `output: false`.
468
+
469
+ Use `contact_supervisor` with `reason: "progress_update"` when:
470
+ - a child is explicitly asked for progress
471
+ - a meaningful discovery changes the plan
472
+ - a long-running child needs to report a blocked/progress checkpoint without waiting for normal tool return flow
473
+
474
+ Message conventions:
475
+ - `reason: "need_decision"` waits for the parent reply and returns it to the child.
476
+ - `reason: "progress_update"` is non-blocking and should stay concise.
477
+ - Child-side routine completion handoffs are not expected. With the intercom bridge active, parent-side `pi-subagents` sends grouped completion results through `pi-intercom`: one grouped message per foreground parent run and one per completed async result file. Acknowledged foreground delivery returns a compact receipt with artifact/session paths; if unacknowledged, the normal full output is preserved. Grouped messages include child intercom targets, full child summaries, and compact nested summaries under the parent child that launched them.
478
+
479
+ If bridge instructions provide the child-facing tool, a child can ask:
480
+
481
+ ```typescript
482
+ contact_supervisor({
483
+ reason: "need_decision",
484
+ message: "Should I optimize for readability or performance here?"
485
+ })
486
+ ```
487
+
488
+ The parent replies with:
489
+
490
+ ```typescript
491
+ intercom({ action: "reply", message: "Optimize for readability." })
492
+ ```
493
+
494
+ Or inspects unresolved asks first:
495
+
496
+ ```typescript
497
+ intercom({ action: "pending" })
498
+ ```
499
+
500
+ If intercom messages do not show up, run `subagent({ action: "doctor" })` or `/subagents-doctor`.
501
+
502
+ ## Management Mode
503
+
504
+ The `subagent(...)` tool also supports management actions.
505
+
506
+ ### List available agents and chains
507
+
508
+ ```typescript
509
+ subagent({ action: "list" })
510
+ ```
511
+
512
+ ### Create an agent
513
+
514
+ ```typescript
515
+ subagent({
516
+ action: "create",
517
+ config: {
518
+ name: "my-agent",
519
+ package: "code-analysis",
520
+ description: "Project-specific implementation helper",
521
+ systemPrompt: "Your system prompt here.",
522
+ systemPromptMode: "replace",
523
+ model: "openai-codex/gpt-5.4",
524
+ tools: "read,grep,find,ls,bash"
525
+ }
526
+ })
527
+ ```
528
+
529
+ ### Update an agent
530
+
531
+ ```typescript
532
+ subagent({
533
+ action: "update",
534
+ agent: "code-analysis.my-agent",
535
+ config: {
536
+ thinking: "high"
537
+ }
538
+ })
539
+ ```
540
+
541
+ ### Delete an agent
542
+
543
+ ```typescript
544
+ subagent({ action: "delete", agent: "code-analysis.my-agent" })
545
+ ```
546
+
547
+ Use management actions when the system needs to create or edit subagents on
548
+ demand without dropping into raw file editing.
549
+
550
+ Management actions create or update user/project agent files. `config.name` is the local frontmatter name; optional `config.package` registers and looks up the runtime name as `{package}.{name}`. Use the dotted runtime name for `get`, `update`, `delete`, slash commands, and chain steps. For small builtin changes such as a model swap, prefer `subagents.agentOverrides` in settings.
551
+
552
+ ## Creating and Editing Agents by File
553
+
554
+ A minimal agent file looks like this:
555
+
556
+ ```markdown
557
+ ---
558
+ name: my-agent
559
+ package: code-analysis
560
+ description: What this agent does
561
+ model: openai-codex/gpt-5.4
562
+ thinking: high
563
+ tools: read, grep, find, ls, bash
564
+ systemPromptMode: replace
565
+ inheritProjectContext: true
566
+ inheritSkills: false
567
+ ---
568
+
569
+ Your system prompt here.
570
+ ```
571
+
572
+ That is only a starting point. Omit `package` for the traditional unqualified runtime name. Common optional fields include:
573
+ - `defaultProgress`
574
+ - `defaultReads`
575
+ - `output`
576
+ - `fallbackModels`
577
+ - `maxSubagentDepth`
578
+
579
+ For many customizations, builtin overrides in settings are lower-friction than
580
+ copying a full builtin file.
581
+
582
+ ## Prompt Template Integration
583
+
584
+ The package includes prompt shortcuts for common workflows: `/parallel-review`,
585
+ `/review-loop`, `/parallel-research`, `/parallel-context-build`,
586
+ `/parallel-handoff-plan`, `/gather-context-and-clarify`, and
587
+ `/parallel-cleanup`. Use them when the user wants repeatable review,
588
+ review/fix loops, research, context handoff, implementation handoff,
589
+ clarification, or cleanup-review patterns. `/parallel-review autofix` and
590
+ `/parallel-cleanup autofix` synthesize reviewer feedback and then apply only the
591
+ fixes worth doing now. Parent agents can also apply the same recipes directly
592
+ with `subagent(...)` when the user describes the workflow in natural language
593
+ instead of invoking a slash command.
594
+
595
+ If `pi-prompt-template-model` is installed, additional user prompt templates can delegate into
596
+ `pi-subagents`. This is useful when a slash command should always run through a
597
+ particular agent or with forked context.
598
+
599
+ ## Important Constraints
600
+
601
+ - **Forking requires a persisted parent session.** If the current session does not
602
+ have a persisted session file, forked runs fail. Packaged `planner`, `worker`,
603
+ and `oracle` default to forked context, so use `context: "fresh"` explicitly
604
+ when that is not available or not wanted.
605
+ - **Forked runs inherit parent history.** They are branched threads, not fresh
606
+ filtered contexts. Use fresh context for adversarial reviewers unless the user explicitly asks for forked context.
607
+ - **Default subagent nesting depth is 2.** Deeper recursive delegation is blocked
608
+ unless configured otherwise.
609
+ - **Attention signals are not lifecycle state.** `needs_attention` means no activity has been observed past the configured threshold. `paused` means the child turn was intentionally interrupted or is awaiting direction; it is not the same as `failed`.
610
+ - **Intercom asks are blocking.** A session can only maintain one pending outbound
611
+ ask wait state at a time.
612
+ - **Keep conversational authority clear.** Advisory subagents should not silently
613
+ become second decision-makers.
614
+
615
+ ## Best Practices
616
+
617
+ ### Prefer async orchestration
618
+
619
+ Launch every subagent asynchronously by default. Use `async: true` for scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, chains, and parallel groups unless you intentionally need a foreground/blocking run. The parent should keep moving: inspect code while scouts run, prepare validation while a worker implements, do a local diff pass while reviewers review, and synthesize or verify while a fix worker applies accepted feedback. Async is the default orchestration posture; foreground runs are the explicit opt-out.
620
+
621
+ ### Keep writes single-threaded by default
622
+
623
+ A strong pattern is one main decision-maker plus advisory/research/review/validation subagents around it. Use `oracle` for advice and `worker` for the actual write path. Parallelize reading, review, validation, and synthesis support, not normal writes, unless you deliberately isolate writers with worktrees. A child that writes should report what changed, what was left undone, commands run with exit codes, validation evidence, surprises, and any decisions that need parent approval.
624
+
625
+ ### Use fork for branched advisory or execution threads
626
+
627
+ Forked runs are useful when the child should reason in a separate thread while
628
+ still inheriting the parent’s accumulated context. They are especially useful for
629
+ `oracle`, which audits inherited decisions and drift. For adversarial code review,
630
+ prefer fresh-context reviewers that inspect the repo and diff directly unless the
631
+ user explicitly requests forked context.
632
+
633
+ ### Prefer narrow tasks
634
+
635
+ Give subagents specific tasks rather than vague mandates.
636
+ `Review auth.ts for null-check gaps` works better than `Review everything`.
637
+
638
+ ### Escalate decisions upward
639
+
640
+ If a subagent encounters an unapproved product, architecture, or scope choice,
641
+ it should coordinate back via `intercom` instead of deciding alone.
642
+
643
+ ### Intervene only on clear control signals
644
+
645
+ Use subagent control proactively when a delegated run emits `needs_attention`, or when a human asks you to regain control. Do not interrupt just because a child has briefly produced no output. Silence can be normal during long tool calls, test runs, or model reasoning.
646
+
647
+ ### Name sessions meaningfully
648
+
649
+ Use `/name` so intercom targeting stays stable.
650
+
651
+ ## Common Workflows
652
+
653
+ ### Recon → Plan → Implement
654
+
655
+ ```typescript
656
+ subagent({
657
+ chain: [
658
+ { agent: "scout", task: "Map the auth flow and summarize relevant files" },
659
+ { agent: "planner", task: "Plan the migration from {previous}" },
660
+ { agent: "worker", task: "Implement the approved plan from {previous}" }
661
+ ]
662
+ })
663
+ ```
664
+
665
+ ### Clarify → Plan → Implement → Review (self-orchestrated workflow)
666
+
667
+ When you are the orchestrating agent for a new feature or non-trivial change, factor in the packaged prompt workflows without literally invoking slash commands. Use the same patterns through tools and subagents.
668
+
669
+ Keep builtin agent defaults unless the user explicitly asks for a different model, thinking level, skills, output behavior, context mode, or other override. Do not add overrides just because you are orchestrating; the defaults encode the intended role behavior. In particular, packaged `planner`, `worker`, and `oracle` default to forked context.
670
+
671
+ When the user approves launching a subagent to carry out a plan or workflow, treat that as approval to generate a proper role-specific meta prompt for that subagent. Include the approved plan path or summary, clarified requirements, non-goals, relevant context, role boundaries, files or areas to inspect, acceptance criteria, expected output, and validation expectations. Do not pass vague instructions like “implement the plan fully” or “review this” by themselves.
672
+
673
+ - `/gather-context-and-clarify` maps to: launch `scout` and, when needed, `researcher`; synthesize findings; then use `interview` to ask every clarification question needed for shared understanding.
674
+ - `/parallel-review` maps to: launch fresh-context `reviewer` agents with distinct review angles; synthesize the feedback before applying anything.
675
+ - `/review-loop` maps to: keep the parent in charge of worker → fresh reviewers → synthesized fix worker cycles until no fixes worth doing now remain, an unapproved decision appears, or the review-round cap is reached.
676
+ - `/parallel-research` maps to: combine local `scout` context with external `researcher` evidence when current docs, ecosystem behavior, or API details matter.
677
+ - `/parallel-context-build` maps to: run a chain-mode parallel group of `context-builder` agents with distinct temp output paths, then synthesize their context and meta-prompt sections.
678
+ - `/parallel-handoff-plan` maps to: run external `researcher` plus local/strategy `context-builder` passes, then a synthesis `context-builder` that writes an implementation handoff plan and implementation-ready meta-prompt.
679
+ - `/parallel-cleanup` maps to: use review-only cleanup passes after implementation, especially for simplicity, verbosity, and redundant tests.
680
+
681
+ For feature work, use this sequence as scaffolding for parent-agent behavior:
682
+
683
+ ```text
684
+ clarify → validation contract → planner → async worker → parallel async fresh-context reviewers/validators → async fix worker → follow-up review when warranted → parent review
685
+ ```
686
+
687
+ The validation contract defines what done means before code is written: expected behavior, acceptance checks, commands or user flows to exercise, and evidence the worker should return. Keep it lightweight for small tasks, but make it explicit enough that reviewers and validators are checking the intended outcome rather than the worker’s own assumptions.
688
+
689
+ The first `worker` implements the approved plan. The parent continues with independent inspection or validation prep while it runs, not parallel edits to the same worktree. When the async worker completes, treat its handoff as the transition into review, not as final completion, unless the user explicitly asked for worker-only work, review-only output, or to stop after implementation. Parallel reviewers inspect the resulting diff from fresh context. Validators check behavior with the best available evidence: commands, tests, browser/CLI interaction, screenshots, logs, or manual reproduction notes. The final `worker` applies synthesized review fixes in forked context, then the parent looks over the final diff before completing. The parent may launch these steps as an initial async chain when the workflow is already clear, or as follow-up subagent runs after each async completion. Initial chains should pass `async: true` so the main chat is unblocked; avoid `clarify: true` unless the user asked for foreground clarification. Do not stop after parallel review unless the user explicitly asked for review-only output or the review surfaced a decision that needs approval first.
690
+
691
+ For complex work, risky changes, broad refactors, or many changed lines, increase review and validation fanout rather than trusting one reviewer. Use distinct angles such as correctness/regressions, tests/validation, simplicity/maintainability, security/privacy, performance, docs/API contracts, and user-flow behavior. When reviewers find non-trivial issues or the fix worker touches many lines, run another focused review round before final validation.
692
+
693
+ When review has already produced concrete findings across several independent areas, use staged fix orchestration: parallel read-only planners for each issue cluster, one sole writer worker for the active worktree, then parallel fresh-context validators. This is the safest way to handle a dirty worktree with many prior changes because it parallelizes judgment without parallelizing writes. Non-blocking suggestions may go into the writer prompt only if they are small, safe, and inside the approved scope; otherwise defer them explicitly.
694
+
695
+ For very large work, split into serial milestones instead of launching a swarm of writers. Each milestone gets one writer, a validation contract, fresh-context review/validation, a fix pass, and parent acceptance before the next milestone starts. Use parallel subagents inside a milestone for read-only context, research, review, and validation only.
696
+
697
+ Keep orchestration authority in the parent session. Child subagents should not launch more subagents, read this skill, or run their own orchestration loops unless the parent intentionally selected a fanout agent whose builtin `tools` includes `subagent`. Spawned subagents do not receive the `pi-subagents` skill, parent-only status/control/slash messages, or prior parent `subagent` tool-call/tool-result artifacts. Ordinary children also do not receive the `subagent` extension tool. Child context filtering strips old hidden orchestration-instruction messages when they appear in inherited history. Every child receives a boundary instruction: ordinary children are told the parent owns orchestration and they must not propose or run subagents; explicit fanout children are told to use `subagent` only for the assigned fanout work, with `maxSubagentDepth` still enforced. Implementation children must call real edit/write tools instead of printing pseudo tool calls. Pass children concrete role-specific work instead.
698
+
699
+ 1. Clarify first. This is mandatory. Gather code context with `scout` or `context-builder`, add `researcher` only when external evidence matters, then ask the user clarifying questions with `interview` until scope, acceptance criteria, constraints, and non-goals are clear.
700
+ 2. Define the validation contract. State what done means before implementation: expected behavior, checks to run, user flows to exercise, and evidence required in the worker handoff. For UI, CLI, integration, or workflow changes, include at least one validator angle that uses the product the way a user would rather than only reading code.
701
+ 3. Plan when useful. For complex work, call `planner` or write a plan doc yourself and get approval before implementation. For simple work, confirm shared understanding and explicitly note why planning is skipped.
702
+ 4. Implement with one writer. After approval, launch `worker` asynchronously with a proper meta prompt that includes clarified requirements, relevant context, plan path or summary, the validation contract, and output expectations. Packaged `worker` defaults to forked context; pass `context: "fresh"` only when you intentionally want a fresh child. While it runs, prepare validation or inspect adjacent code instead of editing the same worktree.
703
+ 5. Require a useful worker handoff. Ask the worker to report changed files, what was implemented, what was left undone, commands run with exit codes, validation evidence, surprises or new risks, decisions made inside approved scope, and decisions needing parent approval.
704
+ 6. Review after implementation. After the worker completes, launch parallel async fresh-context `reviewer` agents for correctness/regressions, tests/validation, and simplicity/maintainability. Add security, performance, docs/API, domain-specific, or user-flow validators for complex work, risky changes, broad refactors, or many changed lines. Use `output: false` unless review artifacts are explicitly needed.
705
+ 7. Synthesize, then run the fix worker. Separate blockers, fixes worth doing now, optional improvements, and feedback to ignore/defer, then launch an async forked `worker` to apply fixes worth doing now when the workflow is implementation-authorized. If reviewers found scope/product/architecture choices that were not approved, ask the user first instead of applying them.
706
+ 8. Review again when warranted. If the fix worker made substantial changes or addressed non-trivial findings, run another focused parallel review round before final validation.
707
+ 9. Validate and complete. After the fix worker and any follow-up review return, inspect the final diff yourself, run or confirm focused validation, update docs/changelog when relevant, and summarize what changed and why.
708
+
709
+ Example implementation handoff after clarification and optional planning:
710
+
711
+ ```typescript
712
+ subagent({
713
+ agent: "worker",
714
+ task: "Implement the approved feature.\n\nClarified requirements:\n- ...\n\nPlan: see ~/Documents/docs/...-plan.md\n\nValidation contract:\n- ...\n\nReturn a handoff with changed files, what was implemented, what was left undone, commands run with exit codes, validation evidence, surprises/new risks, and decisions needing parent approval.",
715
+ async: true
716
+ })
717
+ ```
718
+
719
+ Example review pass after implementation:
720
+
721
+ ```typescript
722
+ subagent({
723
+ tasks: [
724
+ { agent: "reviewer", task: "Review the current diff for correctness and regressions. Inspect changed files directly; do not rely on the worker's reasoning.", output: false },
725
+ { agent: "reviewer", task: "Review the current diff for tests and validation quality against the validation contract. Inspect changed files directly.", output: false },
726
+ { agent: "reviewer", task: "Review the current diff for simplicity and maintainability. Inspect changed files directly.", output: false }
727
+ ],
728
+ concurrency: 3,
729
+ context: "fresh",
730
+ async: true
731
+ })
732
+ ```
733
+
734
+ Example fix worker after parallel reviews:
735
+
736
+ ```typescript
737
+ subagent({
738
+ agent: "worker",
739
+ task: "Apply the synthesized reviewer feedback below. Only apply fixes worth doing now; preserve user-approved scope; ask before unapproved product or architecture changes. Run focused validation and summarize what changed.\n\nReviewer synthesis:\n...",
740
+ async: true
741
+ })
742
+ ```
743
+
744
+ ### Review loop
745
+
746
+ Do not treat review as the final step for implementation work. Run reviewers and validators, synthesize their findings against user scope and the validation contract, then launch one `worker` for accepted fixes when implementation is authorized.
747
+
748
+ When an async implementation worker completes, treat the worker handoff as an intermediate state. The next parent action is review fanout, then synthesis, then a fix worker if reviewers found fixes worth doing now. This can be planned as an initial async chain when the whole workflow is known, or continued as follow-up subagent runs when the parent only launched the first worker initially. Initial chains should pass `async: true` so the main chat is unblocked; `clarify: true` is the explicit foreground opt-in.
749
+
750
+ For explicit review-loop requests, repeat worker → fresh-reviewer → synthesized-fix-worker cycles until reviewers find no blockers or fixes worth doing now, remaining feedback is optional or intentionally deferred, an unapproved product/scope/architecture decision needs the user, or the max review-round cap is reached. Default to 3 review rounds unless the user sets a different cap. For complex work, many changed lines, or any fix pass that materially changes the diff, run another focused review round before the parent’s final look; otherwise stop instead of chasing optional polish.
751
+
752
+ ### Parallel non-conflicting analysis
753
+
754
+ ```typescript
755
+ subagent({
756
+ tasks: [
757
+ { agent: "scout", task: "Audit frontend auth flow" },
758
+ { agent: "researcher", task: "Research current retry/backoff best practices" }
759
+ ]
760
+ })
761
+ ```
762
+
763
+ ### Saved chain
764
+
765
+ ```text
766
+ /run-chain review-chain -- review this branch
767
+ ```
768
+
769
+ Use saved `.chain.md` workflows when the user wants a repeatable multi-agent flow without rewriting the chain each time.
770
+
771
+ ## Error Handling
772
+
773
+ **"Unknown agent"**
774
+ ```typescript
775
+ subagent({ action: "list" })
776
+ // Check available agents and chains, then confirm scope/precedence.
777
+ ```
778
+
779
+ **Setup, discovery, or intercom confusion**
780
+ ```typescript
781
+ subagent({ action: "doctor" })
782
+ // Check runtime paths, async support, discovery counts, current session, and intercom bridge state.
783
+ ```
784
+
785
+ **"Max subagent depth exceeded"**
786
+ ```typescript
787
+ // Flatten the workflow or raise maxSubagentDepth in config.
788
+ ```
789
+
790
+ **"Session manager did not return a session file"**
791
+ ```typescript
792
+ // Persist the current session before using context: "fork".
793
+ ```
794
+
795
+ **Intercom "Already waiting for a reply"**
796
+ ```typescript
797
+ // Resolve the current outbound ask before starting another one.
798
+ ```
799
+
800
+ **Parallel output-path conflict**
801
+ ```typescript
802
+ // Give each parallel task a distinct output path, or disable output for tasks that do not need it.
803
+ ```
804
+
805
+ **Worktree launch fails**
806
+ ```typescript
807
+ // Ensure the git working tree is clean and task cwd overrides match the shared cwd.
808
+ ```
809
+
810
+ **Child fails before starting**
811
+ ```typescript
812
+ // Inspect `subagent({ action: "status", id: "..." })`, artifact metadata/output logs, and run doctor. Extension loader errors usually appear in child output logs.
813
+ ```