# Features - Full Reference

Comprehensive list of every feature the pipeline ships. The top-level `README.md` only highlights the 5-7 most important; this file is the complete catalog.

## Core Pipeline

### 8-Phase Orchestration (0-7)

```
Phase 0: Init      Project selection, branch setup, identity, worktree
Phase 1: Analysis  Stack detection, codebase exploration (parallel Explore agents)
Phase 2: Planning  Task decomposition, architecture review, user approval
Phase 3: Dev       TDD cycle: test → code → build (Sonnet)
Phase 4: Review    Deterministic gates + parallel AI review + Fable triage
                   (Claude Code: Fable + Sonnet · Copilot CLI: GPT-5.4 + Opus + Sonnet)
Phase 5: Test      Optional manual testing + on-demand device audits
Phase 6: Commit    Git commit, push, PR with default reviewers + draft/ready prompt
Phase 7: Report   External: Jira comment · Wiki + Figma screenshots · Confluence
                   Internal: agent-log.md + Quality & Metrics + knowledge + memory
```

Each phase reads its own spec file under `pipeline/multi-agent-refs/phases/phase-N-*.md` - lazy-loaded so the orchestrator only pays the token cost for the phase it's currently in.

### Modifier Flags (orthogonal, combinable)

| Flag        | Effect                                                                              |
| ----------- | ----------------------------------------------------------------------------------- |
| `autopilot` | Skip all confirmation prompts; still fails safe on review blockers + build retries. |
| `--local`   | No worktree - works directly in `$PROJECT_ROOT` on a local branch.                  |

Depth is not a flag. `/multi-agent` and `/multi-agent:local` ask Full or Short at Phase 0 Step 7.5, recommending from the detected `taskType`; Short strips to Init → Dev(Opus self-contained) → Review → Test → Commit → Report. Autopilot never asks and always runs Full - "fast plus unattended" was removed in v16.0.0, because something has to choose when nobody is asked and unattended is the worst place to drop analysis and planning.

### Outside a Pipeline Run

The install is not only useful while `/multi-agent` is running. `rules/outside-the-pipeline.md` loads with every session and announces three things a plain conversation would otherwise not know it had:

- **Onboarded service credentials.** Resolve the logical name through `credential-store.sh` and read the issue, page or log. Writes route through the pipeline commands, which carry the rules that make them safe - issues are never auto-closed, PR bodies use `Ref:`, outward prose goes through the humanizer.
- **The stack skills enabled for this repo.** Each toolkit's own `index` skill routes. The pipeline reads the effective `enabledPlugins` rather than keeping a stack table, so a seventh toolkit needs no code change.
- **The `multi-agent-toolkit` MCP.** 83 tools for a running app.

Uninstall preserves the whole layer - tokens, the reader that opens them, the mapping that names them, the MCP registration. It is 1.5 kB of always-loaded text; the detail lives in a ref that loads on demand, and a gate keeps both under a ceiling because every byte there is paid by every session.

### Stack Auto-Detection

| Platform       | Detection                                    | Guide Loaded             |
| -------------- | -------------------------------------------- | ------------------------ |
| iOS/Swift      | `.xcodeproj`, `Package.swift`                | `refs/swiftui-guide.md`  |
| Android/Kotlin | `build.gradle[.kts]`                         | `refs/android-guide.md`  |
| Backend        | `requirements.txt`, `package.json`, `go.mod` | `refs/backend-guide.md`  |
| Frontend       | `package.json` + framework detection         | `refs/frontend-guide.md` |
| Docker         | `Dockerfile`, `docker-compose.yml`           | `refs/backend-guide.md`  |

Build commands, test runners, lint tools, and review focus areas all adapt to the detected stack.

### Stack Selection (marketplace plugins)

Stack skill sets ship as versioned plugins in the `multi-agent-plugins` marketplace. Selecting a stack enables the matching plugin(s) in the current repo's `.claude/settings.json` `enabledPlugins` - no skill copying, no session restart tricks, no directory shuffling. Two toolkits are always enabled alongside the stack plugin because neither is stack-specific: `ai-common-toolkit` (accessibility audit, humanizer, Firebase) and `ai-analyst-toolkit` (GitHub and package-registry evidence, community signal).

