---
name: multi-agent
description: "Task orchestrator: runs the full pipeline from a Jira ID or GitHub Issue URL  -  analysis → plan → TDD development → parallel review (Fable + Opus + Sonnet on Claude Code, GPT + Opus + Sonnet on Copilot CLI) → commit → log. Every step is written to agent-log.md. Use when given a Jira ID, a GitHub issue or a free-text task and the whole pipeline should run."
user-invocable: true
argument-hint: '"PROJ-12345" "feature/PROJ-12345-order-filter" | "https://github.com/.../issues/316" | status | log #1 | resume #1 | kill #1 | clear-logs | purge | review'
metadata:
  language: en
---

Read and follow the instructions in this file's INSTRUCTION.md section below.

---

# Multi-Agent Task Orchestrator

References under `$HOME/.claude/multi-agent-refs/` are installed with Claude Code.

## Project Detection

Detect project from cwd FIRST, then validate input format:

| cwd contains | Project | Accepted Input | Rejected Input |
|--------------|---------|----------------|----------------|
| `/my-ios-app` | my-app | `"PROJ-XXX" "branch"` | GitHub Issue URL |
| `/my-figma-app` | figma | `"https://github.com/.../issues/N"` | Jira ID + branch |
| Other | generic | Both formats |  -  |

If user gives wrong format for the project, warn:
- my-ios-app + GitHub URL → "This project expects a Jira ID + branch. Example: multi-agent \"PROJ-12345\" \"feature/PROJ-12345-desc\""
- my-figma-app + Jira → "This project expects a GitHub Issue URL. Example: multi-agent \"https://github.com/my-org/my-figma-app/issues/316\""

## Input Parsing

Classify user input into one of 5 types (matches the `commands/multi-agent/SKILL.md` dispatcher contract; cross-CLI parity is enforced by `smoke-cross-cli-behavior.sh`):

| # | Pattern | Type | Action |
|---|---------|------|--------|
| 1 | `#N` or bare `316` | github-issue-number | Fetch via gh after project selection |
| 2 | `https://github.com/.../issues/N` | github-issue-url | Extract org/repo/N, fetch via gh |
| 3 | `https://{JIRA_HOST}/browse/{JIRA_KEY}-XXXXX` | jira-url | Extract ID, fetch via Jira API |
| 4 | `{JIRA_KEY}-XXXXX` (bare) | jira-id | Fetch via Jira API |
| 5 | Anything else | free-text | No external fetch |

All types enter the same Phase 0 flow.

## Routing

Parse the user's input and route to the correct sub-command:

| Input Pattern | Action |
|---------------|--------|
| `"PROJ-XXX" "branch"` | **my-app only**  -  Jira ID + branch name → auto-assigned incremental ID |
| `"https://github.com/..."` | **figma only**  -  parse issue, extract Jira from title/body, auto-create branch |
| `status` | Show all tasks with ID, phase, status |
| `log [id]` | Show agent-log.md for task (latest if no id) |
| `resume [id]` | Resume paused/failed task from last successful phase |
| `kill [id]` | Stop task, delete worktree + branch + logs. Asks confirm first |
| `clear-logs` | Superseded  -  redirect only, see below |
| `purge` | Nuclear cleanup  -  delete ALL worktrees, branches, logs, state, counter. Full reset |
| `review` | Skip phases 0-3, review current diff only |
| `autopilot` flag | Add to any pipeline command  -  skip user confirmations except destructive ops |
| No args / `help` | Show usage guide (project-specific) |

## Task operations: status, kill, purge, resume

Every task gets an auto-incremented short ID (`#1`, `#2`), stored in `agent-state.json`.

- **kill** MUST ask for confirmation before deleting anything; the remote branch is deleted ONLY on a second, explicit yes.
- **purge** MUST confirm twice: a first confirm, then a native `AskUserQuestion` paranoia gate where anything other than **Purge permanently** cancels. Remote branches are deleted ONLY on explicit confirmation.
- **resume** reads `$HOME/.claude/logs/multi-agent/{project}/{task-id}/agent-state.json` (or `.../artifacts/agent-state.json` for a task Phase 4 finalized) and restarts from `currentPhase + 1`.
- **clear-logs**: **do not run it.** Say it was superseded, then route to `multi-agent-prune-logs` (per-task logs, audit trail and metrics kept) or `multi-agent-garbage-collect` (`/tmp` scratch + worktree residue). Logs live at `$HOME/.claude/logs/multi-agent/{project}/{task-id}/`, not under `.worktrees/`.

