---
name: pi-subagents
description: |
  Delegate work to builtin or custom subagents with single-agent, parallel,
  chain, async, forked-context, and supervisor-coordinated workflows. Use for
  specialized analysis, independent review, implementation handoffs, and
  multi-step work where the parent must retain control.
---

# Pi Subagents

This skill is for the parent orchestrator only. Do not inject it into spawned
children. Use delegation when specialization, independent context, parallel
reading, or long-running work provides real value; keep tiny tasks local.

## Non-negotiable invariants

- **The parent owns orchestration.** The parent approves scope, synthesizes
  findings, decides whether loops continue, and accepts the final result.
- **Ordinary children do not delegate.** The only exception is an explicitly
  assigned fanout child whose resolved builtin tools include `subagent`; it may
  delegate only the fanout work assigned by the parent.
- **One writer per active worktree.** Parallelize research, review, and
  validation. Use isolated worktrees only for intentionally parallel writers.
- **Reviewers are not inherently read-only.** Every review-only task must say:
  “Do not modify project/source files.” Output artifacts are still allowed
  unless `output: false` is set.
- **Decision boundaries return to the parent.** Do not chain planning directly
  into implementation or review directly into fixes when parent approval or
  synthesis is required.
- **Escalate unapproved decisions.** Product, API, architecture, scope, cost,
  privacy, and risk choices belong to the user or parent, not a child.
- **Schedule only on explicit request.** Never create speculative delayed runs.
- **Publish only with user approval.** Commits, pushes, releases, and pull
  requests require an explicitly approved boundary.

## Choose an agent and context

Call `subagent({ action: "list" })` before execution. Use only listed executable
agents, and check any reported chain diagnostics before launching a chain.

| Agent | Use |
| --- | --- |
| `scout` | Fast local repository reconnaissance |
| `context-builder` | Requirements and codebase handoff context |
| `planner` | Implementation plans after context is understood |
| `worker` | Sole-writer implementation of approved work |
| `reviewer` | Review, validation, or an explicitly assigned fix task |
| `researcher` | External evidence, official docs, and current behavior |
| `delegate` | Lightweight generic delegation |
| `oracle` | Optional advice about inherited direction, drift, or tradeoffs |

Context choice:

- Use `context: "fresh"` for adversarial review, independent validation,
  research, and work that should not inherit the parent’s reasoning.
- Use `context: "fork"` when the child needs the persisted parent history.
  Forking requires a persisted parent session and creates an inherited branch,
  not a filtered context.
- Packaged `planner`, `worker`, and `oracle` default to forked context. Be
  explicit when context choice affects correctness.
- `oracle` is situational and advisory. Use it for trajectory or tradeoff
  questions, not as a mandatory precursor to every worker.

## Write a task contract

Give each child a compact contract rather than a procedural script:

- **Goal:** the concrete result to produce.
- **Context/evidence:** files, diffs, plans, decisions, URLs, and constraints.
- **Success criteria:** what must be true before completion.
- **Hard constraints:** read-only status, sole-writer ownership, and non-goals.
- **Validation:** checks or direct user-flow evidence to gather.
- **Output:** expected findings, handoff fields, or artifact path.
- **Stop/escalation rules:** when to stop, ask the parent, or avoid more search.

Reusable constraints:

```text
Review-only: Do not modify project/source files. Returning findings through the
normal response or configured output artifact is allowed.

Writer: You are the sole writer for this worktree. Stay inside the approved
scope and ask before making product, API, architecture, or scope decisions.
```

A writer handoff should report changed files, completed and incomplete work,
commands with exit codes, validation evidence, surprises, residual risks, and
questions requiring approval.

### Acceptance

Use `acceptance` when the run needs an explicit evidence contract:

- `checked` requires the configured handoff evidence.
- `verified` runs configured validation commands at runtime.
- `reviewed` means an independent reviewer result exists; a worker cannot
  self-attest to it, and explicit runs should not request it directly.
- Disable gates with `{ level: "none", reason: "..." }`; bare `"none"` is
  rejected and `false` is deprecated.

Child-reported command success is evidence, not runtime verification.

## Execution shapes

Prefer `async: true` unless a foreground result is immediately required. Async
is an orchestration policy, not the runtime default, so set it explicitly.

### Single

```typescript
subagent({
  agent: "oracle",
  task: "Review the inherited direction and identify unapproved assumptions.",
  context: "fork",
  async: true
})
```

