---
name: agent-team
description: Auto-generate and run a per-repo Claude Code agent team. Probes the current repo (build/CI/env manifests, agent launchers, slash commands, spec dirs) and writes `.claude/agents/{role}.md` subagent definitions for the relevant roles from a library (coder, reviewer, auditor, tester, documenter, release, researcher) plus a `.claude/agent-team.md` workflow doc. Use when (1) `/agent-team init` to create the team for the current repo, (2) `/agent-team update` to refresh after project shape changes, (3) `/agent-team {task}` to run a task with the team (TeamCreate plus spawn plus drive orchestrator flow plus stop at user gates). Triggers include "/agent-team", "spin up a team", "auto-create agents", "agent team for this repo", "team-on-task".
---

## What this skill does

Builds and operates a Claude Code [agent team](https://code.claude.com/docs/en/agent-teams) tailored to the current repo. Inspired by Viktor Farcic's [`dot-agent-deck`](https://github.com/vfarcic/dot-agent-deck) (a TUI that both displays and defines multi-agent teams across Claude Code and OpenCode); this skill is the native-APIs alternative: it probes the current repo for signals, picks roles from a library, and writes Claude Code native `.claude/agents/*.md` subagent definitions plus a `.claude/agent-team.md` workflow doc, so teammates are spawned by name via the Agent tool's `subagent_type` parameter.

The skill has three modes selected by the first argument:

| Mode | Trigger | What it does |
|------|---------|--------------|
| **init** | `/agent-team init`, or no args + no `.claude/agents/` present | Probe the repo, pick roles, write `.claude/agents/<role>.md` + `.claude/agent-team.md` |
| **update** | `/agent-team update` | Re-probe, diff against existing `.claude/agents/`, apply targeted changes |
| **run** | `/agent-team <task description>` | Read team manifest, TeamCreate, spawn teammates, drive the workflow, STOP at user gates |

`.claude/agents/` is a Claude Code project-scoped subagent directory. `.claude/agent-team.md` is a workflow manifest this skill writes for its own use; not loaded automatically by Claude Code but read by the skill on `run`.

## Autonomy: spin up teams as you see fit

When this skill is loaded, the team-lead has standing authority to spawn agents and create teams without asking the user to authorize each one. Decide which roles to spawn, how many, whether to run them in the foreground or background, and when to recycle or shut them down, based on the task shape, not on per-call user confirmation. The user does NOT have to say "create coder + reviewer" or "spin up the team for this"; if the work fits the team's shape, just do it.

Scope of standing authority:

- **Spawning teammates** from the existing `.claude/agents/` roster for the active task.
- **TeamCreate / TeamDelete** at task boundaries.
- **Background vs foreground** mode per Agent call.
- **Recycling** a teammate at a clean task boundary (Mode 3 Step 5 + the "Context recycling" section below).
- **Dispatching slash commands** the orchestrator may invoke between delegations (per the workflow manifest).

Still requires explicit user confirmation (do NOT auto-act):

- **Shared-system writes** the team would perform on the user's behalf: release tag pushes, force-pushes, PR merges, sending external messages. Present a verification summary and STOP, per Mode 3 Step 4.
- **PRD-task transitions** to a NEW scope (`/dot-ai-prd-next`, picking the next task). Analyze and propose; spawn only after acceptance.
- **Role-file hotfixes** (Mode 3 Step 6.A) unless pre-authorized in durable instructions.
- **Editing the role library** at `./roles.yaml` or running `/agent-team update`.

If `.claude/agents/` is missing for the current repo, propose `/agent-team init` before spawning; do not auto-init without surfacing the proposed roster.

## Required pre-checks

Before any mode, confirm:

1. `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set (per the [docs](https://code.claude.com/docs/en/agent-teams), agent teams are experimental and disabled by default). Check `settings.json` or env. If missing, tell the user how to enable it and stop.
2. The current working directory is a git repo root (look for `.git`). If not, ask the user to confirm the target directory.
3. Claude Code `v2.1.32` or later: `claude --version`.

## Mode 1: init

Use when `.claude/agents/` does not exist, or `/agent-team init` is invoked explicitly.

### Step 1: discover the repo

Probe for these signals. Use the Glob and Read tools; do NOT run `find /`. All probing scoped to the current repo.

- **Build/package manifests**: `package.json`, `go.mod`, `pyproject.toml`, `Cargo.toml`, `pom.xml`, `Gemfile`, `build.gradle`, `Makefile`, `kcl.mod`, `Chart.yaml`.
- **Task runners**: `Taskfile.yml`, `justfile`, `Makefile`, `package.json#scripts`.
- **Reproducible-env manifests**: `devbox.json`, `flake.nix`, `shell.nix`, `.nvmrc`, `pyproject.toml` (poetry), `environment.yml`, `.tool-versions`, `.envrc`. The first hit drives `init_command` references in the team workflow doc.
- **Agent launchers**: scripts/aliases that launch a Claude/opencode/etc. session. Look in `scripts/`, `Taskfile.yml`, `Makefile`, `package.json#scripts`, devbox script blocks. Record the FULL invocation form (`devbox run agent-big`, `task agent`, `make agent`), not the bare script name.
- **Project slash commands** the orchestrator can invoke between delegations: `.claude/commands/`, `.claude/skills/`. List them; the lead will reference them in the workflow doc.
- **Spec directories**: `prds/`, `specs/`, `rfcs/`, `proposals/`, `docs/adr/`, `docs/design/`.
- **CI configs**: `.github/workflows/`, `.forgejo/workflows/`, `.gitlab-ci.yml`, `Jenkinsfile`, `.circleci/`.
- **Release signals**: `docs/releasing.md`, `RELEASING.md`, `.goreleaser.*`, `CHANGELOG.md`, `semantic-release.json`, `.releaserc*`, a release workflow in CI.
- **CLAUDE.md and CONTRIBUTING.md**: read both (top-level and any nested). They contain authoring rules workers must follow.

Cite the actual files/directories you found in the proposal you present to the user. Do not pad with generic boilerplate.

### Step 2: pick roles

Load the role library at `./roles.yaml` (relative to this SKILL.md). For each role:

- **coder, reviewer, auditor**: always include. These are the default trio.
- **tester**: include if any of the role's `triggers_on` patterns match a path in the repo (`tests/`, `test/`, `*_test.go`, `pytest.ini`, etc.).
- **documenter**: include if a non-trivial `docs/` dir exists OR README is large (>500 lines) OR a docs site config is present (`mkdocs.yml`, `book.toml`, `docusaurus.config.*`).
- **release**: include if any release signal from §discover step matches.
- **researcher**: opt-in only; include if the user requests it or if the repo has a substantial spec directory (≥3 documents) suggesting research-heavy work.

If a borderline call needs the user, ask via AskUserQuestion before writing files.

### Step 3: tune prompt bodies

For each picked role, take the `prompt_body` from `roles.yaml` and append project-specific details discovered in step 1:

- **coder**: name the actual test/lint command (e.g. `task test`, `cargo test`, `pytest`, `devbox run -- task kcl:test`). Reference CONTRIBUTING.md / CLAUDE.md by path. Reference the spec directory if found.
- **reviewer**: cite the authoring-rules file (CONTRIBUTING.md / CLAUDE.md) by exact path and quote one or two of its load-bearing rules if obvious.
- **auditor**: note if the repo is public (security implications differ); name the secret scanner if found in CI (`gitleaks`, `trufflehog`).
- **tester**: name the test framework discovered (jest, pytest, go test, cargo test).
- **documenter**: name the doc site generator (mkdocs, hugo, docusaurus) or "plain markdown" if none.
- **release**: name the release flow doc by path (`docs/releasing.md`, etc.) and the release command (`semantic-release`, `goreleaser`, manual tag-push).
- **researcher**: name the spec directory.

Keep additions tight: 1-3 extra sentences per role. The role library text already covers the generic shape.

### Step 4: present a proposal

Show the user a numbered proposal:

```
Proposed team for <repo-name>:

1. coder (sonnet) - implements features, fixes bugs. Will run `<test-command>`
   before reporting done. Will follow rules in <CONTRIBUTING.md path>.
2. reviewer (sonnet) - reviews against <CONTRIBUTING.md rules>. Read-only.
3. auditor (sonnet) - security audit. Notes: <public/private repo>, secret
   scanner: <name>. Read-only.
4. tester (sonnet) - <test framework discovered>. (included because <reason>)
   [omit if not picked]
5. release (sonnet) - runs <release-doc path>. (included because <release signal>)
   [omit if not picked]
... etc

Files I would write:
  .claude/agents/coder.md
  .claude/agents/reviewer.md
  .claude/agents/auditor.md
  ... (one per role)
  .claude/agent-team.md (workflow manifest)

Tell me what to drop or change, otherwise I'll write the whole thing.
```

Wait for user confirmation. Use AskUserQuestion only if a specific binary decision needs resolving (e.g., "include researcher?"); otherwise present numbered text and let the user reply free-form.

### Step 5: write the files

For each picked role, write `.claude/agents/<name>.md`:

```markdown
---
name: <role-name>
description: <role's description from roles.yaml, lightly tuned if needed>
tools: <comma-separated allowlist from roles.yaml, or omit field entirely if empty>
model: <model from roles.yaml, or omit>
---

<tuned prompt_body from step 3>
```

**Tool allowlist format**: Claude Code subagent frontmatter accepts `tools:` as a comma-separated list. If `roles.yaml` says `tools: []` (empty array, meaning inherit all), OMIT the `tools` line entirely from the frontmatter. Do not write `tools: []`.

**Team-coordination tools (REQUIRED on any non-empty allowlist)**: every role with a `tools:` line MUST include `SendMessage, TaskUpdate, TaskList, TaskGet`. Without these, the spawned agent renders reports in its pane but cannot transmit them to team-lead, claim/complete tasks, or respond to `shutdown_request`. The role library at `roles.yaml` already includes them on every non-empty allowlist; verify they survived any prompt-body or schema-tuning edits you make in Step 3.

**Frontmatter MUST be single-line for `description`** (multi-line YAML breaks Claude Code's parser per the `dot-ai-skills` skill).

**Model MUST be auto-mode-capable (never `haiku`)**: auto-mode (the bias-to-act permission mode that lets teammates complete shared-system writes like a release push without a manual confirmation round-trip) is gated by the Claude Code docs to **Sonnet 4.6, Opus 4.6, or Opus 4.7 only**. Haiku and Sonnet 4.5 are explicitly unsupported, so a teammate on those models cannot participate in auto-mode and falls back to ask-for-everything, stalling autonomous flow. Use `model: sonnet` (the alias resolves to Sonnet 4.6) for every role by default; a repo MAY bump heavier roles (coder/reviewer/auditor) to `opus`. Do NOT pin `haiku` for any role, including release. Note (per the docs): a subagent's frontmatter `permissionMode` is ignored; its actions are classified under the parent session's rules, but only if the subagent's model is itself auto-mode-capable, which is why the model choice (not a mode flag) is the lever here.

Write `.claude/agent-team.md` as the workflow manifest:

```markdown
# Agent team workflow for <repo-name>

Generated <date> by the `agent-team` skill.

## Team roster

| Role | Subagent type | Model | Tools |
|------|---------------|-------|-------|
| coder | coder | sonnet | (inherit) |
| reviewer | reviewer | sonnet | Bash, Read, Grep, Glob, WebFetch |
| ... | | | |

## Orchestrator workflow

You (the team lead) NEVER do implementation, review, or audit work yourself.
You coordinate the team via TeamCreate + Agent (with team_name + name +
subagent_type) + SendMessage + TaskUpdate.

Default flow for a typical task:
1. Spawn coder with the full task context. The coder runs `<test-command>`
   before reporting done.
2. After coder reports done, spawn reviewer + auditor IN PARALLEL with
   coder's diff + report.
3. Resolve any blocking findings (route them back to coder via SendMessage).
4. <if release role exists> Before delegating to release, summarize what to
   verify end-to-end and STOP for user confirmation.
5. <if release role exists> On user OK, spawn release.

## Context handoff (CRITICAL)

Every teammate cold-starts with no memory of prior conversation or other
teammates' outputs. Whatever you write in the spawn `prompt:` is the entire
context they have, plus the body of `.claude/agents/<role>.md`.

Therefore every spawn prompt MUST include:
- File paths the teammate should read (the spec, the files being modified,
  CLAUDE.md/CONTRIBUTING.md when authoring rules matter)
- A summary of any prior teammate's findings when chaining workers
- The exact error message when retrying after a failure
- If context is long, write it to `.claude/agent-team-tasks/<slug>.md` and
  reference that path in the prompt instead of pasting inline

## Project signals

- Test command: <discovered>
- Lint command: <discovered>
- Release flow: <discovered path>
- Spec dir: <discovered path>
- Authoring rules: <CLAUDE.md / CONTRIBUTING.md paths>
- CI: <forgejo / github / gitlab / etc.>
- Slash commands the orchestrator may invoke between delegations:
  <list of /commands the lead can run itself>
```

Cite specific values, not "discovered".

After writing, suggest the user commit `.claude/agents/` and `.claude/agent-team.md` to the repo so the team definition is reproducible.

## Mode 2: update

Use when `/agent-team update` is invoked, or when an existing team feels out of date.

1. Read existing `.claude/agents/*.md` files and `.claude/agent-team.md`.
2. Re-run discovery (step 1 of init).
3. Diff: roles in library that match repo signals but missing from `.claude/agents/`, OR roles present but whose `triggers_on` no longer match (project no longer has tests, release flow removed, etc.).
4. Present the diff to the user as a numbered proposal (additions / removals / prompt-body updates).
5. On confirmation, apply targeted edits. Preserve any manual customizations the user made (e.g. extra paragraphs in a `prompt_body`) by merging rather than overwriting — read existing content, identify which parts came from the library and which are manual, only touch the library parts.

## Mode 3: run

Use when `/agent-team <task description>` is invoked with a non-keyword first argument.

### Step 1: precheck

- Confirm `.claude/agents/` exists. If not, suggest running `/agent-team init` first.
- Confirm `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`.
- Read `.claude/agent-team.md` for the workflow + project signals.

### Step 2: TeamCreate + plan tasks

Call `TeamCreate({team_name: "<repo-name>-<short-slug>", agent_type: "orchestrator", description: "<task summary>"})`.

Create team-level tasks via TaskCreate:
- Task #1: implementation (owner: coder)
- Task #2: review (owner: reviewer, blockedBy: #1)
- Task #3: audit (owner: auditor, blockedBy: #1)
- Task #4: release (owner: release, blockedBy: #2 + #3, user-gated) - only if release role exists

### Step 3: spawn teammates

Spawn each teammate in parallel via Agent calls in a single message:

```
Agent({
  team_name: "<team>",
  name: "coder",
  subagent_type: "coder",
  prompt: "<task-specific cold-start prompt>"
})
```

For `coder`, the prompt includes the full task description plus paths to read.

For `reviewer` and `auditor` (which depend on coder's output), the prompt is "stand by, prime your context by reading <PRD/CLAUDE.md/CONTRIBUTING.md>, then go idle. Wait for the team lead to send the diff/files to review/audit."

For `release`, do NOT spawn at start; spawn only after user confirms post-audit.

### Step 4: drive the flow

- Wait for coder's completion message via the automatic mailbox notifications (do NOT poll).
- On coder done: SendMessage to reviewer and auditor with the diff summary, file paths changed, and the coder's report. They claim their tasks and report findings.
- On reviewer + auditor both done: synthesize findings for the user. If any blocking finding, route back to coder via SendMessage.
- Before release (if applicable): present an end-to-end verification summary and STOP. Ask the user to confirm before spawning the release teammate.

### Step 5: cleanup

When the task is complete and the user is done, do NOT send `shutdown_request` blindly. Verify each teammate is at a clean stop boundary first.

#### Pre-shutdown checks (mandatory before SendMessage shutdown_request)

1. **Task-ownership check**: Run TaskList. If the teammate owns any task in `in_progress` status, they may be mid-work. Investigate before shutting down.

2. **Pane-activity check**: Capture the teammate's tmux pane and look for the running indicator:

```bash
PANE_ID=$(jq -r '.members[] | select(.name=="<teammate>") | .tmuxPaneId' ~/.claude/teams/<team>/config.json)
tmux capture-pane -p -t "$PANE_ID" 2>/dev/null | tail -30
```

Interpret the output:
- **`✽ Nucleating…` or `✻ Cooked for Ns`**: actively processing. Likely reading your last inbox message or executing tool calls. Look at the scrollback above to identify what they're doing.
- **Idle `❯` prompt with no spinner**: ready for shutdown.
- **Mid-shell-command output without a returned prompt**: a Bash invocation is in flight; wait for it to finish.

3. **Scrollback inspection**: capture with `-S -50` for more context. Look for recent edits, uncommitted local state, in-flight git pull/rebase, or tool calls without rendered results.

#### If the teammate is mid-work

Do NOT send `shutdown_request` directly. SendMessage a plain question instead: "we're stopping today; what's your cleanest stopping point from where you are?" Let the teammate propose the stop boundary. Valid responses include "finish current sub-step then stop", "current state is clean, send shutdown when ready", or "rollback needed first". Give them the agency to choose; their work product is what's at risk.

**Anti-pattern**: send `shutdown_request` without checking, then send a corrective "wait, are you OK?" message later. This burns inbox slots, confuses the teammate, and forces them to reconcile a conflicting protocol signal with the actual state.

#### After verification

Send `{type: "shutdown_request", reason: "<reason>"}` via SendMessage. Wait for `shutdown_response approve: true`. After all teammates confirm, call `TeamDelete`. Do NOT call TeamDelete with active teammates; it will fail.

#### Pane-capture caveat

`tmux capture-pane` shows scrollback, NOT only what the teammate is doing *right now*. A recent investigation in the scrollback might have already concluded; the only signal of *current* activity is the running indicator in the statusline. If you see Bash output for an action in the scrollback, assume that action is **already done** unless the statusline shows active processing AND the prompt hasn't returned yet.

### Step 6: run-mode hotfixes (role-file edits + slot collisions)

Run-mode normally assumes `.claude/agents/*.md` is stable. Two situations break that assumption and require team-lead action mid-run:

**A. Role-file hotfix when a teammate reports a structural defect.**

If a spawned teammate reports a structural problem with its own role file (missing tool in the allowlist, broken frontmatter, contradictory instructions), the team-lead MAY patch the role file in-place rather than aborting the run. Procedure:

1. Confirm the defect by reading the affected role file. A teammate's self-report is necessary but not sufficient; verify before editing.
2. Propose the fix to the user via `AskUserQuestion` with the minimal change as the recommended option and 1-2 alternatives (e.g., "workaround via files", "remove the `tools:` line entirely"). Skip the question only if the user has pre-authorized hotfixes in durable instructions.
3. Apply the patch (`Edit` on `.claude/agents/<role>.md`). Keep the change minimal: add the missing tool, fix the broken YAML, narrow the contradictory instruction. Do NOT rewrite the role wholesale; that's `/agent-team update` work.
4. Respawn the affected teammate (see slot-collision handling below). The live teammate's tool set is frozen at spawn time; the patched file only takes effect on the next spawn.
5. After the run completes, decide whether the hotfix should be backported into the role library at `~/.claude/commands/dot-ai-agent-team/roles.yaml` and propagated via `/agent-team update`. Flag this to the user; the team-lead does NOT edit the role library directly.

Out of scope for hotfixes: adding new roles, removing roles, changing a role's responsibilities, changing `model:`. Those are `/agent-team init`/`update` work.

**B. Slot-collision handling when respawning a teammate.**

The team config (`~/.claude/teams/<team>/config.json`) keeps member entries indefinitely; killing a teammate's pane sets `isActive: false` but does NOT free the name slot. A subsequent `Agent` spawn with the same `name:` and `team_name:` produces a new agent with a `-N` suffix (e.g., `reviewer` becomes `reviewer-2` on first respawn, `reviewer-3` on the next). Two implications:

- The live agent's NAME (for `SendMessage` targeting and `TaskUpdate` ownership) is the suffixed form. Address them as `reviewer-2`, not `reviewer`. The skill text + brief prompts must use the live name.
- The stale `reviewer` entry with `isActive: false` is harmless but clutters the roster. Optional cleanup: edit the config to remove the stale members before respawning, OR accept the suffix and move on. Do NOT call `TeamDelete` to "reset" the team mid-run; that nukes the task list and any other live members.

If the pane is alive but the agent is wedged (responded to `shutdown_request` with plain text instead of the protocol response, often because the tool allowlist excludes `SendMessage`), kill the pane directly with `tmux kill-pane -t <pane-id>`. Then respawn (accepting the `-N` suffix) with the patched role file.

## Context recycling for long-running teammates

Each teammate is a full Claude Code session with its own context window (1M for Opus 4.7, smaller for Sonnet/Haiku). Over a multi-track session, the heaviest worker (usually `coder`) accumulates context fast and starts paying prompt-cache penalties. The lead should actively recycle teammates at clean task boundaries.

### Monitoring teammate context

Each teammate runs in a tmux pane recorded at `~/.claude/teams/<team>/config.json#members[].tmuxPaneId`. Capture the live statusline:

```bash
PANE_ID=$(jq -r '.members[] | select(.name=="coder") | .tmuxPaneId' ~/.claude/teams/<team>/config.json)
tmux capture-pane -p -t "$PANE_ID" 2>/dev/null | grep -E '% of [0-9]+k'
```

Output: `▰▰▰▱▱▱▱ 51% of 1000k` — the live context budget. Check before dispatching a new task to that teammate.

### When to recycle (heuristic)

Recycle when **both** conditions hold:
- The current task has a structured wrap-up report from the teammate, AND everything that report references lives in the file system (commits, checkpoint files, PRD edits) rather than only in the teammate's working memory.
- The next task is logically independent: no shared file context, no follow-up findings from the prior task that aren't already documented.

Force-recycle (regardless of coupling) when:
- Context >85%. Prompt cache pressure compounds and quality drops.

Skip recycle when:
- Mid-task (never recycle).
- Next task tightly references prior task's working memory (debugging the same code, iterating on the same diff).
- Context <60% AND next task is in the same logical track (e.g., subsequent batches of a fan-out where the migration pattern is the carried context).
- Only one more task remains before team shutdown (no payback for the recycle cost).

### Recycle procedure

1. **Teammate writes a checkpoint**. Send a SendMessage asking the teammate to write `.claude/agent-team-tasks/<slug>-checkpoint.md` covering: files changed (full paths + commit SHAs), open questions, anything the next session of this role would need to know. The checkpoint is the only carrier of historical context across the recycle boundary.

2. **Shutdown**. Send `SendMessage({to: "<teammate>", message: {type: "shutdown_request", reason: "Recycle for context budget"}})`. Wait for `shutdown_response` with `approve: true`.

3. **Respawn**. Call Agent with the same `team_name`, `name`, `subagent_type`, and a cold-start prompt that references the checkpoint:

   ```
   Agent({
     team_name: "<team>",
     name: "<role>",
     subagent_type: "<role>",
     prompt: "Cold-start. Read .claude/agent-team-tasks/<slug>-checkpoint.md for prior context. Then: <new task>."
   })
   ```

The respawned teammate starts fresh; the checkpoint is the bridge.

### Anti-patterns

- **"Clear as often as possible" is wrong.** Each recycle costs a cold-start prompt + checkpoint-write effort + risk of losing context that wasn't externalized. Recycle at *clean task boundaries* only.
- **Recycling without a checkpoint** orphans whatever the teammate knew that wasn't in the file system.
- **Recycling mid-task** loses working state and forces re-discovery.
- **Recycling reviewer/auditor between dispatches** is usually wasteful — they're typically dispatched once per task they're reviewing, finish their report, and idle. Their context stays low. Coder is the one to watch.

### Lead's own context

The lead's context grows from teammate wrap-up reports too. The lead cannot self-recycle without losing the team. If lead context >70%, consider asking teammates to write more terse reports referencing files rather than pasting content inline, and prune lead-side conversation by summarizing into a CLAUDE.md or memory file before context fills.

## PRD-task transitions: fresh team per task

The within-task recycling above is for one teammate at a sub-task boundary. PRD-task transitions are coarser: when team-lead is asked to start a new PRD task (`/dot-ai-prd-next`, `/prd-start`, or any natural-language pickup of a new scope), the default is **recycle the entire team**, not reuse it. PRD-task boundaries are the cleanest recycle point in the workflow; primed context from the prior task is rarely load-bearing for the next task and carries scope-contamination risk.

Sequence:

1. **Analyze without dispatching.** Read the PRD, identify the next task, present the recommendation. The team stays dormant: no spawns, no SendMessage, no role-file edits.
2. **Wait for user acceptance.** Do NOT spawn anything until the user confirms the chosen task. Skipping this step risks priming teammates on a scope the user will redirect.
3. **On acceptance, gracefully shutdown the existing team.** Follow the Mode 3 Step 5 cleanup procedure: pre-shutdown checks (task ownership + pane activity), `SendMessage shutdown_request` + wait for `shutdown_response approve:true`, `TeamDelete`. Wedged teammates (no `SendMessage` in their allowlist) get `tmux kill-pane`. Mid-work teammates mean the prior task wasn't actually done; resolve before transitioning.
4. **TeamCreate + spawn fresh.** A new `team_name` (or reusing the same one if no stale member slots remain) avoids the `-N` suffix collision documented in Step 6 above.
5. **Run the task** per Mode 3 normal flow.

Exception: if the user explicitly wants the existing team kept alive across the transition (the next task is a tight follow-up on the same diff, primed context is directly reusable, no scope drift), skip the shutdown. But this is the exception; the default is recycle.

## Role library reference

The full role library is in `./roles.yaml`. Read it during init/update to see the canonical role descriptions, default tool allowlists, and `triggers_on` patterns. The library may evolve over time; the skill always reads it fresh.

## Gotchas

- **Team config is global**, not per-repo. Multiple repos can each have their own `.claude/agents/`, but only one team can be active at a time across the whole Claude Code instance. If a team is already running for a different repo, ask the user to clean it up first.
- **Single-line description in `.claude/agents/<role>.md`**: multi-line YAML (`>-`, `|`) breaks Claude Code's parser. Same rule as dot-ai skills (per `dot-ai-skills`).
- **`tools: []` field**: omit entirely if inheriting. Do not write an empty array.
- **Team-coordination tools on every non-empty `tools:` allowlist**: include `SendMessage, TaskUpdate, TaskList, TaskGet`. The role library enforces this; check survives any prompt-body or schema-tuning edits. A teammate spawned without these cannot report findings, claim/complete tasks, or respond to `shutdown_request`, even though its `prompt_body` says "Report via SendMessage". Symptom on first surface: teammate renders the report in its pane and goes idle; lead has to scrape and apply the hotfix in Step 6.A.
- **`subagent_type` matches the agent's name**, not its filename. The `name:` frontmatter field is authoritative.
- **Never pin `model: haiku`** (or Sonnet 4.5) for any role. Auto-mode is docs-gated to Sonnet 4.6 / Opus 4.6 / Opus 4.7; a haiku teammate cannot do auto-mode and stalls on every shared-system write (e.g. a release tag push needs a manual confirmation round-trip). Default all roles to `sonnet`; bump to `opus` for heavier reasoning. See the Step 5 model note for the full rationale.
- **Don't add `Co-Authored-By:` trailers** to any commits the release teammate makes (per the user's global instruction in `~/.claude/CLAUDE.md`).
- **Avoid em dashes (—)** in all generated prompt bodies and workflow docs. Use commas, colons, or parentheses.
- **Idle is normal**: teammates go idle after every turn. Do not interpret idle as "done" or "stuck". Only act when a teammate sends a message or completes a task.
- **Tasks vs SendMessage**: use TaskUpdate to mark progress (shared task list); use SendMessage for human-readable communication. Do not send structured JSON status payloads via SendMessage.

## Examples

### Init for a fresh repo

```
User: /agent-team init
Claude: [probes repo, finds Cargo.toml + tests/ + docs/ + .github/workflows/release.yml]
       Proposed team for myproject:
       1. coder (sonnet) - will run `cargo test` before reporting done.
       2. reviewer (sonnet) - read-only.
       3. auditor (sonnet) - public repo on github; no secret scanner in CI (consider gitleaks).
       4. tester (sonnet) - cargo test framework discovered in tests/.
       5. release (sonnet) - .github/workflows/release.yml present; uses cargo-release.

       Files I would write: .claude/agents/{coder,reviewer,auditor,tester,release}.md + .claude/agent-team.md.

       Tell me what to drop, otherwise I'll write the whole thing.
User: ok
Claude: [writes 6 files, confirms]
```

### Run a task

```
User: /agent-team implement the new --json output flag
Claude: [reads .claude/agent-team.md, TeamCreate, spawns coder with the task,
        spawns reviewer + auditor in standby mode, waits]
        Team spawned. Coder is working on the --json flag. Reviewer + auditor
        primed and standing by.
[... mailbox notifications drive the flow ...]
        Coder done; reviewer + auditor dispatched on the diff.
        Reviewer: 1 non-blocking finding (consider adding a test). Auditor: clean.
        Summary for end-to-end verification: <points>. Want me to proceed with release?
User: yes
Claude: [spawns release teammate, drives tag/push, reports]
```

### Update after project change

```
User: /agent-team update
Claude: [re-probes; finds new docs/ site (mkdocs.yml just added) and no longer-present .github/workflows/release.yml]
        Proposed updates:
        + Add documenter role (mkdocs.yml + docs/ now present)
        - Remove release role (release workflow gone)
        ~ Update auditor's prompt_body (removed CI secret-scanner reference)

        Apply?
User: yes, but keep the release role (I'll add a release flow back next week)
Claude: [adds documenter, updates auditor, leaves release in place]
```

## Next steps

After this skill writes `.claude/agents/` for a repo, the team is reusable by any Claude Code session: `/agent-team <task>` or natural-language ("spin up the team to ..."). The lead reads `.claude/agent-team.md` to know the workflow.

Consider also installing the [SessionStart hook](https://code.claude.com/docs/en/agent-teams) to enable team auto-cleanup between sessions if a team gets orphaned.