Full procedure: `$HOME/.claude/multi-agent-refs/orchestrator/operations.md`. Read it when the input is `status`, `kill`, `purge` or `resume`.

---

## Autopilot Mode

Add `autopilot` to any pipeline command (`multi-agent "PROJ-12345" "feature/PROJ-12345-desc" autopilot`) to skip interactive confirmations and run end-to-end.

| Phase | Normal | Autopilot |
|-------|--------|-----------|
| Phase 1 (Plan Approval Gate) | Clarification (max 2 rounds) + approval loop  -  user replies `onayla`/`iptal`/free-text | **Gate skip**  -  log the plan, go straight to Phase 2 (autopilot contract: zero interaction) |
| Phase 3 (User test) | "Want to test it?" → wait | Skip → go straight to Phase 4 |
| Phase 4 (Commit) | "Want to commit?" → wait | Automatic commit + push |
| Phase 4 (PR) | "Want to open a PR?" → wait | Automatically create the PR |

**What NEVER skips (even in autopilot):**
- Phase 3 Review → if there is a blocking finding, return to Phase 2, fix + rebuild automatically (safety)
- Kill/Purge confirmations → destructive operations always ask
- Build fail → fix + rebuild automatically (max 3 retries). If it still fails after 3 retries → pause, ask the user

**State tracking**: `"autopilot": true` is added to `agent-state.json`. Autopilot continues on resume too.

Full procedure: `$HOME/.claude/multi-agent-refs/phases/modes.md`. Read it when `autopilot` is set, for the circuit-breaker halts and the Phase 5 channels pause.

---

## Agent dispatch  -  per-persona model routing

Every agent persona under `$HOME/.claude/agents/*.md` declares a `preferredModel` frontmatter field. The orchestrator MUST honor it on every dispatch, on both Claude Code and Copilot CLI  -  cross-CLI parity is enforced by `smoke-cross-cli-behavior.sh`. Each persona file carries its own `modelRationale`; this is the rung only.

| Persona | `preferredModel` |
|---|---|
| `explorer` | `sonnet` |
| `code-reviewer` | `fable` (Reviewer 1; Phase 3 sets Reviewer 2 `opus`, Reviewer 3 `sonnet`) |
| `security-auditor` | `opus` |
| `ios-architect` / `android-architect` / `backend-architect` | `fable` |

**Dispatch contract:**

```bash
persona_file="$HOME/.claude/agents/${persona}.md"
pref_model="$(awk '/^preferredModel:/ {print $2; exit}' "$persona_file")"
override="${PHASE_MODEL_OVERRIDE:-}"   # per-dispatch, e.g. Phase 3 Reviewer 3 → sonnet
routed="${override:-$("$HOME/.claude/lib/model-dispatch.sh" subagent --persona "$persona" --phase "$currentPhase" --task-kind "$taskType" --default "${pref_model:-opus}" 2>/dev/null)}"
resolved_model="${routed:-${pref_model:-opus}}"

export CLAUDE_CODE_SUBAGENT_MODEL="$resolved_model"
# Claude Code honors the env var; Copilot CLI also passes it as --model.
```

**Precedence:** per-dispatch `PHASE_MODEL_OVERRIDE` > `prefs.global.modelRouting` rule > persona `preferredModel` > global default (`opus`). Routing here is Anthropic-only: features/model-fallback.md "Routing at dispatch".

**Observability:** emit `phase.agent.dispatch` OTel span with `{persona, resolved_model, override_source}` attributes when `MULTI_AGENT_OTEL_SPANS=1` (see `phase-tracker.sh`).

## Skill loading and injection

Gated by `prefs.global.dynamicSkillLoading` (default `false`): when on, only skills matched by `match-skills.mjs` are injected into Phase 1-3 sub-agent prompts; without `.skills-index.json` it eager-loads, so it never blocks the happy path. Every sub-agent prompt SHOULD carry task-specific context from Phase 1 on top of the persona's embedded skills.

