---
name: dispatching-subagents
description: Dispatch sf's internal subagents — single, parallel, debate, or chain. Use when stuck on a hard problem, need parallel research from multiple lenses, or want adversarial / role-based debate before locking a decision. Stays inside sf's own agent fabric — no shelling out to external CLIs.
---

# Dispatching Subagents

sf has a built-in subagent fabric. Use the `subagent` tool to spawn sub-agents inside the same sf session: single delegation, parallel research, bounded debate rounds, chain pipelines, and swarm-style dispatch with parent synthesis. They share sf's model routing, allowed providers, memory store, and MCP tools — they are *sf agents*, not external coding-agent CLIs.

This skill is sf-internal only. **Do not** shell out to external `claude`, `codex`, or other coding-agent CLIs from inside sf — that breaks the harness boundary, bypasses sf's model routing, and loses traceability into `.sf/traces/`.

## When to Dispatch

| Need | Pattern |
|---|---|
| Hard problem, want fresh eyes | Single subagent (validation tier). |
| Multiple hypotheses to explore | Parallel batch — one subagent per hypothesis. |
| Adversarial review of a plan | Debate mode with advocate + challenger, or [`advisory-partner`](../advisory-partner/SKILL.md). |
| Multi-stakeholder critique of a milestone roadmap | Debate mode or parallel swarm: PM / User / Combatant / Architect / Specialist (5–8 subagents). |
| Pre-execution gate evaluation | sf's built-in Q3 / Q4 gates — already wired in `gate-evaluate.md`. |
| Post-execution milestone review | sf's `validate-milestone` — already 3 parallel reviewers. |
| Iterative refinement of a result without re-briefing | Background single + `write_subagent` / `read_subagent` (multi-turn). |

Don't dispatch a subagent for tasks the parent agent can do in 2–3 tool calls. Subagent overhead beats parent-agent work only when the task is large enough or the parallelism actually buys something.

## Swarm Suitability Gate

Before using a same-model execution swarm, decide whether swarming is actually
the right shape. Default to **no swarm** unless the work passes this gate.

Use a 2-3 worker swarm when all of these are true:

- The work decomposes into independent shards with clear file or directory ownership.
- Each worker can receive a small, complete prompt without depending on another worker's live edits.
- Verification can run per shard, then once globally after merge.
- The expected saved wall-clock time is larger than dispatch, synthesis, and merge overhead.
- Conflicts are unlikely or can be isolated behind explicit interfaces/contracts.

Do not swarm when any of these are true:

- Multiple workers need to edit the same files, generated artifacts, lockfiles, migrations, or shared public interfaces.
- The task is mostly design judgment, debugging one failure, or a sequence where step B depends on step A's result.
- The repo is already dirty in the target files and ownership cannot be assigned safely.
- The result needs a single coherent narrative or API design more than raw throughput.

If the gate passes, start small: use 2 workers by default, 3 only when the
third shard has genuinely independent ownership. More workers are reserved for
read-only research/review until full file-lease swarm execution exists.

## The `subagent` Tool

sf's `subagent` tool dispatches one or more sub-agents that share the parent session's allowed providers, memory store, and tool surface, but run with their own context and model selection.

### Single subagent

```
subagent({
  agent: "worker",
  task: "<task instructions, full context, expected output>"
})
```

The subagent runs to completion and returns its final output as a string. No context inheritance from the parent — provide everything in the prompt.

### Parallel batch (swarm)

```
subagent({
  tasks: [
    { agent: "reviewer", task: "Advocate for the design. Cite repo evidence. ..." },
    { agent: "reviewer", task: "Challenge the design. Cite repo evidence. ..." },
    { agent: "security", task: "Audit the design for security failure modes. ..." },
    { agent: "tester",   task: "Find missing proof and test coverage. ..." }
  ]
})
```

All tasks run concurrently. The tool returns one result per task, preserving task order and agent names. Use `tasks` whenever you can — sf's auto-loop already accounts for parallel subagent budgets.

For execution swarms, the parent must assign ownership explicitly:

```
subagent({
  model: "kimi-k2.6",
  tasks: [
    {
      agent: "worker",
      task: "Shard A. Edit only src/foo/**. Do not touch shared interfaces except to report a requested change. Run the shard's narrow tests and return changed files plus verification."
    },
    {
      agent: "worker",
      task: "Shard B. Edit only src/bar/**. Do not touch shared interfaces except to report a requested change. Run the shard's narrow tests and return changed files plus verification."
    }
  ]
})
```