```bash
/multi-agent:stack ios         # ai-ios-toolkit (SwiftUI, Xcode, HIG)
/multi-agent:stack android     # ai-android-toolkit (Compose, Gradle, Hilt)
/multi-agent:stack mobile      # iOS + Android combined
/multi-agent:stack backend     # ai-backend-toolkit (spec-driven APIs)
/multi-agent:stack frontend    # ai-frontend-toolkit (React/TSX)
/multi-agent:stack fullstack   # backend + frontend
/multi-agent:stack all         # every stack plugin
```

### Task Type Detection

Phase 0 Step 9 classifies every task before Phase 1 starts. Deterministic priority order: Figma URL → instruction file path → git diff heuristic → Jira issue type → branch name → description keywords → user prompt (autopilot defaults to `feature`).

Result persisted to `agent-state.taskType`:

| Type        | Downstream effects                                                            |
| ----------- | ----------------------------------------------------------------------------- |
| `component` | Phase 3 dispatches to the marketplace component plugin (create-component) with SubPhase reporting |
| `bugfix`    | Phase 4 emphasizes test coverage + regression; Phase 6 uses `fix(...)` prefix |
| `feature`   | Standard TDD flow; Phase 6 uses `feat(...)` prefix                            |
| `refactor`  | Phase 4 emphasizes behavior preservation; Phase 6 uses `refactor(...)` prefix |
| `chore`     | Lightweight flow; Phase 6 uses `chore(...)` prefix                            |

### SubPhase Convention

When a specialized skill takes over a main pipeline phase, progress is reported as SubPhases (e.g. `SubPhase 3.0: Init`, `SubPhase 3.1: Gather`). The top-level pipeline stays fixed at 8 phases (0-7) - specialized work slots into its parent phase without inflating the count.

## PR & Review Flow

### Default Reviewers

- **Bitbucket**: Fetches via `/rest/default-reviewers/1.0/`. Every PUT must re-send `reviewers`, `fromRef`, `toRef`, `draft` (regression guarded by smoke test).
- **GitHub**: Honors `CODEOWNERS` + falls back to `prefs.projects[].githubDefaultReviewers`.
- PR author always filtered out (Bitbucket: 409, GitHub: GraphQL error).

### Draft vs Ready Prompt

Phase 6 asks `DRAFT or READY?` before creating the PR and persists the choice in `prefs.projects[].defaultPrMode`.

- Bitbucket: `draft: true` flag (DC 8.x+) with `[DRAFT]` title fallback for older servers.
- GitHub: `gh pr create --draft` + `gh pr ready` for promotion.

### `channels` Command

Multi-channel reporter - Phase 7 delegates to it, and it's also invocable post-hoc for fixes closed outside the pipeline:

```bash
/multi-agent:channels                              # current branch, current PR
/multi-agent:channels https://jira.company/browse/PROJ-12345
/multi-agent:channels #42 --channels pr            # PR only
/multi-agent:channels --message "manual fix description"
/multi-agent:channels ABC-1234 --channels jira,confluence --content test
```

Multi-select **channels** (Jira / Confluence / Wiki / PR description) × multi-select **content** (normal analysis / test scenarios / auto-diff summary / manual note). Each body runs through the humanizer skill per-channel. Bitbucket PR updates use the reviewer-preserving PUT pattern (title + description + reviewers + fromRef + toRef + version mandatory). Replaces the earlier `enrich` command - all its capabilities (diff auto-summarize, manual mode, reviewer-preserving) are preserved; Confluence + Wiki are new.

### Body Preservation Contract (smoke-verified)

Every external-system body (PR description, Jira comment, GitHub issue) uses `jq -n --rawfile body body.md '{description: $body}'` → `curl --data-binary @payload.json`. No literal `\n` strings, no HTML entities (`&amp;`, `&lt;`, `&quot;`). UTF-8 preserved end-to-end. `scripts/smoke-add-detail.sh` runs 14 contract assertions.

### Issue Safety