Full procedure: `$HOME/.claude/multi-agent-refs/orchestrator/skill-loading.md`. Read it when `dynamicSkillLoading` is on, or when composing a sub-agent prompt.

---

## Phase Pipeline

Run phases sequentially. Log every step to `agent-log.md`.
If any phase fails, mark task as `paused` and stop  -  user can `resume` later.

**The blocks below are the routing summary, not the specification.** Each phase's
full contract lives in `$HOME/.claude/multi-agent-refs/phases/phase-{n}-{name}.md`
and is read when that phase actually starts. Modes are in `phases/modes.md`,
operations in `phases/operations.md`, the log shape in `phases/log-format.md`.
Where a summary here and a ref disagree, the ref wins.

### Canonical phase labels (TaskCreate + banner)

Every user-facing phase title  -  TaskCreate cards, `phase-banner.sh` headers, and any status line rendered to the terminal  -  MUST come from this table. Phase labels are English on every host (`promptLanguage` is fixed to `en`; picker text follows its own matrix):

| # | Label                |
|---|----------------------|
| 0 | Phase 0: Init        |
| 1 | Phase 1: Plan        |
| 2 | Phase 2: Dev         |
| 3 | Phase 3: Review      |
| 4 | Phase 4: Commit & PR |
| 5 | Phase 5: Report      |

**Render rule:**

1. For TaskCreate, use the matching label as the task `subject`.
2. For terminal banners, call `phase-banner.sh` with the `auto` sentinel and `PHASE_LANG=en` env  -  or pass the literal label from the table. Never invent a new label.
3. Reviewer-count qualifiers (e.g. `(parallel + triage)`) stay English  -  they are technical artifacts, not user copy.

**Out of scope for localization** (always EN, per `prefs.schema.json`): reviewer/triage system prompts, commit messages, PR titles/bodies, Jira comments, wiki content, log payloads inside `agent-log.md`  -  these are external artifacts consumed by other tools and humans beyond this user.

#### TaskCreate ordering (strict)

All TaskCreate calls fire in strict phase-number order BEFORE any TaskUpdate is applied (Claude Code path; Copilot CLI has no TaskList widget, so this rule is Claude-only). The widget renders by creation order, so out-of-order calls scramble the tile stack even when the state file is correct. Pre-marking phases as completed/skipped before Phase 0 starts is FORBIDDEN: register each tile in order as `pending`, then flip via TaskUpdate when the phase actually short-circuits. Mode-specific phase sets:

- `multi-agent`, `multi-agent-autopilot`: 0 → 1 → 2 → 3 → 4 → 5
- `multi-agent-analysis`: 0 → 1 → 3 → 4 → 5 (no code is written, so Dev is not in the set)

Every mode registers its whole set at Step -1. Full contract: `refs/tracker-contract.md` section "TaskCreate ordering (strict)".

### Phase 0: Init

> **Contract (strict)**  -  Phase 0 has **8 sequential interactive steps**, defined in
> `$HOME/.claude/multi-agent-refs/phases/phase-0-init.md`. Read it before every Phase 0 run and execute all of
> them. Do **NOT** short-circuit: even when the input is a Jira ID plus a branch, the
> prefs load, the multi-repo offer, the branch picker and the branch-name confirm are
> required UX checkpoints.
>
> **Exit gate (BLOCKING).** Before marking Phase 0 completed:
>
> ```bash
> node "$HOME/.copilot/scripts/phase0-exit-gate.mjs" "$TASK_ID" --input "$USER_INPUT"
> ```
>
> Non-zero means Phase 0 did not produce its own output - `taskType`, `baseBranch`,
> `baseFetchStatus`, a worktree path distinct from the project root, and a recorded Figma
> access tier when the input carries a Figma URL. Fix the missing step; do not proceed.
>
> **Credential inventory (Step 0).** Run
> `bash "$HOME/.copilot/lib/credential-inventory.sh" --json` and store the result in
> `agent-state.json.credentialInventory`. Per `refs/keychain.md` Rule 2, never ask the
> user for data a mapped credential can fetch. Ask for the pointer (the issue URL)
> instead, and say what you will do with it.