### Parallel read-only work

```typescript
subagent({
  tasks: [
    {
      agent: "scout",
      task: "Map the auth flow. Do not modify project/source files."
    },
    {
      agent: "reviewer",
      task: "Audit auth tests. Do not modify project/source files."
    }
  ],
  context: "fresh",
  concurrency: 2,
  async: true
})
```

Give parallel tasks distinct output paths. Use `outputMode: "file-only"` with
an `output` path for large artifacts. `output: false` means no output file; it
does not make a child read-only.

### Chain without crossing an approval boundary

```typescript
subagent({
  chain: [
    { agent: "scout", task: "Map the auth flow." },
    { agent: "planner", task: "Create a plan from {previous}." }
  ],
  async: true
})
```

After the parent reviews and approves the plan, launch the worker separately:

```typescript
subagent({
  agent: "worker",
  task: "Implement the parent-approved plan: ...",
  async: true
})
```

Chains may use `{task}`, `{previous}`, `{chain_dir}`, and `{outputs.name}`.
Name outputs with `as` when a later step needs one specific result. Use
`outputSchema` for reliable structured handoffs. Do not predeclare a chain that
bypasses parent approval or review synthesis.

### Worktree isolation

`worktree: true` gives top-level parallel tasks isolated Git worktrees and
requires a clean repository. Use it only when parallel writers are intentional;
otherwise keep one writer in the active worktree.

### Clarify UI and scheduling

`clarify: true` previews or edits a foreground single, parallel, or chain launch.
Do not combine it with ordinary background orchestration. Scheduled runs are
opt-in, always fresh and async, and must be explicitly requested by the user.
See the README parameter reference for syntax and limits.

## Async lifecycle and control

After launching async work, continue useful independent work. Do not edit the
same worktree while an async worker owns it.

In interactive chat, normally return control and let Pi wake the session. Call
`subagent_wait()` when this request must run to completion in the current
turn.
Headless sessions auto-drain current-session work at `agent_end`. Call
`subagent_wait()` when the turn itself needs the result. Never sleep or poll in
a loop merely to wait.

- `subagent_wait()` waits for the next initially active run or provider item.
- `subagent_wait({ all: true })` drains everything active at call time.
- `subagent_wait({ id: "..." })` waits for one tracked run.
- `subagent_wait({ timeoutMs })` caps waiting without stopping the run.

Control actions:

```typescript
subagent({ action: "status", id: "run-id" })
subagent({ action: "status", view: "fleet" })
subagent({ action: "steer", id: "run-id", message: "Focus on the failing test." })
subagent({ action: "interrupt", id: "run-id" })
subagent({ action: "resume", id: "run-id", message: "Continue with ..." })
```

Use `steer` for acknowledged guidance to a live top-level async child. Use
`resume` for paused, completed, or failed children; revival requires a stored
session file, and multi-child runs may require `index`. Stopped runs are not
resumable. `needs_attention` only means observed activity is stale—it is not a
failure state. A soft interrupt cancels the current child turn and leaves the
run paused; choose an explicit next action afterward. Do not interrupt merely
because a long tool call is quiet.

<!-- markdownlint-disable MD013 -->
As a conservative orchestration policy, do not pass `turnBudget` or a hard `toolBudget` to mutation-capable children.
<!-- markdownlint-enable MD013 -->
The default tool budget blocks read/search tools rather than mutation tools, so
its count is not a safe delivery boundary. Prefer a narrow delivery slice and
adequate elapsed time over hard turn/tool-count limits. A timeout is not a
mutation-safe checkpoint. Request a checkpoint after the current tool returns;
it should describe changed files, build/test state, and remaining work. Report
commit or PR state.

## Canonical workflows

### Recon and planning

1. Run `scout` or `context-builder`; add `researcher` only when external evidence
   materially helps.
2. The parent reads the load-bearing source and resolves disagreements.
3. Ask only questions needed to resolve material ambiguity.
4. Run `planner` when complexity warrants it.
5. Return the plan to the parent or user for approval before implementation.

### Implementation and review

1. Define a validation contract before code changes.
2. Launch one async `worker` with approved scope and sole-writer instructions.
3. While it runs, prepare validation or inspect unaffected context; do not edit
   its worktree.