Never auto-closes issues - uses `Ref: #N` / `Related: #N` / `See: PROJ-12345`, never `Closes` / `Fixes` / `Resolves`. Closure requires team review (configurable, typically 4 approvals).

## Review Quality

### Deterministic Gates (Phase 4 Step 1)

Cheap, objective checks run BEFORE any AI token is spent:

1. Build (acquires xcodebuild lock, isolated DerivedData per worktree)
2. Lint (SwiftLint / detekt / ruff / eslint - stack-dependent)
3. Tests pass
4. Secret scan

If any gate fails, fix first. Don't waste AI tokens reviewing broken code.

### CLI-Aware Parallel Review + Fable Triage (Phase 4 Steps 2-3)

| Reviewer   | Model               | Focus                             | Where it runs        |
| ---------- | ------------------- | --------------------------------- | -------------------- |
| Reviewer 1 | `claude-fable-5` (Claude Code) / `claude-opus-4-8` (Copilot CLI) | Deep security + architecture | Both CLIs |
| Reviewer 2 | `gpt-5.4`           | Edge cases, different perspective | **Copilot CLI only** |
| Reviewer 3 | `claude-sonnet-4-6` | Quality + correctness + naming    | Both CLIs            |

The reviewer set is **CLI-aware**: Claude Code dispatches 2 reviewers in parallel (Fable + Sonnet - GPT-5.4 is not available there); Copilot CLI dispatches all 3. Each returns structured JSON for deterministic aggregation. Cross-model diversity catches blind spots that any single model family would miss.

**Fable Triage** (Phase 4 Step 3, Opus on Copilot CLI): Evaluates merged raw findings against task scope. Classifies each as `accepted` (fix now), `deferred` (out of scope, log for later), or `rejected` (false positive / noise). Only triage-accepted blocking items loop back to Phase 3.

### Runtime Triage Validator

After triage returns, output is validated by `validate-triage.mjs`:

| Exit  | Meaning                                                      |
| ----- | ------------------------------------------------------------ |
| **0** | Valid and clean - act on triage output                       |
| **1** | Invalid structure - retry once, then fallback                |
| **2** | Over-rejection guard tripped - pause for human               |
| **3** | Contradiction auto-corrected - proceed with corrected output |

### Bidirectional Approved↔Blocking Auto-Correction

If triage returns `approved: false` but has no blocking items, the validator forces `approved: true`. Conversely, if `approved: true` but blocking items exist, it forces `approved: false`. Hardened with an `if`/`then` constraint in the schema itself.

### Verify-by-Test Triage (Phase 4 Step 3.7, opt-in)

A triage verdict is a judgment call; a failing repro test is proof. When `prefs.global.verifyByTest.enabled` is on, one verifier agent (default Sonnet) writes a minimal repro test per accepted blocking finding (cap: `maxFindings`=3) and runs only that test. Fails as predicted -> finding confirmed, the repro test becomes the Phase 3 rework RED test. Passes under `evidence-gate.mjs` -> finding downgraded to `deferred`. Compile error / timeout -> `inconclusive`, judgment stands. Timeout-bounded, never blocks. Full spec: `refs/features/verify-by-test.md`.

### Immutable-Test Rule + `test_lines_removed` Signal

Existing tests are immutable during a task: deleting, renaming, or weakening an assertion to reach green is a violation (`refs/rules.md`, Phase 3 GREEN step). A test changes only when the task changes the spec it encodes, named in the commit body. Deterministic backstop: `diff-risk-score.mjs` emits `test_lines_removed` (w=3.0) for any test-classified file whose diff removes more lines than it adds.

### Update Check at Run Start

Phase 0 Step 0.6. Once per `ttlHours` window (cached, 3s-bounded curl to the npm registry), the installed version is compared against two dist-tags.

**`latest` - automatic**, since v16.5.0. `prefs.global.updateCheck.autoUpdate` defaults to `true`: a newer version is installed before the run starts, in interactive modes and autopilot alike, and the run continues. Set `autoUpdate: false` to be asked once per `ttlHours` instead, or `updateCheck.enabled: false` to silence the check (neither disables the required-version floor).