Per-project input parsing (my-ios-app / my-figma-app / generic), worktree creation, git author and the initial log + state files. Full procedure: `$HOME/.claude/multi-agent-refs/orchestrator/phase-0-projects.md`. Read it when Phase 0 reaches input parsing and worktree setup.

**IMPORTANT**: Update `agent-state.json` at EVERY phase transition. This file is the resume source of truth.

### Phase 1: Plan
Two halves, one phase, one approval gate.

**1a  -  Analysis** (claude-sonnet-5, `explorer` persona)
1. Launch **explore agents** (parallel) to scan the codebase: related files, existing patterns and conventions, potential impact areas
2. Summarize findings
3. Log: `📊 Phase 1: Plan (analysis)  -  {N} files identified, {summary}`

**1b  -  Planning** (claude-fable-5)
1. Create task breakdown → todos with dependencies
2. Launch **ios-architect** agent for architecture review (if structural changes)
3. Determine development approach per todo (new file, modify, refactor)
4. Log: `🧠 Phase 1: Plan  -  {N} todos created`
5. **Plan Approval Gate** (interactive only  -  autopilot may not ask). Full flow in `refs/phases/phase-1-plan.md` Step 5:
   - **5a  -  Clarification** (conditional, max 2 rounds): if the Jira/issue description is ambiguous (vague acceptance, UI task without Figma, API task without endpoint contract, `ambiguityScore >= 2`, parent-story scope drift), ask structured questions before rendering the plan. User answers → plan regenerated. If it is still unclear after the 2nd round, render the plan with a "best-effort" banner.
   - **5b  -  Approval loop**: render plan → user: `onayla`/`iptal`/free-text. A free-text edit request → the planning model (Fable) revises the plan → show it again. No iteration cap; user controls exit via `onayla` or `iptal`.
   - Persist `clarificationRounds`, `clarificationQuestions`, `clarificationAnswers`, `planIterations`, `planApprovedAt`, `planEditRequests` to `state.phases["1"]`.

### Phase 2: Dev (claude-sonnet-5)
For each todo (respecting dependency order):
1. Update todo status: `in_progress`
2. **TDD cycle**: write failing test → verify RED; write minimal code → verify GREEN; refactor if needed
3. Run build: `xcodebuild` via **task agent**
4. If build fails → fix → rebuild (max 3 attempts, track `retryCount` in `agent-state.json`)
5. Update todo status: `done`
6. Log: `⚡ Phase 2: {todo-id}  -  Test ✅ Build ✅`

### Phase 3: Review (parallel + triage)
0. **Diff Risk Scoring (advisory)**  -  before reviewer dispatch run `node $HOME/.claude/scripts/diff-risk-score.mjs --base "$BASE_BRANCH" --top 5` and inject the top-N risk-ranked files as a `${PRIORITY_FILES}` block into each reviewer's prompt. Heuristic, deterministic, sub-second, never gates the pipeline. Disabled when `prefs.global.diffRiskAdvisory = false`. Signals: security paths (×3), schema migrations (×4), public API surfaces (×2), no-test-change (×2.5), complexity delta (×1.5), UI-critical paths (×1.5), loc changed (×1).
1. Launch **code-reviewer** agents in parallel. Reviewer set depends on which CLI is hosting the pipeline:
   - **Claude Code** (3 reviewers): `claude-fable-5` (deep security + architecture) + `claude-opus-5` (edge cases, different perspective) + `claude-sonnet-5` (quality + correctness)
   - **Copilot CLI** (3 reviewers): `gpt-5.4` (edge cases, different perspective) + `claude-opus-5` + `claude-sonnet-5` (Fable 5 is not offered on Copilot CLI)
   - Triage: single top-tier pass over merged findings (`claude-fable-5` on Claude Code, `claude-opus-5` on Copilot CLI)
2. Collect findings, classify:
   - 🔴 **Blocking** → must fix → back to Phase 2 (max 3 iterations)
   - 🟡 **Important** → fix and re-review
   - 🟢 **Suggestion** → apply if reasonable
3. Log: `🔍 Phase 3: Review  -  {consensus}`