Same-model swarms are acceptable for throughput-oriented execution models such
as Kimi K2.6 or MiniMax M2.7-highspeed, but model choice does not replace the
ownership gate. The parent remains coordinator and must synthesize, inspect
dirty files, resolve conflicts, and run final verification.

### Debate batch

```
subagent({
  mode: "debate",
  rounds: 3,
  tasks: [
    { agent: "reviewer", task: "Advocate for <design>. Cite repo evidence." },
    { agent: "reviewer", task: "Attack <design>'s strongest assumption and propose an alternative." },
    { agent: "planner",  task: "Moderate from architecture and delivery risk. End with a recommendation." }
  ]
})
```

Debate mode runs bounded rounds. In each round, every participant sees the
previous rounds' transcript, so the challenger can engage the advocate's
strongest defence instead of firing a parallel monologue.

Use debate mode for high-stakes decisions, plan review, architecture review,
and migrations where the cost of a weak plan is high. Keep `rounds` between 2
and 3 by default; max is 5.

### Parent trace (for verifier/review subagents)

Set `parentTrace` when dispatching a verifier or reviewer that should audit
what the parent **actually did**, not just what the parent's prose claims. The
dispatch tool wraps the value in a `<parent_trace>...</parent_trace>` block
prepended to the task, with embedded verifier instructions to look for hedge
words, glossed-over tool errors, and claims without Command/Output traces. The
parent assembles its own trace (recent tool-call summary); the dispatch tool
only plumbs it through.

```
subagent({
  parentTrace: "<recent tool-call summary: commands run, outputs, edits made>",
  tasks: [
    { agent: "reviewer", task: "Audit the migration for correctness against the spec." },
    { agent: "tester",   task: "Audit test coverage for the new code paths." }
  ]
})
```

Per-task `parentTrace` overrides the batch-level value — set it on a single
`TaskItem` (or `ChainItem`) when one subagent needs a different trace.

For chain mode, only step 0 receives the trace; later steps see `{previous}`.
For debate mode, only round 1 receives the trace; later rounds have the debate
transcript. For parallel and single mode, the trace is always injected when
set.

### Agent selection and model overrides

sf routes subagents through agent definitions in `src/resources/agents/`,
`~/.sf/agent/agents/`, or project `.sf/agents/`. SF is not a general CLI coder
with a menu of personas; bundled agents are primarily SF's internal autonomous
worker pool. Direct human invocation is an operator/debug path. The actual tool
schema uses `agent`, `task`, optional per-task `model`, optional `cwd`, plus
batch-level `mode`/`rounds` for debates.

- `planner` — architecture and implementation planning; conflicts with active sf planning phases.
- `critic` — adversarial pre-implementation review; surfaces blocking flaws before code is written.
- `scout` — fast codebase recon.
- `researcher` — web/current-info research.
- `reviewer` — independent code/design review.
- `tester` — tests and coverage gaps.
- `security` — security audit.
- `worker` — general-purpose execution.

Use `model` only when you need an explicit override:

```
{ agent: "reviewer", task: "...", model: "claude-sonnet-4-5" }
```

### Multi-turn background (write_subagent / read_subagent)

Single-mode background jobs support iterative refinement without re-establishing context.

```
// Turn 0: launch
subagent({ agent: "researcher", task: "Analyse X. Return findings.", background: true })
// → "Background job started: sub_a1b2c3d4"

// After await_subagent returns:
write_subagent({ job_id: "sub_a1b2c3d4", message: "Focus on the Y aspect and expand." })
// → "Follow-up dispatched on sub_a1b2c3d4 (turn 2). Use await_subagent to get the response."

// After second await_subagent:
read_subagent({ job_id: "sub_a1b2c3d4" })
// → Full turn history: agent (turn 0), user (turn 1), agent (turn 2)

// Read only new turns:
read_subagent({ job_id: "sub_a1b2c3d4", since_turn: 2 })
```

**How it works:** The subagent receives the original task + full conversation history + new message. The agent retains the role/context of the original dispatch — no re-briefing needed.

**Constraints:**
- Only available for single-mode jobs (`agent` + `task`, no `tasks`/`chain`).
- `write_subagent` on a running job is rejected — wait for completion first.
- Counts against the same `maxRunning` concurrency limit as new jobs.
- The conversation history is injected into the task string. For very long conversations (10+ turns, multi-KB each), prefer starting a fresh subagent with a synthesised briefing to avoid hitting OS argument length limits.

## Patterns

### Pattern 1 — Parallel research

Three subagents investigate three hypotheses simultaneously; the parent synthesises:

```
subagent({
  tasks: [
    { agent: "scout", task: "Investigate whether the claim() race could leak past the conditional UPDATE under SQLite's WAL semantics. Cite files and line numbers. ..." },
    { agent: "scout", task: "Investigate whether claim_until expiry handles clock skew between hosts. ..." },
    { agent: "scout", task: "Investigate whether a crashed worker's claim can be resurrected after a stale-lock cleanup. ..." }
  ]
})
```

Each returns a paragraph; the parent picks the highest-confidence finding.

### Pattern 2 — Adversarial review (advocate + challenger)

For non-trivial decisions, pressure-test before locking:

```
subagent({
  mode: "debate",
  rounds: 3,
  tasks: [
    { agent: "reviewer", task: "Argue the strongest case FOR <design>. Cite repo evidence. End with: ADVOCATE_VERDICT: <PROCEED | CAVEAT>." },
    { agent: "reviewer", task: "Attack <design>'s strongest assumption AND propose an alternative. Anchored attacks don't count — propose a different framing. End with: CHALLENGER_VERDICT: <design wrong if [observable condition]>." }
  ]
})
```

The parent synthesises the advocate's strongest support, the challenger's strongest objection, and either answers the objection or accepts it as residual risk. Debate mode gives later rounds the prior transcript.

This is the pattern [`advisory-partner`](../advisory-partner/SKILL.md) wraps. Use that skill rather than reinventing if the subject is a plan or decision being reviewed.

### Pattern 3 — Multi-role swarm

For high-stakes milestone planning, spawn a stakeholder swarm (the same roles as the Vision Alignment Meeting in `plan-milestone`):

```
subagent({
  mode: "debate",
  rounds: 2,
  tasks: [
    { agent: "planner",    task: "Product Manager view: what is the real product move? What should the roadmap prove? ..." },
    { agent: "reviewer",   task: "User Advocate view: what must matter for UX and trust? ..." },
    { agent: "reviewer",   task: "Combatant view: why is this roadmap wrong, overbuilt, or solving the wrong thing? ..." },
    { agent: "planner",    task: "Architect view: system fit and sequencing synthesis. ..." },
    { agent: "researcher", task: "Researcher view: comparable products, OSS tools, market expectations. ..." },
    { agent: "planner",    task: "Delivery Lead view: smallest credible milestone sequence and scope cuts. ..." }
  ]
})
```

The parent does **weighted synthesis**, not majority vote. Confidence-by-area trumps headcount.

### Pattern 4 — Code review at slice close

Already wired into `validate-milestone` (3 parallel reviewers: Requirements Coverage, Cross-Slice Integration, Acceptance Criteria) — invoke the prompt rather than rolling your own.

For non-milestone changes, use [`requesting-code-review`](../requesting-code-review/SKILL.md) which dispatches advocate + challenger-A + challenger-B before submitting.

## Prompt Template (per subagent)

```
TASK: <one-sentence summary>

CONTEXT:
- Repo: <project-root>
- Key files: <list specific paths and what they contain>
- Architecture: <brief relevant context — phase machine, harness boundary, etc.>
- Doctrine: AGENTS.md and docs/SPEC_FIRST_TDD.md

WHAT TO DO:
<what you need done — be precise about scope; let them choose method>

CONSTRAINTS:
- Follow the Iron Law (failing test first, no completion without a real consumer).
- <preferences, patterns, things to avoid>
- <what the parent has already tried, if dispatching because stuck>

OUTPUT:
<expected structure — JSON, bullet list, paragraph; end with a verdict line if applicable>
```

Things to make explicit because the subagent has no context inheritance:

- **Specific files** (paths, line ranges) — "look at `src/resources/extensions/sf/auto/loop.ts:140-180`", not "the auto-loop".
- **Output format** — don't leave it open-ended.
- **Constraints** — sf-specific rules (`AGENTS.md`, `.sf/DECISIONS.md`).
- **Falsifier** for review tasks — what observable condition would change the verdict.

## Synthesis

After a parallel or debate batch returns, the parent agent **must** synthesise. The synthesis goes back into the unit's artefacts so the next phase sees it:

- For research swarms: pick the highest-confidence finding; document why the others were rejected.
- For adversarial reviews: state the strongest support and strongest objection; either answer the objection or accept it as residual risk in writing.
- For stakeholder swarms: weighted synthesis with confidence-by-area; do not majority-vote.

Persist non-trivial syntheses to memory:

```
log_reasoning(
  category="design-synthesis",
  content="<one-line synthesis of the swarm result> — slice <id>",
  confidence=<0.0-1.0>
)
```

## Subagent Prompt Audit