**`required` - blocking** (v15.14.0+). Most releases do not publish this tag and nothing changes for them. A release that changed a contract a run depends on is promoted with `npm dist-tag add <pkg>@<version> required`, and an install below that floor is not behind, it is wrong: `require-supported-version.sh` exits 3, the run halts, `/multi-agent:update` runs, and the user re-issues the command on the new version rather than continuing on docs already loaded from the old one. Interactive and autopilot behave identically. The gate fails open on every undeterminable answer (offline, blocked registry, no tag), `updateCheck.enabled: false` does not disable it, and the single override is the env var `MULTI_AGENT_ALLOW_OUTDATED=1`, which is logged in the run record. Exemptions: `update`, `setup`, `uninstall`, `help`, `status`, `log`, `search`, `routines`, `forget`, `language`.

### Structured Handoff Blocks

Every phase transition appends a `## Handoff` block (Done / Remaining / Decisions / Open findings / Next) to `agent-log.md` - orchestrator-written from existing state, no LLM call. `/multi-agent:resume` and post-`/compact` re-grounding read the latest handoff first, so long runs re-enter from durable artifacts instead of conversation memory (fresh-context discipline from Anthropic's long-running-agent harness guidance).

### Accessibility Code Review (Phase 4 Step 1.5)

If changes include UI files, reviewers check for:

- Missing `.accessibilityLabel` / `contentDescription` on interactive elements (→ blocking)
- Small tap targets (<44×44pt iOS / <48×48dp Android) (→ important)
- Missing identifiers + Dynamic Type support (→ suggestion)

Pure code analysis - no simulator needed. Device-level audits run in Phase 5 when requested.

### Status Enforcement

Phase 3 treats the issue-tracker status update as a required step with a post-mutation verify step that re-reads the field and retries once on silent `VALIDATION` failures (e.g. stale Projects V2 option IDs after a board rebuild).

## Safety & Hygiene

- **Pre-Commit Secret Detection** (12 patterns): `PreToolUse` hook scans staged files for API keys/tokens, AWS access keys, private keys, `.env` files, service account JSON. Commit **blocked** if found.
- **Build Queue**: All `xcodebuild` calls acquire a lock. Each worktree uses own `-derivedDataPath`. Stale locks auto-clean after 15 min. Non-Xcode builds don't need the lock.
- **Context Management**: `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=65` - compaction at 65% usage (prevents degradation in 8-phase sessions).
- **3-Iteration Hard Kill**: Any retry loop stops after 3 attempts, then pauses for user. No infinite loops.

## Testing & Quality

### Schema-Validated State

All critical state files are schema-validated at read and write time:

- `agent-state.schema.json` - validates `$HOME/.claude/logs/multi-agent/.../agent-state.json`
- `prefs.schema.json` - validates `$HOME/.claude/multi-agent-preferences.json`
- `triage-output.schema.json` - validates triage output (contradiction `if`/`then` constraint built in)

### Smoke Test Suites

100+ suites, auto-discovered from `smoke-*.sh` (no hardcoded list). Representative: add-detail (body-preservation assertions), review-triage (validator exit codes), prefs (schema round-trip), state (agent-state lifecycle), metrics (telemetry emission), sync (instruction parity), secret-scan (hook patterns), phase-banner (terminal UI), token-budget (per-phase limits), phase-tracker (progress tracking).

### Adversarial Eval Fixtures

Adversarial fixtures that test triage resilience against adversarial reviewer output: over-rejection, hallucinated findings, contradictions, invalid JSON, schema violations, duplicate findings, scope creep, empty results, timeout simulation, and combined edge cases.

### Sync Parity Check

Detects drift between Claude Code instructions (`~/.claude/commands/multi-agent/SKILL.md`), Copilot CLI instructions (`~/.copilot/copilot-instructions.md`), and the repo's pipeline spec files. Reports discrepancies during Phase 0 Init.

### Token Budget Enforcement

Per-phase token budgets prevent runaway sessions. If a phase exceeds its budget, the pipeline pauses and offers: continue (extend budget), skip phase, or abort. Budgets are configurable in `prefs.global.tokenBudgets`.

## Telemetry & Observability

- **Pipeline Metrics**: Structured metrics to `metrics.jsonl` via `log-metric.sh`. Aggregated by `aggregate-metrics.mjs`.
- **Cost Telemetry**: Per-phase token cost tracking (`tokens_in`, `tokens_out`, `model`, `duration_ms`). Omitted fields handled gracefully.
- **Phase Tracker**: Cross-CLI visual progress (current phase, elapsed time, iteration count).
- **Phase Banner**: Terminal UI for phase transitions with Unicode box-drawing characters.
- **Per-task Cost Breakdown in agent-log.md**: Phase 7 appends a 4-column block (Phase · Model · Tokens in/out · Est. USD) to every run's `agent-log.md`. Sourced from `phase-tracker.sh tokens` accumulators × `cost-table.json` prices. Independent of the channels-side `reportContent.costSummary` toggle. The `LOG_METRIC_FORWARD_TO_TRACKER=1` env flag mirrors `tokens_in`/`tokens_out`/`model` from `log-metric.sh` into the tracker so JSONL metrics and the cost block stay in sync from one call site.

### Diff Risk Scoring

`pipeline/scripts/diff-risk-score.mjs` runs at Phase 4 Step 1.75 - before reviewer dispatch. Heuristic, deterministic, sub-second, no LLM. Top-N risk-ranked files inject into each reviewer's prompt as a `${PRIORITY_FILES}` block; reviewers read those files first but still review the entire diff.

Signals + weights: `security_path` ×3, `migration` ×4, `public_api` ×2, `no_test_change` ×2.5, `test_lines_removed` ×3 (test file shrinks - immutable-test backstop), `complexity_delta` ×1.5, `ui_critical` ×1.5, `loc_changed` ×1. Toggle via `prefs.global.diffRiskAdvisory` (default ON).

### Test Gap Detection

`pipeline/scripts/test-gap-scan.mjs` runs at Phase 5 Step 0. Walks the diff for newly added public symbols and reports those with no paired test. Stack-specific rules ship for iOS, Android, Python, Node.js. iOS Views and Android `@Composable` symbols default to `important`; other public API additions to `suggestion`. Optional gating via `prefs.testGap.blockingThreshold` - when set, the report becomes a Phase 4 rework finding once `important + blocking` count exceeds the threshold.

### Triage Memory

Per-repo append-only JSONL corpus at `~/.claude/memory/multi-agent/<repo-slug>/triage-corpus.jsonl`. Phase 7 ingests every triage output (idempotent), Phase 1 enriches the analysis with similar past tasks, Phase 4 triage attaches prior-art hits to each raw finding with an explicit bias hedge. Token-overlap recall, zero deps, Node-18-compatible. `/multi-agent:search "<text>" --semantic` routes the query to the corpus instead of agent-log grep. Toggle via `prefs.global.priorArtEnrichment.enabled` (default ON).

## Learning

### Knowledge Base (per project)

Incremental learning. Phase 7 captures architecture, patterns, gotchas, and decisions into `$HOME/.claude/knowledge/{project}/`. Phase 1 reads it on the next run. Token cost decreases over time as the base grows.

### Memory Capture (cross-session)

Pipeline learns behavioral signals (feedback corrections, project constraints, external references). Phase 7 saves, Phase 1 injects. Max 3 new memories per run. Merge-over-duplicate. Stale memories verified before use.

**What does NOT go in memory**: architecture, code patterns, build gotchas, design decisions - those belong in the knowledge base.

### Lesson Diagnosis (Reflexion)

Phase 4's lesson-memory loop records the causal root cause of each fix (`--diagnosis`), not just the outcome: the verbal "why" that prevents recurrence (Reflexion). `learnings-ledger.mjs brief` renders it as `(why: ...)` back into Phase 1 + triage on the next run, so the reason re-enters the loop, not only the symptom.

### Corpus Freshness Gate

Each triage-corpus row is stamped with the file's git `file_sha`; a query annotates `stale=true` when the file changed since the lesson was recorded, so lessons about code that has since moved on stop resurfacing.

### Learning Curve

`learning-curve.mjs` renders a time-bucketed trend over `metrics.jsonl` (first-pass clean rate, review cycles, rework per task, tokens per task, cache ratio) so a repo's runs can be shown getting better and cheaper over time. Flags: `--bucket=<days>`, `--since`, `--json`, `--markdown`.

## User-Defined Routines

Turn a recurring, project-specific job into a first-class `/multi-agent:<name>` command.

- **`/multi-agent:save`** distills candidate routines from the work just done this session (and named procedures in `~/.claude/CLAUDE.md`), offers them in a multi-select picker (pick one, combine several into one, or free-text a new one), and registers the chosen routine.
- **`/multi-agent:routines`** lists saved routines (in `outputLanguage`); **`/multi-agent:forget`** removes one (guarded: never touches a shipped command).
- Backed by `routine-registry.mjs`. Saved routines are `local-only: true` command dirs + a `prefs.global.routines` entry: preserved across `/multi-agent:update` by install snapshot/restore, never synced to the public repo, and never counted in the command inventory.

## Integrations

### Figma / Component Generation (dispatched to marketplace plugins)

Component + Figma-to-code work is no longer bundled in this repo. When Phase 0 classifies a task as `component`, Phase 3 dispatches it to the per-stack marketplace plugins (`ai-ios-toolkit` / `ai-android-toolkit` in the `multi-agent-plugins` marketplace) via the Skill tool. The plugin's component skill generates `{Name}Configuration.swift`, `{Name}View.swift`, `{Name}+Modifiers.swift`, `{Name}.figma.swift`, and `FIGMA.md` with a variant matrix, then runs a 14-item pre-commit checklist covering design tokens, accessibility, tests, and Code Connect.

The plugin's cross-cutting integration skills feed component detection + implementation when the design triggers them (content: form / price / ui-patterns; interaction: navigation / overlays / bottom-sheets). Each is native-SwiftUI-first and reads project specifics (token namespaces, component paths, UI systems) from `figma-config`, including the optional `ui.navigationSystem` / `ui.overlaySystem` / `ui.sheetSystem` hooks (absent -> stock SwiftUI), so the same capabilities work on any SwiftUI codebase. The plugin's evolve-component skill reconciles an existing component against current Figma (drift-heal) and additively extends it, behind a human gate.

### UI Bug Hunter + Audits

Automated visual testing and compliance audits via direct Bash (no MCP server dependency):

| Audit                 | When                | Command                      |
| --------------------- | ------------------- | ---------------------------- |
| iOS Accessibility     | Phase 5, on request | `swift ui-tree-dumper.swift` |
| Android Accessibility | Phase 5, on request | `adb shell uiautomator dump` |
| iOS Biometric         | Phase 5, auth flow  | `xcrun simctl keychain`      |
| Android Launch Time   | Phase 5, perf       | `adb shell am start -W`      |
| iOS Archive           | Phase 6, release    | `codesign`, `plutil`, `nm`   |
| Android APK           | Phase 6, release    | `aapt2`, `apksigner`         |

Audits are **on-demand** - triggered by user, never automatic.

### Jira + Confluence

- Phase 3: transition issue to `In Progress` (verified post-mutation).
- Phase 7: post analysis + test scenarios as Jira comment (Turkish by default, configurable).
- Phase 7 (optional): create Confluence page under chosen parent, cached per project.

### Keychain

Token registry maps logical names (`jira`, `bitbucket`, `github`, `confluence`) to Keychain item names. Tokens never land in a config file, never synced to the repo.

## Schemas & Validation

- `pipeline/schemas/agent-state.schema.json` - validates agent state lifecycle
- `pipeline/schemas/prefs.schema.json` - validates preferences
- `pipeline/schemas/triage-output.schema.json` - validates triage output (contradiction `if`/`then` constraint built in)

## File Layout

Each subcommand is its own directory: `commands/multi-agent/<name>/SKILL.md` → slash command; the dispatcher is `commands/multi-agent/SKILL.md`. The user-facing invocation `/multi-agent:<name>` is unchanged. Guides, phase specs, and rules live under `pipeline/multi-agent-refs/**` (kept out of `commands/` so they are not invocable as slash commands). Modifier flags and ops stay inline in the dispatcher SKILL.