#### Phase 3 user test (optional, interactive)
Lets the user test the code before the PR, through a native `AskUserQuestion` picker (never a typed y/N prompt). The prompt MUST say that yes **removes the worktree and checks the branch out locally**, or the side effect is implicit. Skip → Phase 4; a requested fix recreates the worktree and returns to Phase 2. Commits live on the branch, so removing the worktree does NOT delete them.

Full procedure: `$HOME/.claude/multi-agent-refs/orchestrator/phase-3-user-test.md`. Read it when Phase 3 review is done and the run is interactive.

### Phase 4: Commit & PR

Every project:
1. **Ask**: "Want to commit?" **No** → pause; the user continues with `resume` when ready.
2. my-figma-app: run `/figma-iteration-commit {ComponentName}`  -  do NOT commit manually, the skill manages everything.
3. my-app / generic: stage specific files with `git add` (NOT `git add -A`  -  avoid committing .env, credentials, or other sensitive files), commit as `{type}({scope}): {description} [PROJ-{id}]`, push, then **Ask**: "Want to open a Pull Request?" before creating it.
4. Author: resolved from `prefs.global.identities[]`  -  NEVER hardcode.

Full procedure: `$HOME/.claude/multi-agent-refs/orchestrator/phase-4-5-projects.md`. Read it when Phase 4 starts, for the per-project steps and the GitHub issue body update.

### Phase 5: Report
1. Finalize `agent-log.md` with ALL sections:
   - **Timeline table**: phase, agent, model, duration, status, detail
   - **Agent Activity Report**: per-agent call count, total duration, models used, skill count
   - **Token Estimate**: estimated token usage per agent + total
   - **Per-Phase Time Distribution**: ASCII bar chart showing time per phase
   - **Review Iterations**: blocking/important/suggestion counts per iteration
   - **Files Changed**: `git diff --stat` output
   - **Review Consensus**: final 🔴/🟡/🟢 status
   - **Test Scenarios**: Turkish, for Jira (Precondition → Steps → Expected result)
2. Print compact summary to terminal:
   ```
   ✅ PROJ-{id} complete
   ⏱️  Total: 3m 18s | Agents: 12 calls | Files: 4 changed
   📦 Commit: abc1234 | PR: #87
   📖 Wiki: {ComponentName}.md pushed to wiki master
   📋 Full report: ~/.claude/logs/multi-agent/{project}/{task-id}/agent-log.md
   ```
3. Log: `📋 Phase 5: Report complete`

**Step 2  -  Wiki + Figma screenshots** runs only for a component implementation with a GitHub Issue (skip for a bug fix or refactor). Full procedure: `$HOME/.claude/multi-agent-refs/orchestrator/phase-4-5-projects.md`. Read it when Phase 5 reports a component task.

---

## Log File Format

Canonical shape, and the path the code actually uses, live in
`$HOME/.claude/multi-agent-refs/phases/log-format.md`. Read it when writing
the log; do not re-derive the format here.

## Component Generation

Generic guide: `$HOME/.claude/multi-agent-refs/component-generation.md`.
Dispatch (which plugin skill handles it per CLI):
`$HOME/.claude/multi-agent-refs/component-dispatch.md`.
Loaded only for a task that generates a component from a design.

## Rules

- ❌ NEVER put "Copilot", "AI", "generated by" in code or commits
- ❌ NEVER commit without passing build
- ❌ NEVER commit without passing review
- ❌ NEVER auto-close an issue (GitHub or Jira); PR bodies use `Ref: #N` / `Related: #N`, never `Closes/Fixes/Resolves`
- ✅ Follow existing code style and conventions
- ✅ Use design tokens, no magic numbers
- ✅ Every public method must have tests
- ✅ Xcode header on new Swift files
- ✅ Commit message format:
  - With Jira: `{type}({scope}): description [PROJ-{id}]`
  - Without Jira (generic): `{type}({scope}): description [#{shortId}]`
- ✅ Git author: resolved from `prefs.global.identities[]` (e.g. `{identity.name} <{identity.email}>`)  -  NEVER hardcoded

## Help Display

Rendered by the `multi-agent-help` skill (`/multi-agent-help`), which owns the full text in both languages.