Before dispatching, audit each subagent prompt. The subagent inherits sf's tool surface but **does not** inherit the parent's mode constraints (autonomous vs auto, ask-gate state) — the prompt is the only thing constraining its behaviour.

Check the prompt for each of:

- **Smuggled user-question.** In autonomous mode, the parent is forbidden from `ask_user_questions` (see `bootstrap/ask-gate.ts`). A subagent dispatched with "ask the user about X" sidesteps this. Reject prompts that delegate the user-prompt the parent itself isn't allowed to issue.
- **Action-class delegation.** A prompt that instructs the subagent to perform a destructive action (force-push, drop schema, delete worktree) inherits that action's risk regardless of which agent runs it. If the action would be blocked for the parent, block it at dispatch — don't route around the gate by spawning a child.
- **Scope creep.** A research subagent ("scout") with a prompt that asks it to *also* fix what it finds is two roles in one. Split: scout reports, parent decides whether to dispatch a worker. Mixing roles in one prompt produces unauditable side effects.
- **Tool surface vs prompt mismatch.** A subagent agent definition with `disallowedTools: [Edit, Write]` (read-only role) cannot satisfy a prompt that asks for "fix the bug". Either the agent or the prompt is wrong; reject the dispatch and pick the right pairing.

When the subagent returns, scan the result for these patterns before treating it as evidence:

- **Hedge words** ("should be fine", "probably", "looks correct based on my reading"). The subagent rationalised instead of verifying. Re-dispatch with explicit verification requirements.
- **Tool-result errors glossed over.** Search the subagent's reported actions for `Error:`, `failed`, non-zero exit codes that the subagent narrated past. If the subagent treated a tool failure as success, its conclusion is unreliable.
- **Self-reports without traces.** "I ran the tests and they pass" without a Command/Output block is the agentic equivalent of a hand-wave. Trust traces, not summaries.

## Hard Rules

- **Stay inside sf.** Do not shell out to `claude`, `codex`, or any other external coding-agent CLI. sf's own subagent fabric handles all of this with proper trace integration.
- **Use the `validation` tier** for adversarial / advisory subagents. The whole point of an advisory-partner is that it's *not* the planning model.
- **Don't reuse the same lens twice in one swarm.** If two challengers attack from the same angle, you have one challenger with two voices — not two perspectives.
- **Pass the doctrine paths** in every subagent prompt: `AGENTS.md`, `docs/SPEC_FIRST_TDD.md`, the relevant `.sf/DECISIONS.md` row. The subagent has no context inheritance.
- **Synthesise — don't just collect.** A swarm result without synthesis is a list of opinions. The parent owns the decision.
- **If all subagents report low confidence, gather better evidence** rather than spawning more opinions. More voices saying "I don't know" is not signal.

## Failure Modes

- **Garbage subagent output** — prompt was too vague. Rewrite with specific paths and clearer expected output.
- **Subagent contradicts the parent's framing** — your framing was probably wrong. Re-verify facts before synthesis.
- **All subagents agree quickly** — check whether you accidentally framed the prompts toward a single conclusion. Adversarial pairs that always agree aren't adversarial.
- **Subagent timeout** — break the task into smaller dispatches; for research, prefer a `research` tier model with longer context window.

## Cross-References

- [`advisory-partner`](../advisory-partner/SKILL.md) — the canonical adversarial-review framework. Wraps the advocate / challenger / falsifier pattern.
- [`brainstorming`](../brainstorming/SKILL.md) — invokes parallel research and adversarial subagents during the design step.
- [`code-review`](../code-review/SKILL.md) — the multi-lens review skill; can be parallelised by dispatching one subagent per lens.
- [`gate-evaluate.md`](../../prompts/gate-evaluate.md) (prompt) — pre-execution Q3/Q4 gates dispatched as parallel subagents.
- [`validate-milestone.md`](../../prompts/validate-milestone.md) (prompt) — post-execution milestone validation with 3 parallel reviewers.

## Future: Full Swarm Chat

Round-robin debate mode exists now: `subagent({ mode: "debate", rounds: 3, tasks: [...] })`.

Still deferred:

- **Full swarm chat** — agent-to-agent `send_message` during an ephemeral swarm, scoped by `swarm_id` with a TTL. Reuses the persistent-agent inbox machinery from `SPEC.md` §17–18. Best fit for open-ended multi-stakeholder Vision Alignment Meeting use cases.

Full design, sequencing, risks, and implementation sketch in **[ADR-011](../../../../../../docs/dev/ADR-011-swarm-chat-and-debate-mode.md)**. Tracked in [`BUILD_PLAN.md`](../../../../../../BUILD_PLAN.md) (Tier 1+ active follow-ups).