4. Treat the worker handoff as intermediate, not final.
5. Launch fresh-context, explicitly read-only reviewers with distinct angles:
   correctness/regressions, tests/validation, and simplicity/maintainability.
   Add security, performance, docs/API, or user-flow review when warranted.
6. The parent classifies findings as blockers, fixes worth doing now, optional,
   or deferred/incorrect.
7. If implementation is authorized, launch one worker for accepted fixes.
8. Rereview substantial or non-trivial fixes, then inspect and validate the
   final diff in the parent.

Stop when no blockers or worthwhile fixes remain, only optional/deferred items
remain, an unapproved decision needs the user, or the review-round cap is hit.
Default explicit review loops to at most three rounds; do not chase polish.

Every canonical reviewer task must include the no-source-edit clause. Reviewers
may edit only when directly assigned an authorized fix task.

### Review-only

Launch fresh, explicitly read-only reviewers, then synthesize their evidence.
Do not launch a fix worker unless the user has authorized implementation.

### Parallel research or context building

Give each reader a distinct angle and, when saving artifacts, a distinct output
path. External research should cite primary sources; local analysis should cite
file ranges. The parent combines evidence and records gaps and confidence.

### Staged broad fixes

Do not encode this as one uninterrupted chain:

1. Parallel read-only planners inspect issue clusters.
2. The parent accepts an exact fix scope.
3. One sole-writer worker applies accepted fixes.
4. Fresh read-only validators inspect the resulting diff.
5. The parent synthesizes the outcome and decides whether another fix pass is
   justified.

### Fable mode for complex work

For cross-cutting, ambiguous, high-impact, or expensive-to-validate work, use
these parent-owned gates:

1. **Understand:** gather breadth, then personally read load-bearing evidence.
2. **Decide:** resolve user-owned product, cost, taste, and risk choices.
3. **Design:** synthesize one plan and define seams between workstreams.
4. **Implement:** capture a baseline and use one writer per worktree.
5. **Verify:** climb from static checks to the least expensive realistic probe;
   observe actual behavior, not only exit codes.
6. **Iterate:** classify failures, search for siblings, and send one fix worker.
7. **Ship:** run independent review, disposition findings, rerun affected gates,
   and summarize evidence, artifacts, and residual risks. Commit, push, release,
   or open a pull request only inside a user-approved boundary.

Split very large work into serial milestones. Parallelize read-only support
inside a milestone, then require parent acceptance before the next milestone.

## Supervisor coordination

Children should use the bridge-injected `contact_supervisor` tool. Do not invent
an intercom target. Generic `intercom` is only a fallback when bridge
instructions provide a target and `contact_supervisor` is unavailable.

- `need_decision`: blocking approval or free-form clarification.
- `interview_request`: blocking structured supervisor input.
- `progress_update`: concise, non-blocking material progress or changed risk.

Do not send routine completion pings. Do not ask whether review-only children
may return normal responses or configured artifacts; those are allowed unless
explicitly disabled. The parent replies with `subagent_supervisor`, usually
after checking `subagent_supervisor({ action: "pending" })`.

When a foreground child detaches for supervisor coordination, reply first and
then wait on that run ID. Do not resume it or launch a replacement while the
detached child remains active; doing so can duplicate work or create two
writers.

## Essential constraints

- Forked runs require a persisted parent session and inherit its full history.
- Default nesting depth is bounded; flatten workflows instead of recursively
  orchestrating ordinary children.
- Only one blocking supervisor ask may be pending per child session.
- Advisory children do not become decision-makers or writers implicitly.
- Parallel output paths must be unique.
- Tool allowlists do not load extension providers; requested tools must also be
  available through normal discovery or configured child extensions.
- Use `subagent({ action: "doctor" })` for setup, discovery, startup, or bridge
  problems before guessing.

## Reference documentation

Keep this skill focused on orchestration behavior. Use the package README for
operational detail:

- **Common workflows** and **Programmatic tool usage**
- **Background and forked runs** and **Native supervisor coordination**
- **Agents and chains**, **Management actions**, and agent-file fields
- **Parameter reference**, **Configuration**, and **Acceptance Gates**
- **Worktree isolation**, scheduling, prompt-template integration, and RPC

Useful human commands include `/run`, `/parallel`, `/chain`, `/run-chain`,
`/subagents-fleet`, `/subagents-doctor`, `/subagents-models`, and
`/subagent-cost`. Agents should normally use `subagent(...)` directly.
