---
title: "Implement"
description: "Full-power feature implementation using parallel subagents for backend, frontend, testing, and security, with worktree isolation and quality verification in one workflow. Chains with /ork:cover for tests and /ork:verify for validation. Use when asked to build, add, create, scaffold, or set up a new feature, endpoint, component, or UI capability. Not for fixing a bug, reviewing, explaining, testing, or comparing existing code."
canonical: "https://orchestkit.yonyon.ai/docs/reference/skills/implement"
---

# Implement

Full-power feature implementation using parallel subagents for backend, frontend, testing, and security, with worktree isolation and quality verification in one workflow. Chains with /ork:cover for tests and /ork:verify for validation. Use when asked to build, add, create, scaffold, or set up a new feature, endpoint, component, or UI capability. Not for fixing a bug, reviewing, explaining, testing, or comparing existing code.

<span className="badge badge-blue">Command</span> <span className="badge badge-yellow">medium</span>

```bash title="Invoke"
/ork:implement
```

<ContextualSkillSidebar slug="implement" />

> **Implement** Full-power feature implementation using parallel subagents for backend, frontend, testing, and security, with worktree isolation and quality verification in one workflow. Chains with /ork:cover for tests and /ork:verify for validation. Use when asked to build, add, create, scaffold, or set up a new feature, endpoint, component, or UI capability.


# Implement Feature

Parallel subagent execution for feature implementation with scope control and reflection.

## Quick Start

```bash
/ork:implement user authentication
/ork:implement --model=opus real-time notifications
/ork:implement dashboard analytics
```

---

## Argument Resolution

```python
FEATURE_DESC = "$ARGUMENTS"  # Full argument string, e.g., "user authentication"
# $ARGUMENTS[0] is the first token, $ARGUMENTS[1] second, etc. (CC 2.1.59)

# Model override detection (CC 2.1.72)
MODEL_OVERRIDE = None
for token in "$ARGUMENTS".split():
    if token.startswith("--model="):
        MODEL_OVERRIDE = token.split("=", 1)[1]  # "opus", "sonnet", "haiku", "fable"
        FEATURE_DESC = FEATURE_DESC.replace(token, "").strip()
```

Pass `MODEL_OVERRIDE` to all Agent() calls via `model=MODEL_OVERRIDE` when set. Accepts symbolic names (`opus`, `sonnet`, `haiku`, `fable` on harnesses whose Agent tool lists it; note fable is premium API spend after 2026-07-12) or full IDs (`claude-opus-4-8`) per CC 2.1.74.

---

## Step -1: MCP Probe + Resume Check

**Run BEFORE any other step.** Detect available MCP servers and check for resumable state.

```python
# Probe MCPs (parallel — all in ONE message):
# memory is alwaysLoad in .mcp.json (CC 2.1.121+, #1541) — probe below kept as fallback for older CC:
ToolSearch(query="select:mcp__memory__search_nodes")
ToolSearch(query="select:mcp__context7__resolve-library-id")

Write(".claude/chain/capabilities.json", JSON.stringify({
  "memory": <true if found>,
  "context7": <true if found>,
  "timestamp": now()
}))

# Resume check:
Read(".claude/chain/state.json")
# If exists and skill == "implement":
#   Read last handoff (e.g., 04-architecture.json)
#   Skip to current_phase
#   "Resuming from Phase {N} — architecture decided in previous session"
# If not: write initial state
Write(".claude/chain/state.json", JSON.stringify({
  "skill": "implement", "feature": FEATURE_DESC,
  "current_phase": 1, "completed_phases": [],
  "capabilities": capabilities,
  "budget_remaining_pct": 100  // advisory; see Budget Awareness below
}))
```

### Batch Size Governance (large refactors)

For implementations touching **>10 files**, enforce max 5 files per agent batch, run tests between batches, commit green batches immediately, stop on red. Override via `--batch-size N`. Full rule: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/rules/batch-governance.md")`.

### Budget Awareness (Opus 5 task budgets, public beta)

Opus 5 exposes per-task token budgets. Until the CC side is GA, OrchestKit tracks an advisory `budget_remaining_pct` in `state.json` so long runs self-throttle. Update after each phase:

```python
# At end of every phase, estimate remaining budget:
pct = tokensAsContextPct(tokensUsedSoFar)  # from lib/context-window.ts
remaining = max(0, 100 - pct)
state["budget_remaining_pct"] = remaining
Write(".claude/chain/state.json", JSON.stringify(state))
```

Thresholds influence behavior:

| Remaining | Behavior |
|---|---|
| `> 50%` | Normal — all optional depth (devil's advocate, visual capture, deep exploration). |
| `20-50%` | Efficient — skip optional depth; keep core phases. Warn user once. |
| `&lt; 20%` | Conservation — finish current phase, emit a handoff with next steps, do not start new work. |

When CC's native task-budget API ships GA, replace the estimate with the real signal; the thresholds and behavior stay the same.

> Load: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/chain-patterns/references/checkpoint-resume.md")`

---

## Step -0.5: Assess Verdict Gate

If `.claude/chain/assess-verdict.json` exists with a `feature` matching this run and `verdict == "fail"` (composite &lt; the 5.5 `min_pass` in `$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/rubric.json`, or any dimension below its `min_blocker`), **BLOCK Phase 1**. Present each `blockers[]` entry (dimension, score, reason), then `AskUserQuestion` with plain label+description options (no `preview`):

1. **Fix blockers first (Recommended)** — address the blockers, re-run `/ork:assess`, then return here.
2. **Override and implement** — proceed anyway; record `"assess_gate": "overridden"` in `state.json` and carry the blockers into Phase 1 context.

Missing file or `verdict == "pass"` → no gate; continue to Step 0.

---

## Step 0: Effort-Aware Phase Scaling (CC 2.1.76; `xhigh` added in 2.1.111)

Read the `/effort` setting to scale implementation depth. The effort-aware context budgeting hook detects effort level automatically — adapt the phase plan accordingly:

| Effort Level | Phases Run | Agents | Token Budget |
|-------------|------------|--------|--------------|
| **low** | 1 (Discovery) → 5 (Implement) → 10 (Reflect) | 2 max | ~50K |
| **medium** | 1 → 2 → 5 → 7 (Scope Creep) → 10 | 3 max | ~150K |
| **high** (default) | All 10 phases | 4-7 | ~400K |
| **xhigh** (Opus 5, CC 2.1.111+) | All 10 phases + one additional healing iteration on test failures before escalating | 4-7 | ~550K |

> **Override:** Explicit user selection in Step 0 (e.g., "Plan first" or "Worktree") overrides `/effort` downscaling. If user requests full exploration, respect that regardless of effort level.

## Step 0a: Project Context Discovery

**BEFORE any work**, detect the project tier. This becomes the complexity ceiling for all patterns.

Scan codebase signals and classify into tiers 1-6 (Interview through Open Source). Each tier sets an architecture ceiling and determines which phases/agents to use.

Load tier details, workflow mapping, and orchestration mode: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/tier-classification.md")`

### Worktree Isolation (CC 2.1.49)

For features touching 5+ files, offer worktree isolation to prevent conflicts with the main working tree:

```python
AskUserQuestion(questions=[{
  "question": "Isolate this feature in a git worktree?",
  "header": "Isolation",
  "options": [
    {"label": "Yes — worktree (Recommended)", "description": "Creates isolated branch via EnterWorktree, merges back on completion"},
    {"label": "No — work in-place", "description": "Edit files directly in current branch"},
    {"label": "Plan first", "description": "Research and design in plan mode before writing code"}
  ],
  "multiSelect": false
}])
```

**If 'Plan first' selected:**

```python
# 1. Enter read-only plan mode
EnterPlanMode("Research and design: $ARGUMENTS")

# 2. Research phase — Read/Grep/Glob ONLY, no Write/Edit
#    - Read existing code in the target area
#    - Grep for related patterns, imports, dependencies
#    - Check tests, configs, and integration points
#    - If context7 available: query library docs

# 3. Design the plan — produce:
#    - File map: which files to create/modify
#    - Architecture decisions with rationale
#    - Task breakdown with acceptance criteria
#    - Risk assessment and edge cases

# 4. Exit plan mode — returns plan to user for approval
ExitPlanMode()

# 5. User reviews plan. If approved → continue to Phase 1 (Discovery)
#    with the plan as input. If rejected → revise or stop.
```

If worktree selected:
1. Call `EnterWorktree(name: "feat-\{slug\}")` to create isolated branch
2. All agents work in the worktree directory
3. On completion, merge back: `git checkout \{original-branch\} && git merge feat-\{slug\}`
4. If merge conflicts arise, present diff to user via `AskUserQuestion`

Load worktree details: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/worktree-isolation-mode.md")`

---

## Step 0b: Blast-Radius Clarification (ask "what" before "how")

Before Phase 1, resolve the unknowns whose answers would **change the architecture**, in blast-radius order — schema/migration → auth → API contract → perf/scale → cosmetics (last). Grep first, then `AskUserQuestion` one at a time (highest first, cap ~5, skip the obvious). Each answer becomes a row in a Decisions table written to `.claude/chain/decisions.json` and the PR body, feeding Phase 4 (Architecture) as constraints. Do NOT start Phase 1 with an unresolved schema/auth question; skip in `low` effort. Full protocol: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/blast-radius-clarification.md")`.

---

## Task Management (MANDATORY)

**BEFORE doing ANYTHING else, create tasks to track progress:**

```python
# 1. Create main task IMMEDIATELY
TaskCreate(
  subject="Implement: {feature}",
  description="Feature implementation with parallel subagents",
  activeForm="Implementing {feature}"
)

# 2. Create subtasks for each phase
TaskCreate(subject="Research best practices and docs", activeForm="Researching best practices")  # id=2
TaskCreate(subject="Micro-plan: scope, files, criteria", activeForm="Micro-planning")            # id=3
TaskCreate(subject="Architecture design (parallel agents)", activeForm="Designing architecture") # id=4
TaskCreate(subject="Implement and write tests", activeForm="Implementing code")                  # id=5
TaskCreate(subject="Integration verification", activeForm="Verifying integration")               # id=6
TaskCreate(subject="Scope creep check", activeForm="Checking scope creep")                       # id=7
TaskCreate(subject="E2E verification", activeForm="Running E2E verification")                    # id=8
TaskCreate(subject="Document and reflect", activeForm="Documenting decisions")                   # id=9

# 3. Set dependencies for sequential phases
TaskUpdate(taskId="3", addBlockedBy=["2"])  # Plan needs research
TaskUpdate(taskId="4", addBlockedBy=["3"])  # Architecture needs plan
TaskUpdate(taskId="5", addBlockedBy=["4"])  # Implementation needs architecture
TaskUpdate(taskId="6", addBlockedBy=["5"])  # Integration needs implementation
TaskUpdate(taskId="7", addBlockedBy=["6"])  # Scope creep needs integration
TaskUpdate(taskId="8", addBlockedBy=["7"])  # E2E needs scope check
TaskUpdate(taskId="9", addBlockedBy=["8"])  # Docs need E2E

# 4. Update status as you progress
TaskUpdate(taskId="2", status="in_progress")  # When starting
TaskUpdate(taskId="2", status="completed")    # When done — repeat for each subtask
```

---

## Workflow (10 Phases)

| Phase | Activities | Agents |
|-------|------------|--------|
| **1. Discovery** | Research best practices, Context7 docs, break into tasks | — |
| **2. Micro-Planning** | Detailed plan per task (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/micro-planning-guide.md`) | — |
| **3. Worktree** | Isolate in git worktree for 5+ file features (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/worktree-workflow.md`) | — |
| **4. Architecture** | 4 parallel background agents (+ event-driven-architect when event/CQRS/queue-shaped) | workflow-architect, backend-system-architect, frontend-ui-developer, llm-integrator |
| **5. Implementation + Tests** | Parallel agents, single-pass artifacts with mandatory tests | backend-system-architect, frontend-ui-developer, llm-integrator, test-generator |
| **6. Integration Verification** | Code review + real-service integration tests | backend, frontend, code-quality-reviewer, security-auditor |
| **7. Scope Creep** | Compare planned vs actual (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/scope-creep-detection.md`) | workflow-architect |
| **8. E2E Verification** | Browser + API E2E testing (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/e2e-verification.md`) | — |
| **9. Documentation** | Save decisions to memory graph | — |
| **10. Reflection** | Lessons learned, estimation accuracy | workflow-architect |

Load agent prompts: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/agent-phases.md")`

For Agent Teams mode: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/agent-teams-phases.md")`
> **Nested delegation (CC 2.1.172+):** Phase 4-6 specialist agents MAY be instructed to delegate a bounded sub-problem to their own declared sub-agents (e.g. backend-system-architect → database-engineer for schema design) instead of doing everything inline. Keep chains ≤ 3 levels deep; when sub-tasks are independent, flatten to parallel dispatch from this orchestrator. See chain-patterns Pattern 9 (CC 2.1.172+).

### Phase Handoffs (CC 2.1.71)

Write handoff JSON after major phases. See `chain-patterns` skill for schema.

| After Phase | Handoff File | Key Outputs |
|-------------|-------------|-------------|
| 1. Discovery | `01-discovery.json` | Best practices, library docs, task breakdown |
| 2. Micro-Plan | `02-plan.json` | File map, acceptance criteria per task |
| 4. Architecture | `04-architecture.json` | Decisions, patterns chosen, agent results |
| 5. Implementation | `05-implementation.json` | Files created/modified, test results |
| 7. Scope Creep | `07-scope.json` | Planned vs actual, PR split recommendation |

### Progressive Output (CC 2.1.76+)

Output results **incrementally** after each phase — don't batch everything until the end.

> **Focus mode (CC 2.1.101):** In focus mode (`/focus`), the user only sees your final message. Include a self-contained summary with all key results — don't assume they saw incremental outputs.

| After Phase | Show User |
|-------------|-----------|
| 1. Discovery | Key findings, library recommendations, task breakdown |
| 4. Architecture | Each agent's design decisions as they return |
| 5. Implementation | Files created/modified per agent, test results |
| 7. Scope Creep | Planned vs actual delta, PR split recommendation |

When agents run with `run_in_background=true`, output each agent's findings **as soon as it returns** — don't wait for all agents to finish. This gives users ~60% faster perceived feedback and enables early intervention if an agent's approach diverges from the plan.

> **Teammate background tasks survive turn-end (CC 2.1.183):** A `run_in_background` task started by a teammate is no longer killed when that teammate finishes its turn. A parallel architecture/test teammate can launch a long build and let it outlive its own turn; the lead collects the result later. Pre-2.1.183 the lead had to own every background task to keep it alive.

### Monitor Tool for Background Streaming (CC 2.1.98)

Use `Monitor` to stream real-time events from background build/test scripts instead of polling output files:

```python
# Start a long-running build in background
Bash(command="npm run build 2>&1", run_in_background=true)
# Stream its output line-by-line as notifications (no polling)
Monitor(pid=build_task_id)

# For background agents with test suites:
Agent(subagent_type="ork:test-generator", run_in_background=true, ...)
# Monitor agent progress via task notifications (CC 2.1.98 partial progress)
```

Full pattern reference (when to use vs. `TaskOutput`, until-condition gates, partial-result salvage, anti-patterns): `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/chain-patterns/references/monitor-patterns.md")`.

**Partial results (CC 2.1.98):** if a worktree-isolated agent crashes mid-implementation, salvage its partial output — `git diff --name-only` in its worktree, commit what's usable, flag incomplete items — instead of re-spawning; escalate a `BLOCKED` agent to the user. Full salvage logic: the monitor-patterns reference above.

### Worktree-Isolated Implementation

**Spawn parallel implementation agents with `Agent(isolation="worktree")`.** The
subagent bypass of the worktree-isolation guard was fixed in CC 2.1.154 and
completed in 2.1.203; ork's floor is >= 2.1.220, so every supported session gets
real isolation. Full pattern, plus the 2.1.206 caveat that `EnterWorktree`
now prompts for confirmation on ork's out-of-tree `../&lt;repo&gt;-&lt;task&gt;` convention:
`Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/chain-patterns/references/worktree-agent-pattern.md")`

*Historical (CC &lt;= 2.1.153 only):* the param thrashed the primary worktree's HEAD
and cut agents off at ~60 tool uses (Yonatan-HQ/platform#3224). The manual
pre-create workaround that fixed it is superseded and kept only as a record:
`references/manual-worktree-pattern.md`.

### Post-Deploy Monitoring (CC 2.1.71)

After final PR, schedule health monitoring:

```python
# Guard: Skip cron in headless/CI (CLAUDE_CODE_DISABLE_CRON)
# if env CLAUDE_CODE_DISABLE_CRON is set, run a single check instead
CronCreate(
  schedule="0 */6 * * *",
  prompt="Health check for {feature} in PR #{pr}:
    gh pr checks {pr} --repo {repo}.
    If healthy 24h → CronDelete. If errors → alert."
)
```

### context7 with Detection

```python
if capabilities.context7:
  mcp__context7__resolve-library-id({ libraryName: "next-auth" })
  mcp__context7__query-docs({ libraryId: "...", query: "..." })
else:
  WebFetch("https://docs.example.com/api")  # T1 fallback
```

### Issue Tracking

If working on a GitHub issue, run the Start Work ceremony from `issue-progress-tracking` and post progress comments after major phases.

### Feedback Loop

Maintain checkpoints after each task. Load triggers: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/feedback-loop.md")`

---

## Test Requirements Matrix

Phase 5 test-generator MUST produce tests matching the change type. Each change type maps to specific required tests and testing rules.

Load test matrix, real-service detection, and phase 9 gate: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/test-requirements-matrix.md")`

---

## Key Principles

- **Verification gate (terminal, mandatory)** — before declaring ANY task done you MUST `Read("$\{CLAUDE_PLUGIN_ROOT\}/shared/rules/verification-gate.md")` and satisfy EVERY check: every changed file verified, tests green, scope-creep scored. A partial pass is NOT done; "should work now" is not evidence.
- **Agent status protocol** — all subagents report DONE / DONE_WITH_CONCERNS / BLOCKED / NEEDS_CONTEXT per `Read("$\{CLAUDE_PLUGIN_ROOT\}/shared/status-protocol.md")`
- **Tests are NOT optional** — each task includes its tests, matched to change type (see matrix above)
- **Parallel when independent** — use `run_in_background: true`, launch all agents in ONE message
- **Output limits (CC 2.1.77+):** the Opus tier defaults to 64k output tokens (128k upper bound). Generate complete artifacts in a single pass when possible; chunk across turns if output exceeds the limit
- **Micro-plan before implementing** — scope boundaries, file list, acceptance criteria
- **Detect scope creep** (phase 7) — score 0-10, split PR if significant
- **Real services when available** — if docker-compose/testcontainers exist, use them in Phase 6
- **Reflect and capture lessons** (phase 10) — persist to memory graph
- **Clean up agents** — teammates wind down at turn end (CC 2.1.178+ implicit team); press `Ctrl+F` twice to stop lingering background agents. Note: `/clear` (CC 2.1.72+) preserves background agents
- **Exit worktrees** — call `ExitWorktree(action: "keep")` in Phase 10 if worktree was entered in Step 0; never leave orphaned worktrees

---

## Next Steps (suggest to user after implementation)

```
/ork:verify {FEATURE}              # Grade the implementation
/ork:cover {FEATURE}               # Generate test suite
/ork:commit                        # Commit changes
/loop 10m npm test                 # Watch tests while iterating
/loop 30m /ork:verify {FEATURE}    # Periodic quality gate
```

### PushNotification on Completion (CC 2.1.110+)

`/ork:implement` runs commonly take 10–30 min with parallel agents. **At the final synthesis step, after the PR is opened and tests are green, call `PushNotification`** — the user has almost certainly context-switched.

```python
PushNotification(
  message=f"ork:implement complete — {FEATURE}: {tests_passing}/{tests_total} tests · PR #{pr_num} opened · ready for /ork:verify",
  status="proactive"
)
```

Full rule (when to fire, body content limits, graceful fallback for users without Remote Control): load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/chain-patterns/rules/push-notification-on-completion.md")`.

## Agent Coordination

### Dispatch envelope (CC 2.1.142+ flags — M146-6 / #1849)

When dispatching subagents — whether via the in-session `Agent` tool or a headless `claude -p --bare` from a wrapper script — set explicit `--permission-mode` and `--effort` per agent role so behaviour is deterministic across interactive vs CI runs:

| Agent role | `--permission-mode` | `--effort` | Rationale |
|---|---|---|---|
| Read-only analysis (`Explore`, `code-quality-reviewer`, `debug-investigator`) | `dontAsk` | `low` | No writes, no risk; minimise cost. |
| Test generation (`test-generator`) | `acceptEdits` | `medium` | Writes test files; permission prompts would block the parallel sweep. |
| Production code (`frontend-ui-developer`, `backend-system-architect`) | `default` or `acceptEdits` | `medium` to `high` | Set per-feature complexity. `default` keeps the user in the loop. |
| **Never** | `bypassPermissions` | — | Skip the audit trail — only acceptable in throwaway sandboxes. |

In-session `Agent` tool calls inherit the parent session's permission mode; the table is the **policy** for what those defaults should be. For genuinely headless invocations (cron, CI), pass the flags explicitly to `claude -p --bare`:

```bash
claude -p --bare \
  --permission-mode dontAsk \
  --effort low \
  --max-turns 8 \
  "<prompt>"
```

### Context Passing

All spawned agents receive: changed files list, project tier, architectural constraints, and decisions from prior phases (discovery, plan). Pass via the agent prompt, not just "implement X".

### SendMessage (Active Coordination)

When backend and frontend agents need to align on API contracts:

```python
SendMessage(to="frontend-ui-developer", message="API endpoint is POST /api/auth with {token, refreshToken} response shape")
SendMessage(to="test-generator", message="Backend uses JWT — mock auth middleware in test fixtures")
```

### Skill Chain

After implementation completes, chain to verification:

```python
TaskCreate(subject="Verify implementation", activeForm="Verifying changes")
TaskUpdate(taskId=verify_id, addBlockedBy=[impl_task_id])
# Then: /ork:verify {feature}
```

> **Session recovery (CC 2.1.108+):** After idle periods or interruptions, use `/recap` to restore conversational context. Combined with `.claude/chain/state.json` checkpoint-resume, this enables full recovery of multi-phase implement sessions. Enabled by default since CC 2.1.110 (even with telemetry disabled).

## Quality Bar

Done means all of these hold:
- every changed file verified per the terminal verification gate — never "should work"
- each Phase 5 task ships its tests matched to change type; the suite ran green with the summary line cited
- scope creep scored 0-10 in Phase 7; PR split when the delta is significant
- worktrees entered in Step 0 are exited via ExitWorktree — no orphans

## Related Skills

- `ork:explore`: Explore codebase before implementing
- `ork:verify`: Verify implementations work correctly
- `ork:issue-progress-tracking`: Auto-updates GitHub issues with commit progress

## References

Load on demand with `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/&lt;file&gt;")`:

| File | Content |
|------|---------|
| `agent-phases.md` | Agent prompts and spawn templates |
| `agent-teams-phases.md` | Agent Teams mode phases |
| `interview-mode.md` | Interview/take-home constraints |
| `blast-radius-clarification.md` | Step 0b: ask-what-before-how blast-radius interview + decisions table |
| `orchestration-modes.md` | Task tool vs Agent Teams selection |
| `feedback-loop.md` | Checkpoint triggers and actions |
| `cc-enhancements.md` | CC version-specific features |
| `agent-teams-full-stack.md` | Full-stack pipeline for teams |
| `team-worktree-setup.md` | Team worktree configuration |
| `micro-planning-guide.md` | Detailed micro-planning guide |
| `scope-creep-detection.md` | Planned vs actual comparison |
| `worktree-workflow.md` | Git worktree workflow |
| `e2e-verification.md` | Browser + API E2E testing guide |
| `worktree-isolation-mode.md` | Worktree isolation details |
| `tier-classification.md` | Tier classification, workflow mapping, orchestration mode |
| `test-requirements-matrix.md` | Test matrix by change type, real-service detection, phase 9 gate |


---

## Rules (6)

### Subagents must only modify files within their assigned scope — prevent cross-agent conflicts — HIGH


## Agent Scope Containment

Each subagent spawned in Phase 4-5 must receive an explicit file scope boundary in its prompt. Agents must NOT modify files outside their assigned scope. This prevents parallel agents from overwriting each other's work.

### Problem

Claude spawns parallel agents (backend, frontend, test-generator) without defining which files each agent owns. Two agents edit the same file — the last one to finish silently overwrites the first. This is especially dangerous without worktree isolation.

### Scope Assignment

Define non-overlapping scopes in Phase 2 (Micro-Planning):

```python
scopes = {
    "backend-system-architect": {
        "owns": ["src/api/", "src/services/", "src/models/"],
        "reads": ["src/types/", "src/config/"],
        "forbidden": ["src/components/", "src/pages/", "tests/"]
    },
    "frontend-ui-developer": {
        "owns": ["src/components/", "src/pages/", "src/hooks/"],
        "reads": ["src/types/", "src/api/client.ts"],
        "forbidden": ["src/api/routes/", "src/services/", "src/models/"]
    },
    "test-generator": {
        "owns": ["tests/", "__tests__/", "*.test.*", "*.spec.*"],
        "reads": ["src/"],
        "forbidden": []  # Can read everything, writes only to test dirs
    }
}
```

**Incorrect — no scope boundaries in agent prompts:**
```python
# Phase 5: Agents with overlapping scope
Agent(subagent_type="ork:backend-system-architect",
  prompt="Implement the user auth feature",
  run_in_background=True)
Agent(subagent_type="ork:frontend-ui-developer",
  prompt="Implement the user auth feature",
  run_in_background=True)
# Both agents edit src/types/user.ts — last write wins, first is lost
# Both create src/utils/validation.ts — silent overwrite
```

**Correct — explicit scope in every agent prompt:**
```python
# Phase 5: Agents with strict scope boundaries
Agent(subagent_type="ork:backend-system-architect",
  prompt="""Implement backend for user auth.
  YOUR SCOPE (only modify these): src/api/, src/services/, src/models/
  SHARED TYPES (read-only): src/types/
  DO NOT TOUCH: src/components/, src/pages/, tests/
  If you need a shared type, create it in src/types/auth.types.ts""",
  run_in_background=True)

Agent(subagent_type="ork:frontend-ui-developer",
  prompt="""Implement frontend for user auth.
  YOUR SCOPE (only modify these): src/components/, src/pages/, src/hooks/
  SHARED TYPES (read-only): src/types/
  DO NOT TOUCH: src/api/routes/, src/services/, src/models/
  Import API client from src/api/client.ts — do not modify it""",
  run_in_background=True)
```

### Shared File Protocol

For files both agents need (e.g., shared types):

1. Assign ONE agent as the owner of each shared file
2. Other agents may only read it
3. If both need to add types, use separate files: `auth.types.ts` (backend), `auth-ui.types.ts` (frontend)

### Key Rules

- Include explicit scope boundaries in every subagent prompt
- Log scope assignments in `02-plan.json` handoff for traceability
- After all agents complete, check for conflicting writes to the same file
- Prefer worktree isolation (`isolation: "worktree"`) to eliminate conflicts entirely
- If an agent violates scope, discard its out-of-scope changes and re-run


### Cap changes per agent batch to prevent cascade failures — HIGH


## When This Rule Applies

Large refactors, sweeping renames, signature migrations, or any `ork:implement` run that will modify **more than 10 files**. Also applies when spawning subagents for tasks with broad scope.

## The Rule

**Default batch size: 5 files.** Configurable via `--batch-size N` argument to `/ork:implement`.

For every batch:

1. **Make the change** (Agent edits up to `N` files).
2. **Run the relevant tests** (`npm test -- &lt;scope&gt;` or framework equivalent).
3. **If green**: commit the batch with a descriptive message, proceed to next batch.
4. **If red**: stop. Do not proceed to the next batch. Debug with the failing batch still uncommitted. Fix the issue before touching more files.
5. **Never skip step 4** with `// TODO`, `# type: ignore`, or `eslint-disable` — those suppress the signal the batch was too large.

## Why

From usage analytics across 126 sessions: large one-shot refactors (176-file migrations, 91 exception narrowings) consistently produced cascade failures where one bad change created 50+ test regressions. Sessions that used small batches (≤5 files per cycle) had measurably better outcomes — faster root cause identification, fewer rollbacks, lower turn counts.

## Recognizing the Trigger

Before starting an implementation that touches multiple files, run a quick scope estimate:

```bash
# Estimate affected files
grep -rl "<pattern-to-replace>" src/ | wc -l
```

If count > 10, engage batch governance. If > 50, also consider whether the operation needs a pre-written migration script rather than agent-driven edits — at that scale, a scripted `sed` or `codemod` with a single careful review is usually cheaper than 10+ agent batches.

## Incorrect Pattern

```python
# Don't: one Agent call to rewrite 176 files
Agent(subagent_type="ork:backend-system-architect",
      prompt="Migrate all repository.py files to the new RepositoryBase pattern")
# Result: agent edits all 176, tests fail in 40 places, no clean rollback target
```

## Correct Pattern

```python
# Do: loop with tests between batches
files = find_affected_files(pattern)  # 176 files
for batch in chunks(files, size=5):
    Agent(subagent_type="ork:backend-system-architect",
          prompt=f"Migrate these 5 files to the new RepositoryBase pattern: {batch}")
    result = Bash("npm test -- src/repositories")
    if result.failed:
        break  # Stop. Debug with current batch uncommitted.
    Bash(f"git commit -am 'refactor: migrate batch {batch_num} to RepositoryBase'")
```

## Interaction With Effort Levels

- `low` / `medium`: batch size 3–5 (default).
- `high`: batch size 5.
- `xhigh` (Opus 5): batch size 5 with an extra validation pass per batch — re-read the just-edited files and verify the change matches the migration intent before running tests. Catches LLM-introduced inconsistencies the linter doesn't see.

## Argument

`/ork:implement --batch-size 3 migrate all repositories to RepositoryBase` overrides the default when a particularly risky operation warrants smaller steps.


### Commit after each logical milestone — never batch all commits to session end — HIGH


## Commit After Milestone

Commit working code after each logical unit of work completes. A "logical unit" is a phase that produces working, buildable output. Never accumulate changes across 3+ phases without committing.

### Problem

Claude batches all commits to the end of a session. If the session dies mid-implementation (rate limit, timeout, network), all work is lost. The implement skill runs 10 phases — losing phases 1-7 because the commit was planned for phase 10 is catastrophic.

### Commit Points

| After Phase | Commit? | Why |
|-------------|---------|-----|
| 2. Micro-Plan | Yes | Plan files are valuable context for resume |
| 4. Architecture | Yes | Architecture decisions should survive crashes |
| 5. Implementation | Yes | The bulk of new code — highest risk of loss |
| 6. Integration Verified | Yes | Tests pass, safe checkpoint |
| 8. E2E Verified | Yes | Full verification complete |
| 10. Reflection | Yes | Final commit with docs and lessons |

**Incorrect — one commit after all phases:**
```bash
# Phase 1-2: Discovery + Planning (no commit)
# Phase 4: Architecture decided (no commit)
# Phase 5: 15 files implemented (no commit)
# Phase 6: Integration tests pass (no commit)
# Phase 8: E2E tests pass (no commit)
# --- rate limit hits here ---
# All work lost. No commits exist.
```

**Correct — commit at each milestone:**
```bash
# After Phase 2:
git add .claude/chain/02-plan.json src/docs/plan.md
git commit -m "plan: user auth micro-plan and task breakdown"

# After Phase 5:
git add src/auth/ tests/auth/
git commit -m "feat: implement user auth endpoints and tests"

# After Phase 6:
git add tests/integration/
git commit -m "test: integration verification for user auth"

# After Phase 8:
git add tests/e2e/
git commit -m "test: e2e verification for user auth flow"

# After Phase 10:
git add docs/ .claude/chain/
git commit -m "docs: user auth reflection and lessons learned"
```

### Commit Message Format

```
<type>: <what was completed>

Phase: <N> (<phase-name>)
Tier: <detected-tier>

Co-Authored-By: Claude <noreply@anthropic.com>
```

### Key Rules

- Never go more than 2 phases without a commit
- Commit even if tests are not yet written — partial progress beats total loss
- Use specific `git add &lt;files&gt;` instead of `git add -A` to avoid committing artifacts
- If a phase fails, commit the passing phases first, then address the failure
- Include phase number in commit messages for traceability during resume
- Handoff JSON files (`.claude/chain/*.json`) should be committed alongside code


### Block completion if new code has zero test coverage — tests are mandatory for every implementation — HIGH


## Test Coverage Requirement

Every task in Phase 5 must produce both implementation code AND matching tests. The test-generator agent is not optional — it runs in parallel with implementation agents and its output is required before Phase 6.

### Problem

Claude often treats tests as a "nice to have" and moves to integration/documentation phases without verifying that test-generator actually produced output. The Phase 9 gate catches this too late.

### Per-Task Enforcement

Each Phase 5 task must include a test verification step:

```python
# After each implementation agent completes:
task_output = TaskOutput(task_id)

# Check: does the output include test files?
Grep(pattern="describe\\(|it\\(|test\\(|def test_", glob="**/*.test.*")
Grep(pattern="def test_|class Test", glob="**/test_*.py")

# If 0 matches for new code paths → BLOCK Phase 6 entry
```

**Incorrect — proceed without tests:**
```python
# Phase 5: Implementation
Agent(subagent_type="ork:backend-system-architect",
  prompt="Implement user auth endpoints", run_in_background=True)
Agent(subagent_type="ork:frontend-ui-developer",
  prompt="Implement login form", run_in_background=True)
# No test-generator agent spawned
# Phase 6: "Let's verify integration..." ← no tests exist to run
```

**Correct — tests are parallel and mandatory:**
```python
# Phase 5: Implementation + Tests (parallel)
Agent(subagent_type="ork:backend-system-architect",
  prompt="Implement user auth endpoints", run_in_background=True)
Agent(subagent_type="ork:frontend-ui-developer",
  prompt="Implement login form", run_in_background=True)
Agent(subagent_type="ork:test-generator",
  prompt="Generate tests for user auth: unit tests for endpoints,
  integration tests for auth flow, component tests for login form.
  Change types: API endpoint + UI component (see Test Requirements Matrix)",
  run_in_background=True)

# GATE: Verify before Phase 6
for agent in [backend, frontend, test_gen]:
    output = TaskOutput(agent.task_id)

if test_file_count == 0:
    # DO NOT proceed — return to Phase 5
    Agent(subagent_type="ork:test-generator",
      prompt="BLOCKED: No tests found. Generate tests for: {files_created}")
```

### Change Type to Test Mapping

Always reference the Test Requirements Matrix from SKILL.md when spawning test-generator:

| Change | Minimum Tests |
|--------|--------------|
| API endpoint | 1 unit + 1 integration |
| DB migration | 1 migration test |
| UI component | 1 unit + 1 snapshot |
| Business logic | 2 unit tests |

### Key Rules

- Spawn test-generator in the same message as implementation agents
- Verify test output before advancing to Phase 6
- If test-generator fails, re-run it — do not skip
- Include test file paths in the `05-implementation.json` handoff


### Match implementation tier to assessed complexity — never over-engineer a simple task — HIGH


## Tier Validation

The tier detected in Step 0 sets a hard ceiling on architecture complexity. Every phase must respect this ceiling — especially Phase 4 (Architecture) and Phase 5 (Implementation).

### Tier Ceilings

| Tier | Max Patterns | Max Files | Forbidden |
|------|-------------|-----------|-----------|
| 1. Interview | Flat files, simple routes | 8-15 | DI containers, message queues, microservices |
| 2. Hackathon | Single file if possible | 5-10 | Abstract factories, hexagonal layers |
| 3. MVP | MVC monolith | 20-40 | CQRS, event sourcing, k8s manifests |
| 4-5. Growth/Enterprise | Full patterns allowed | No limit | None |

### Problem

Claude defaults to enterprise-grade patterns regardless of project size. A take-home interview gets hexagonal architecture with ports/adapters when a flat Express app with 3 routes would score higher.

**Incorrect — Tier 1 interview with enterprise architecture:**
```python
# Detected: Tier 1 (Interview, README says "take-home, 4-hour limit")
# Phase 4 agent prompt:
Agent(subagent_type="ork:backend-system-architect",
  prompt="Design hexagonal architecture with DI container, repository pattern,
  CQRS for read/write separation, and event sourcing for the todo API")
# Result: 35 files, 4 abstraction layers for a CRUD app
```

**Correct — Tier 1 interview with appropriate simplicity:**
```python
# Detected: Tier 1 (Interview, README says "take-home, 4-hour limit")
# Phase 4 agent prompt:
Agent(subagent_type="ork:backend-system-architect",
  prompt="Design a simple flat-file Express app for the todo API.
  Tier: 1 (Interview). Max 10 files. No DI, no abstractions beyond MVC.
  Focus: working code, clear tests, clean README.")
# Result: 8 files, runs out of the box, easy to review
```

**Validation check — add to Phase 4 handoff:**
```python
# In 04-architecture.json handoff:
{
  "tier": 1,
  "patterns_used": ["flat-routes", "single-db-file"],
  "tier_ceiling_respected": true,
  "justification": "Interview project — simplicity scores higher than abstraction"
}
# If patterns_used includes anything above the tier ceiling, STOP and simplify
```

### Key Rules

- Always pass the detected tier to every subagent prompt explicitly
- If a subagent produces output exceeding the tier ceiling, reject and re-run with stricter constraints
- When in doubt, under-engineer — simpler code is easier to review and extend
- Tier upgrades require explicit user confirmation via `AskUserQuestion`


### Always ExitWorktree after implementation — never leave orphaned worktrees — HIGH


## Worktree Cleanup

When the implement skill uses `EnterWorktree` for isolation, it MUST call `ExitWorktree` before completing — regardless of success or failure. Orphaned worktrees block future git operations and leak disk space.

### Problem

Claude enters a worktree for isolation but forgets to exit when the implementation finishes, errors out, or gets interrupted. The worktree directory and its lock file persist, causing `git worktree add` failures in the next session.

**Incorrect — enter worktree, finish, but never exit:**
```python
# Phase 3: Enter worktree
EnterWorktree(name="feat-user-auth")

# Phase 5: Implementation agents run in worktree
Agent(subagent_type="ork:backend-system-architect", prompt="Implement auth...")

# Phase 9: Documentation
# "Done! Here's what was implemented..."
# ← MISSING: ExitWorktree never called
# Next session: "fatal: 'feat-user-auth' is already checked out"
```

**Correct — exit worktree in all code paths:**
```python
# Phase 3: Enter worktree
EnterWorktree(name="feat-user-auth")

# Phase 5-8: Implementation, verification, testing...
# (all work happens in worktree)

# Phase 9: Before documentation, merge and exit
Bash("git add -A && git commit -m 'feat: user auth implementation'")
ExitWorktree()  # Merges back to original branch and removes worktree

# Phase 10: Reflection (back in main working tree)
```

**Correct — exit worktree even on failure:**
```python
# Phase 3: Enter worktree
EnterWorktree(name="feat-user-auth")
worktree_active = True

# Phase 5: Implementation fails
try:
    Agent(subagent_type="ork:backend-system-architect", prompt="...")
except:
    # STILL clean up the worktree
    if worktree_active:
        Bash("git stash")  # Save partial work
        ExitWorktree()
        worktree_active = False
    raise

# Normal exit path
if worktree_active:
    ExitWorktree()
```

### Verification

After `ExitWorktree`, confirm cleanup:

```bash
# Should NOT list the feature worktree
git worktree list
# Expected: only the main worktree
# /path/to/repo  abc1234 [main]
```

### Key Rules

- Every `EnterWorktree` must have a matching `ExitWorktree`
- Call `ExitWorktree` BEFORE Phase 10 (Reflection) so reflection runs in the main tree
- On error or early exit, still call `ExitWorktree` to prevent orphaning
- If resuming a session that has an active worktree, check `git worktree list` first
- Never assume the worktree will be cleaned up by a future session
- Include worktree status in handoff JSON: `"worktree_active": false` after cleanup



---

## References (18)

### Agent Phases

# Agent Phases Reference

## 128K Output Token Strategy

With 128K output tokens available, each agent produces **complete artifacts in a single pass**. This reduces implementation from 17 agents across 4 phases to **14 agents across 3 phases**.

| Metric | Before (64K) | After (128K) | Agent Teams Mode |
|--------|-------------|--------------|-----------------|
| Phase 4 agents | 5 | 5 (unchanged) | 4 teammates + lead |
| Phase 5 agents | 8 | 5 | Same 4 teammates (persist) |
| Phase 6 agents | 4 | 4 (unchanged) | 1 (code-reviewer verdict) + lead tests |
| **Total agents** | **17** | **14** | **4 teammates** (reused across phases) |
| Full API + models | 2 passes | 1 pass | 1 pass (same) |
| Component + tests | 2 passes | 1 pass | 1 pass (same) |
| Complete feature | 4-6 passes | 2-3 passes | 1-2 passes (overlapping) |
| Communication | Lead relays | Lead relays | Peer-to-peer messaging |
| Token cost | Baseline | ~Same | ~2.5x (full sessions) |

**Key principle:** Prefer one comprehensive response over multiple incremental ones. Only split when scope genuinely exceeds 128K tokens.

**Agent Teams advantage:** Teammates persist across phases 4→5→6, so context is preserved. No re-explaining architecture to implementation agents — they already know it because they designed it.

---

## Phase 4: Architecture Design (5 Agents)

All 5 agents launch in ONE message with `run_in_background=true`.

### Agent 1: Workflow Architect
```python
Agent(
  subagent_type="ork:workflow-architect",
  model=MODEL_OVERRIDE,  # None inherits default; "opus" for large features (CC 2.1.72)
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  ARCHITECTURE PLANNING — SINGLE-PASS OUTPUT

  Produce a COMPLETE implementation roadmap in one response:

  1. COMPONENT BREAKDOWN
     - Frontend components needed (with file paths)
     - Backend services/endpoints (with route paths)
     - Database schema changes (with table/column names)
     - AI/ML integrations (if any)

  2. DEPENDENCY GRAPH
     - What must be built first?
     - What can be parallelized?
     - Integration points between frontend/backend

  3. RISK ASSESSMENT
     - Technical challenges with mitigations
     - Performance concerns with benchmarks
     - Security considerations with OWASP mapping

  4. TASK BREAKDOWN
     - Concrete tasks for each agent
     - Estimated tool calls per task
     - Acceptance criteria per task

  Output: Complete implementation roadmap with task dependencies.
  Use full 128K output capacity — don't truncate or summarize.

  Feature: $ARGUMENTS""",
  run_in_background=true
)
```

### Agent 2: Backend Architect
```python
Agent(
  subagent_type="ork:backend-system-architect",
  model=MODEL_OVERRIDE,
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  COMPLETE BACKEND ARCHITECTURE — SINGLE PASS

  Standards: FastAPI, Pydantic v2, async/await, SQLAlchemy 2.0

  Produce ALL of the following in one response:
  1. API endpoint design (routes, methods, status codes, rate limits)
  2. Pydantic v2 request/response schemas with Field constraints
  3. SQLAlchemy 2.0 async model definitions with relationships
  4. Service layer patterns (repository + unit of work)
  5. Error handling (RFC 9457 Problem Details)
  6. Database migration strategy (tables, indexes, constraints)
  7. Testing strategy (unit + integration test outline)

  Include file paths for every artifact.
  Output: Complete backend implementation spec ready for coding.

  Feature: $ARGUMENTS""",
  run_in_background=true
)
```

### Agent 3: Frontend Developer
```python
Agent(
  subagent_type="ork:frontend-ui-developer",
  model=MODEL_OVERRIDE,
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  COMPLETE FRONTEND ARCHITECTURE — SINGLE PASS

  Standards: React 19, TypeScript strict, Zod, TanStack Query

  Produce ALL of the following in one response:
  1. Component hierarchy with file paths
  2. Zod schemas for ALL API responses
  3. State management approach (Zustand slices or React 19 hooks)
  4. TanStack Query configuration (keys, stale time, prefetching)
  5. Form handling with React Hook Form + Zod
  6. Loading states (skeleton components, not spinners)
  7. Error boundaries and fallback UI
  8. Accessibility requirements (WCAG 2.1 AA)

  Include Tailwind class specifications for key components.
  Output: Complete frontend implementation spec ready for coding.

  Feature: $ARGUMENTS""",
  run_in_background=true
)
```

### Agent 4: LLM Integrator
```python
Agent(
  subagent_type="ork:llm-integrator",
  model=MODEL_OVERRIDE,
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  AI/ML INTEGRATION ANALYSIS — SINGLE PASS

  Evaluate and design AI integration in one response:
  1. Does this feature need LLM? (justify yes/no)
  2. Provider selection (Anthropic/OpenAI/Ollama) with rationale
  3. Prompt template design (versioned, with Langfuse tracking)
  4. Function calling / tool definitions (if needed)
  5. Streaming strategy (SSE endpoint design)
  6. Caching strategy (prompt caching + semantic caching)
  7. Cost estimation (tokens per request, monthly projection)
  8. Fallback chain configuration

  Output: Complete AI integration spec or "No AI needed" with justification.

  Feature: $ARGUMENTS""",
  run_in_background=true
)
```

### Agent 5: Event-Driven Architect (conditional)

Spawn ONLY when the feature is event-sourcing / CQRS / message-queue / outbox-shaped
(e.g. order pipelines, real-time notifications, async fan-out, audit logs). Skip for
plain CRUD — like Agent 4, it self-justifies and returns "No event-driven design needed".

```python
Agent(
  subagent_type="ork:event-driven-architect",
  model=MODEL_OVERRIDE,
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  EVENT-DRIVEN ARCHITECTURE ANALYSIS — SINGLE PASS

  First decide: is this feature event-driven-shaped? (justify yes/no). If no,
  return "No event-driven design needed" and stop. If yes, produce in one response:
  1. Event model (event types, schemas, versioning)
  2. Event store / log choice (Kafka, Redis Streams, RabbitMQ, FastStream) with rationale
  3. Topic / partition / consumer-group topology
  4. Saga / process-manager design for multi-step workflows
  5. Outbox pattern for transactional event publishing
  6. Idempotency + dead-letter-queue (DLQ) handling
  7. Ordering and exactly-once vs at-least-once trade-offs

  Coordinate with the backend architect's schema; cite file paths.
  Output: Complete event-driven spec or "No event-driven design needed".

  Feature: $ARGUMENTS""",
  run_in_background=true
)
```

### Phase 4 — Teams Mode

In Agent Teams mode, 4 teammates form a team (`implement-\{feature-slug\}`) instead of independent Task spawns. The workflow-architect role is handled by the lead or omitted for simpler features. Teammates message architecture decisions to each other in real-time.

See [Agent Teams Full-Stack Pipeline](agent-teams-full-stack.md) for spawn prompts.

---

## Phase 5: Implementation (5 Agents)

**128K consolidation:** Backend is 1 agent (was 2), frontend is 1 agent (was 3 incl. styling). Each produces complete working code in a single pass.

All 5 agents launch in ONE message with `run_in_background=true`.

### Agent 1: Backend — Complete Implementation
```python
Agent(
  subagent_type="ork:backend-system-architect",
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  IMPLEMENT COMPLETE BACKEND — SINGLE PASS (128K output)

  Generate ALL backend code in ONE response:

  1. API ROUTES (backend/app/api/v1/routes/)
     - All endpoints with full implementation
     - Dependency injection
     - Rate limiting decorators

  2. SCHEMAS (backend/app/schemas/)
     - Pydantic v2 request/response models
     - Field constraints and validators

  3. MODELS (backend/app/db/models/)
     - SQLAlchemy 2.0 async models
     - Relationships, constraints, indexes

  4. SERVICES (backend/app/services/)
     - Business logic with repository pattern
     - Error handling (RFC 9457)

  5. TESTS (backend/tests/)
     - Unit tests for services
     - Integration tests for endpoints
     - Fixtures and factories

  Write REAL code to disk using Write/Edit tools.
  Every file must be complete and runnable.
  Do NOT split across responses — use full 128K output.

  Feature: $ARGUMENTS
  Architecture: [paste Phase 4 backend spec]""",
  run_in_background=true
)
```

### Agent 2: Frontend — Complete Implementation
```python
Agent(
  subagent_type="ork:frontend-ui-developer",
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  IMPLEMENT COMPLETE FRONTEND — SINGLE PASS (128K output)

  Generate ALL frontend code in ONE response:

  1. COMPONENTS (frontend/src/features/[feature]/components/)
     - React 19 components with TypeScript strict
     - useOptimistic for mutations
     - Skeleton loading states
     - Motion animation presets from @/lib/animations

  2. API LAYER (frontend/src/features/[feature]/api/)
     - Zod schemas for all API responses
     - TanStack Query hooks with prefetching
     - MSW handlers for testing

  3. STATE (frontend/src/features/[feature]/store/)
     - Zustand slices or React 19 state hooks
     - Optimistic update reducers

  4. STYLING
     - Tailwind classes using @theme tokens
     - Responsive breakpoints (mobile-first)
     - Dark mode variants
     - All component states (hover, focus, disabled, loading)

  5. TESTS (frontend/src/features/[feature]/__tests__/)
     - Component tests with MSW
     - Hook tests
     - Zod schema tests

  Write REAL code to disk. Every file must be complete.
  Include styling inline — no separate styling agent needed.
  Do NOT split across responses — use full 128K output.

  Feature: $ARGUMENTS
  Architecture: [paste Phase 4 frontend spec]""",
  run_in_background=true
)
```

### Agent 3: AI Integration (if needed)
```python
Agent(
  subagent_type="ork:llm-integrator",
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  IMPLEMENT AI INTEGRATION — SINGLE PASS (128K output)

  Generate ALL AI integration code in ONE response:

  1. Provider setup and configuration
  2. Prompt templates (versioned)
  3. Function calling / tool definitions
  4. Streaming SSE endpoint
  5. Prompt caching configuration
  6. Fallback chain implementation
  7. Langfuse tracing integration
  8. Tests with VCR.py cassettes

  Write REAL code to disk. Skip if AI spec says "No AI needed".

  Feature: $ARGUMENTS
  Architecture: [paste Phase 4 AI spec]""",
  run_in_background=true
)
```

### Agent 4: Test Suite — Complete Coverage
```python
Agent(
  subagent_type="ork:test-generator",
  prompt="""# Cache-optimized: stable content first (CC 2.1.73)
  GENERATE COMPLETE TEST SUITE — SINGLE PASS (128K output)

  IMPORTANT: Match test types to change type using the Test Requirements Matrix:
  - API endpoint → Unit + Integration + Contract (rules: integration-api, verification-contract, mocking-msw)
  - DB schema    → Migration + Integration (rules: integration-database, data-seeding-cleanup)
  - UI component → Unit + Snapshot + A11y (rules: unit-aaa-pattern, integration-component, a11y-testing)
  - Business logic → Unit + Property-based (rules: unit-aaa-pattern, pytest-execution, verification-techniques)
  - LLM/AI      → Unit + Eval (rules: llm-evaluation, llm-mocking)
  - Full-stack   → All of the above

  Follow the testing-unit/testing-e2e/testing-integration skill rules for each test type.

  Generate ALL tests in ONE response:

  1. UNIT TESTS
     - Python: pytest with factories (not raw dicts), AAA pattern
     - TypeScript: Vitest with meaningful assertions
     - Cover edge cases: empty input, errors, timeouts, rate limits

  2. INTEGRATION TESTS
     - API endpoint tests with TestClient
     - Database tests with fixtures
     - VCR.py cassettes for external HTTP calls
     - If docker-compose/testcontainers detected: test against REAL services

  3. CONTRACT / PROPERTY TESTS (if applicable)
     - Contract tests for API boundaries (verification-contract)
     - Property-based tests for business logic (verification-techniques)

  4. FIXTURES & FACTORIES
     - conftest.py with shared fixtures
     - Factory classes for test data
     - MSW handlers for frontend API mocking

  5. COVERAGE ANALYSIS
     - Run: poetry run pytest --cov=app --cov-report=term-missing
     - Run: npm test -- --coverage
     - Target: 80% minimum

  Write REAL test files to disk.
  Run tests after writing to verify they pass.
  Do NOT split across responses — use full 128K output.

  Feature: $ARGUMENTS""",
  run_in_background=true
)
```

### Phase 5 — Teams Mode

In Agent Teams mode, the same 4 teammates from Phase 4 continue into implementation. Key difference: backend-architect messages the API contract to frontend-dev as soon as it's defined (not after full implementation), enabling overlapping work. Optionally, each teammate gets a dedicated worktree. See [Team Worktree Setup](team-worktree-setup.md).

---

## Phase 6: Integration Verification (4 Agents)

### Real-Service Detection

Before running integration tests, check for infrastructure:

```python
# PARALLEL — detect real service testing capability
Glob(pattern="**/docker-compose*.yml")
Glob(pattern="**/testcontainers*")
Grep(pattern="testcontainers|docker-compose", glob="requirements*.txt")
Grep(pattern="testcontainers|docker-compose", glob="package.json")
```

If detected, run integration tests against real services (not just mocks). Reference `testing-integration` rules: `integration-database`, `integration-api`, `data-seeding-cleanup`.

### Validation Commands

**Backend:**
```bash
poetry run alembic upgrade head  # dry-run
poetry run ruff check app/
poetry run ty check app/
poetry run pytest tests/unit/ -v --cov=app
# If docker-compose detected:
docker-compose -f docker-compose.test.yml up -d
poetry run pytest tests/integration/ -v
docker-compose -f docker-compose.test.yml down
```

**Frontend:**
```bash
npm run typecheck
npm run lint
npm run build
npm test -- --coverage
```

### Agent 1: Backend Integration
```python
Agent(
  subagent_type="ork:backend-system-architect",
  prompt="""BACKEND INTEGRATION VERIFICATION

  Verify all backend code works together:
  1. Run alembic migrations (dry-run)
  2. Run ruff/mypy type checking
  3. Run full test suite with coverage
  4. Verify API endpoints respond correctly
  5. Fix any integration issues found

  This is verification, not new implementation.""",
  run_in_background=true
)
```

### Agent 2: Frontend Integration
```python
Agent(
  subagent_type="ork:frontend-ui-developer",
  prompt="""FRONTEND INTEGRATION VERIFICATION

  Verify all frontend code works together:
  1. Run TypeScript type checking (tsc --noEmit)
  2. Run linting (biome/eslint)
  3. Run build (vite build)
  4. Run test suite with coverage
  5. Fix any integration issues found

  This is verification, not new implementation.""",
  run_in_background=true
)
```

### Agent 3: Code Quality Review
```python
Agent(
  subagent_type="ork:code-quality-reviewer",
  prompt="""FULL QUALITY REVIEW — SINGLE PASS (128K output)

  Review ALL new code in one comprehensive report:
  1. Run all automated checks (lint, type, test, audit)
  2. Verify React 19 patterns (useOptimistic, Zod, assertNever)
  3. Check security (OWASP, secrets, input validation)
  4. Verify test coverage meets 80% threshold
  5. Check architectural compliance

  Produce structured review with APPROVE/REJECT decision.""",
  run_in_background=true
)
```

### Agent 4: Security Audit
```python
Agent(
  subagent_type="ork:security-auditor",
  prompt="""SECURITY AUDIT — SINGLE PASS (128K output)

  Audit ALL new code in one comprehensive report:
  1. Run bandit/semgrep on Python code
  2. Run npm audit on JavaScript dependencies
  3. Run pip-audit on Python dependencies
  4. Grep for secrets (API keys, passwords, tokens)
  5. OWASP Top 10 verification
  6. Input validation coverage

  Produce structured security report with severity ratings.""",
  run_in_background=true
)
```

### Security Checks
- No hardcoded secrets
- SQL injection prevention
- XSS prevention
- Proper input validation
- npm audit / pip-audit

### Phase 6 — Teams Mode

In Agent Teams mode, the code-reviewer has been reviewing continuously during Phase 5. Integration validation is lighter: the lead merges worktrees, runs integration tests, and collects the code-reviewer's final APPROVE/REJECT verdict. After Phase 6, the team winds down on its own (CC 2.1.178+ implicit team — no `TeamDelete`; teammates end with their turn, `Ctrl+F` twice to stop any lingering background agent) + worktree cleanup.

---

## Phase 7: Scope Creep Detection

Launch `workflow-architect` to compare planned vs actual files/features. Score 0-10:

| Score | Level | Action |
|-------|-------|--------|
| 0-2 | Minimal | Proceed to reflection |
| 3-5 | Moderate | Document and justify unplanned changes |
| 6-8 | Significant | Review with user, potentially split PR |
| 9-10 | Major | Stop and reassess |

See [Scope Creep Detection](scope-creep-detection.md) for the full agent prompt.

---

## Phase 8: E2E Verification

If UI changes were made, verify with agent-browser:

```bash
agent-browser open http://localhost:5173
agent-browser wait --load networkidle
agent-browser snapshot -i
agent-browser screenshot /tmp/feature.png
agent-browser close
```

Skip this phase for backend-only or library implementations.

---

## Phase 9: Documentation

Save implementation decisions to the knowledge graph for future reference:

```python
mcp__memory__create_entities(entities=[{
  "name": "impl-{feature}-{date}",
  "entityType": "ImplementationDecision",
  "observations": ["chose X over Y because...", "pattern: ..."]
}])
```

---

## Phase 10: Post-Implementation Reflection & Cleanup

### Worktree Cleanup (CC 2.1.72)

If worktree isolation was used in Step 0, exit it before committing:

```python
# Exit worktree — keep branch for PR creation
ExitWorktree(action="keep")
# Verify no orphaned worktrees remain
# Run: git worktree list
```

Every `EnterWorktree` must have a matching `ExitWorktree`. If the session crashes before cleanup, the next session should detect and clean up orphaned worktrees via `git worktree list` + `git worktree remove`.

### Reflection

Launch `workflow-architect` to evaluate:

- What went well / what to improve
- Estimation accuracy (actual vs planned time)
- Reusable patterns to extract
- Technical debt created
- Knowledge gaps discovered

Store lessons in memory for future implementations.


### Agent Teams Full Stack

# Agent Teams: Full-Stack Feature Pipeline

Team formation template for Pipeline 2 — Full-Stack Feature using CC Agent Teams.

**Agents:** 4 teammates + lead
**Topology:** Mesh — backend hands off API contract to frontend, test-engineer works incrementally
**Lead mode:** Delegate (coordination only, no code)

---

## Team Formation

### Team Name Pattern
```
implement-{feature-slug}
```

Example: `implement-user-auth`, `implement-dashboard-analytics`

### Teammate Spawn Prompts

#### 1. backend-architect (backend-system-architect)
```
You are the backend-architect specialist on this team.

## Your Role
Design and implement the complete backend: API routes, service layer, database models,
schemas, and backend tests. You own the API contract.

## Your Task
Implement the backend for: {feature description}

1. Define API endpoints (routes, methods, schemas, status codes)
2. Create Pydantic v2 request/response models
3. Implement service layer with repository pattern
4. Create SQLAlchemy 2.0 async models + migrations
5. Write backend unit and integration tests
6. Handle errors with RFC 9457 Problem Details

## Coordination Protocol
- AS SOON AS your API contract is defined (routes + request/response types),
  message frontend-dev with the contract. Don't wait for full implementation.
- When database schema is ready, update the shared task list.
- If you change the API contract after sharing it, message frontend-dev immediately.
- If blocked, message the lead with what you need.

## Quality Requirements
- All code must pass ruff + type checking
- Include tests for every endpoint (happy path + error cases)
- Document API changes in OpenAPI format
```

#### 2. frontend-dev (frontend-ui-developer)
```
You are the frontend-dev specialist on this team.

## Your Role
Implement the complete frontend: React components, state management, API integration,
styling, and frontend tests. You consume the API contract from backend-architect.

## Your Task
Implement the frontend for: {feature description}

1. Wait for API contract from backend-architect (types + routes)
2. Create Zod schemas matching the API contract
3. Build React 19 components with TypeScript strict
4. Implement TanStack Query hooks for data fetching
5. Add form handling with React Hook Form + Zod
6. Style with Tailwind (mobile-first, dark mode)
7. Write component and hook tests with MSW

## Coordination Protocol
- WAIT for backend-architect to message you with the API contract before building
  API integration. You CAN start on UI layout and component structure immediately.
- When component interfaces (exports, props) are stable, message test-engineer
  so they can write integration tests.
- If the API contract changes, adapt and message test-engineer about the update.
- If blocked, message the lead with what you need.

## Quality Requirements
- TypeScript strict mode, no `any` types
- Skeleton loading states (not spinners)
- WCAG 2.1 AA accessibility
- All components tested with MSW mocking
```

#### 3. test-engineer (test-generator)
```
You are the test-engineer specialist on this team.

## Your Role
Write comprehensive tests incrementally as contracts stabilize. Don't wait for
full implementation — test as soon as interfaces are defined.

## Your Task
Build the test suite for: {feature description}

1. Start writing test fixtures and factories immediately
2. When backend-architect shares API contract, write API integration tests
3. When frontend-dev shares component interfaces, write component tests
4. Add E2E test scenarios covering the full user flow
5. Run all tests and report coverage

## Coordination Protocol
- You do NOT need to wait for anyone. Start with fixtures, factories, and test plans.
- Monitor the shared task list for contract updates from backend-architect and frontend-dev.
- When tests uncover issues, message the responsible teammate directly:
  - API issues → message backend-architect
  - UI issues → message frontend-dev
- Update the shared task list with coverage metrics as tests pass.

## Quality Requirements
- 80% minimum coverage target
- Use factories (not raw dicts) for test data
- MSW handlers for frontend API mocking
- VCR.py cassettes for external HTTP calls
- Every edge case: empty input, errors, timeouts, rate limits
```

#### 4. code-reviewer (code-quality-reviewer)
```
You are the code-reviewer specialist on this team.

## Your Role
Review code as it lands. Don't wait for completion — review incrementally.
Flag issues directly to the author. Require plan approval before making changes.

## Your Task
Review all code for: {feature description}

1. Monitor files as they're written by backend-architect, frontend-dev, and test-engineer
2. Run automated checks: lint, typecheck, security scan
3. Verify architectural compliance (clean architecture, separation of concerns)
4. Check for OWASP Top 10 vulnerabilities
5. Verify test quality (meaningful assertions, not just coverage)

## Coordination Protocol
- Review continuously — don't wait for teammates to finish.
- When you find issues, message the responsible teammate directly with:
  - File path and line number
  - What's wrong and why
  - Suggested fix
- For blocking issues (security vulnerabilities, architectural violations),
  also message the lead.
- Update the shared task list with review status per teammate.

## Quality Requirements
- Zero critical/high security findings
- TypeScript strict compliance
- No hardcoded secrets or credentials
- Consistent error handling patterns
- Produce final APPROVE/REJECT decision for the lead
```

---

## Coordination Messaging Templates

### Backend → Frontend: API Contract Handoff

```
Subject: API contract ready for {feature}

Here are the endpoint definitions:

## Endpoints
- POST /api/v1/{resource} — Create
  Request: { field1: string, field2: number }
  Response: { id: string, ...fields, created_at: string }
  Status: 201

- GET /api/v1/{resource}/:id — Read
  Response: { id: string, ...fields }
  Status: 200

- PUT /api/v1/{resource}/:id — Update
  Request: { field1?: string, field2?: number }
  Response: { id: string, ...fields, updated_at: string }
  Status: 200

## TypeScript Types (for your Zod schemas)
[paste Pydantic models converted to TS interfaces]

## Error Format
RFC 9457: { type, title, status, detail, instance }

You can start building API integration now.
I'll message you if anything changes.
```

### Frontend → Test Engineer: Component Interface Handoff

```
Subject: Component interfaces ready for {feature}

## Exported Components
- <FeatureList /> — props: { items: Item[], onSelect: (id: string) => void }
- <FeatureDetail /> — props: { id: string }
- <FeatureForm /> — props: { onSubmit: (data: FormData) => Promise<void> }

## Query Hooks
- useFeatures() → { data: Item[], isLoading, error }
- useFeature(id) → { data: Item, isLoading, error }
- useCreateFeature() → { mutate, isPending }

## MSW Handlers
Located at: src/features/{feature}/__tests__/handlers.ts

You can start writing component and integration tests now.
```

### Any → Lead: Blocked Notification

```
Subject: BLOCKED — {brief description}

I'm blocked on: {what's blocking}
Waiting for: {who/what}
Impact: {what can't proceed}
Suggested resolution: {what would unblock}
```

---

## Per-Teammate Worktree Setup

See [Team Worktree Setup](team-worktree-setup.md) for detailed instructions.

**Quick summary:**

```bash
# Lead creates branches and worktrees.
# Worktrees live INSIDE the repo at .worktrees/<task>. A sibling path is outside the
# session's project directory, so the teammate's cd is silently bounced back to the
# primary tree and it commits there instead (platform#9870, #3319).
git branch feat/{feature}/backend
git branch feat/{feature}/frontend
git branch feat/{feature}/tests

git worktree add .worktrees/backend  feat/{feature}/backend
git worktree add .worktrees/frontend feat/{feature}/frontend
git worktree add .worktrees/tests    feat/{feature}/tests

# Assignment — each teammate runs pwd first to confirm the cd took
backend-architect  → .worktrees/backend/
frontend-dev       → .worktrees/frontend/
test-engineer      → .worktrees/tests/
code-reviewer      → Primary tree (read-only, reviews all)
```

**When to skip worktrees:** Small features (&lt; 5 files), or when teammates work on non-overlapping directories.

---

## Lead Synthesis Protocol

After all teammates complete (or when all tasks are done):

1. **Merge worktrees** (if used):
   ```bash
   git checkout feat/{feature}
   git merge --squash feat/{feature}/backend
   git commit -m "feat({feature}): backend implementation"
   git merge --squash feat/{feature}/frontend
   git commit -m "feat({feature}): frontend implementation"
   git merge --squash feat/{feature}/tests
   git commit -m "test({feature}): complete test suite"
   ```

2. **Resolve conflicts** — typically in shared types/interfaces

3. **Run integration tests** from the merged branch:
   ```bash
   npm test
   npm run typecheck
   npm run lint
   ```

4. **Collect code-reviewer verdict** — APPROVE or REJECT with findings

5. **Shut down team:**
   ```
   # CC 2.1.178+: no TeamDelete — teammates wind down at turn end
   # (press Ctrl+F twice to stop lingering background teammates).

   # Worktree cleanup (CC 2.1.72)
   ExitWorktree(action="keep")  # Keep branch for PR
   ```

---

## Cost Comparison

| Metric | Task Tool (5 sequential) | Agent Teams (4 mesh) |
|--------|-------------------------|---------------------|
| Expected tokens | ~500K | ~1.2M |
| Wall-clock time | Sequential phases | Overlapping (30-40% faster) |
| API contract handoff | Lead relays | Peer-to-peer (immediate) |
| Cross-agent rework | ~15% (wrong API shapes) | &lt; 5% (contract shared early) |
| Quality gate | After all complete | Continuous (reviewer on team) |

**When Teams is worth the cost:**
- Frontend and backend need to agree on API shape
- Feature has > 5 files across both stacks
- Complexity score >= 3.0

**When Task tool is cheaper and sufficient:**
- Backend-only or frontend-only scope
- Independent tasks (audit, test generation)
- Simple CRUD with clear schema

---

## When to Use

- **Use Agent Teams** for cross-cutting full-stack features where API contract coordination matters
- **Use Task Tool** for simpler features where agents work independently
- **Complexity threshold:** Average score >= 3.0 across 7 dimensions (use `/ork:quality-gates`)
- **Override:** Set `ORCHESTKIT_PREFER_TEAMS=1` to always use Agent Teams


### Agent Teams Phases

# Agent Teams Phase Alternatives

This reference consolidates Agent Teams mode instructions for Phases 4, 5, 6, and 6b of the implement workflow.

## Phase 4 — Agent Teams Architecture Design

In Agent Teams mode, form a team instead of spawning 5 independent Tasks. Teammates message architecture decisions to each other in real-time:

```python
# CC 2.1.178+: one implicit team per session — no TeamCreate.
# Spawn teammates directly via Agent(name=...). Requires
# CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 (set in ork.settings.json).

# Spawn 4 teammates (5th role — UX — is lead-managed or optional)
Agent(subagent_type="ork:backend-system-architect", name="backend-architect",
     team_name="implement-{feature-slug}", model=MODEL_OVERRIDE,
     prompt="Design backend architecture. Message frontend-dev when API contract ready.")

Agent(subagent_type="ork:frontend-ui-developer", name="frontend-dev",
     team_name="implement-{feature-slug}", model=MODEL_OVERRIDE,
     prompt="Design frontend architecture. Wait for API contract from backend-architect.")

Agent(subagent_type="ork:test-generator", name="test-engineer",
     team_name="implement-{feature-slug}", model=MODEL_OVERRIDE,
     prompt="Plan test strategy. Start fixtures immediately, tests as contracts stabilize.")

Agent(subagent_type="ork:code-quality-reviewer", name="code-reviewer",
     team_name="implement-{feature-slug}", model=MODEL_OVERRIDE,
     prompt="Review architecture decisions as they're shared. Flag issues to author directly.")
```

See [Agent Teams Full-Stack Pipeline](agent-teams-full-stack.md) for complete spawn prompts and messaging templates.

> **Fallback:** If team formation fails, fall back to 5 independent Task spawns (standard Phase 4).

---

## Phase 5 — Agent Teams Implementation

In Agent Teams mode, teammates are already formed from Phase 4. They transition from architecture to implementation and message contracts to each other:

- **backend-architect** implements the API and messages `frontend-dev` with the contract (types + routes) as soon as endpoints are defined — not after full implementation.
- **frontend-dev** starts building UI layout immediately, then integrates API hooks once the contract arrives.
- **test-engineer** writes tests incrementally as contracts stabilize. Reports failing tests directly to the responsible teammate.
- **code-reviewer** reviews code as it lands. Flags issues to the author directly.

Optionally set up per-teammate worktrees to prevent file conflicts:

```python
# Lead sets up worktrees (for features with > 5 files).
# INSIDE the repo at .worktrees/<task> — a sibling ../{project}-backend is outside
# the session's project directory, so the teammate's cd is silently bounced back to
# the primary tree and it commits there instead (platform#9870, #3319).
Bash("git worktree add .worktrees/backend  -b feat/{feature}/backend  origin/main")
Bash("git worktree add .worktrees/frontend -b feat/{feature}/frontend origin/main")
Bash("git worktree add .worktrees/tests    -b feat/{feature}/tests    origin/main")

# Include worktree path in teammate messages
SendMessage(to="backend-architect",
    message="Work in .worktrees/backend/. Run pwd to confirm before editing. "
            "Commit to feat/{feature}/backend.")
```

See [Team Worktree Setup](team-worktree-setup.md) for complete worktree guide.

> **Fallback:** If teammate coordination breaks down, shut down the team and fall back to 5 independent Task spawns (standard Phase 5).

---

## Phase 6 — Agent Teams Integration

In Agent Teams mode, the code-reviewer teammate has already been reviewing code during implementation (Phase 5). Integration verification is lighter:

- **code-reviewer** produces final APPROVE/REJECT verdict based on cumulative review.
- **Lead** runs integration tests across the merged codebase (or merged worktrees).
- No need for separate security-auditor spawn — code-reviewer covers security checks. For high-risk features, spawn a `security-auditor` teammate in Phase 4.

```python
# Lead runs integration after merging worktrees
Bash("npm test && npm run typecheck && npm run lint")

# Collect code-reviewer verdict
SendMessage(to="code-reviewer",
    message="All code merged. Please provide final APPROVE/REJECT verdict.")
```

> **Fallback:** If code-reviewer verdict is unclear, fall back to 4 independent Task spawns (standard Phase 6).

---

## Phase 6b — Team Teardown (Agent Teams Only)

After Phase 6 completes in Agent Teams mode, tear down the team:

### 1. Merge Worktrees (if used)

```bash
git checkout feat/{feature}
git merge --squash feat/{feature}/backend && git commit -m "feat({feature}): backend"
git merge --squash feat/{feature}/frontend && git commit -m "feat({feature}): frontend"
git merge --squash feat/{feature}/tests && git commit -m "test({feature}): test suite"
```

### 2. Shut Down Teammates

```python
```

### 3. Clean Up

```python
# CC 2.1.178+: no TeamDelete — teammates wind down at turn end
# (press Ctrl+F twice to stop lingering background teammates).

# Worktree cleanup (CC 2.1.72)
ExitWorktree(action="keep")  # Keep branch for PR
```

> Phases 7-10 (Scope Creep, E2E Verification, Documentation, Reflection) are the same in both modes — the team is already disbanded.


### Agent Teams Security Audit

# Agent Teams: Security Audit Pipeline

Team formation template for Pipeline 4 — Security Audit using CC Agent Teams.

**Agents:** 3 (all read-only, no file conflicts)
**Topology:** Mesh — auditors share findings with each other
**Lead mode:** Delegate (coordination only)

---

## Team Formation

### Team Name Pattern
```
security-audit-{timestamp}
```

### Teammate Spawn Prompts

#### 1. security-auditor (OWASP + Dependencies)
```
You are the security-auditor specialist on this team.

## Your Role
Scan codebase for vulnerabilities, audit dependencies, and verify OWASP Top 10 compliance.
Focus on: dependency CVEs, hardcoded secrets, injection patterns, auth weaknesses.

## Your Task
Run a security audit on the hooks subsystem (src/hooks/). Focus on:
1. Dependency vulnerabilities (npm audit)
2. Secret/credential patterns in source
3. Injection risks (eval, exec, command injection)
4. Input validation on hook inputs
5. OWASP Top 10 applicability

## Coordination Protocol
- When you find critical/high findings, message security-layer-auditor to verify
  which defense layer is affected
- When you find LLM-related issues, message ai-safety-auditor for cross-reference
- Update the shared task list when you complete each scan area
- If blocked, message the lead

## Output
Return findings as structured JSON with severity, location, and remediation.
```

#### 2. security-layer-auditor (Defense-in-Depth)
```
You are the security-layer-auditor specialist on this team.

## Your Role
Verify defense-in-depth implementation across 8 security layers (edge to storage).
Map every finding to a specific layer and assess coverage gaps.

## Your Task
Audit the hooks subsystem (src/hooks/) across all applicable security layers:
1. Layer 2 (Input): How are hook inputs validated?
2. Layer 3 (Authorization): How are tool permissions enforced?
3. Layer 4 (Data Access): How is file system access controlled?
4. Layer 5 (LLM): How is prompt content handled in hooks?
5. Layer 7 (Storage): How are lock files and coordination data stored?

## Coordination Protocol
- When security-auditor shares findings, map them to specific layers
- Validate whether existing controls contain the identified threats
- Share layer gap analysis with ai-safety-auditor for LLM-specific layers
- Update the shared task list when you complete each layer

## Output
Return an 8-layer audit matrix with status (pass/fail/partial) per layer.
```

#### 3. ai-safety-auditor (LLM Security)
```
You are the ai-safety-auditor specialist on this team.

## Your Role
Audit LLM integration security. Focus on prompt injection, tool poisoning,
excessive agency, and OWASP LLM Top 10 compliance.

## Your Task
Audit the hooks subsystem (src/hooks/) for AI safety:
1. Prompt injection risks in context-injection hooks
2. Tool poisoning vectors in MCP integration
3. Excessive agency in automated hook actions
4. Data leakage through hook outputs
5. OWASP LLM Top 10 applicability

## Coordination Protocol
- Cross-reference with security-auditor findings for injection risks
- Cross-reference with security-layer-auditor for Layer 5/6 gaps
- If you find a finding that contradicts another auditor, flag the disagreement
- Update the shared task list when you complete each assessment area

## Output
Return OWASP LLM Top 10 compliance matrix plus specific findings.
```

---

## Lead Synthesis Protocol

After all teammates complete:

1. **Collect** all three audit reports
2. **Cross-reference** findings — same issue found by multiple auditors = higher confidence
3. **Highlight disagreements** — auditors may rate severity differently
4. **Deduplicate** — merge equivalent findings
5. **Produce unified report** with:
   - Combined findings sorted by severity
   - Layer coverage matrix
   - OWASP compliance summary
   - Prioritized remediation plan

---

## Cost Comparison Baseline

| Metric | Task Tool (3 sequential) | Agent Teams (3 mesh) |
|--------|-------------------------|---------------------|
| Expected tokens | ~150K | ~400K |
| Wall-clock time | Sequential (3x) | Parallel (1x) |
| Cross-reference | Manual by lead | Peer-to-peer |
| Finding quality | Independent | Corroborated |

Track actual values to validate.

---

## When to Use

- **Use Agent Teams** when auditors need to cross-reference findings in real-time
- **Use Task Tool** for quick, independent audits (single agent sufficient)
- **Complexity threshold:** Average score >= 3.0 across 7 dimensions


### Blast Radius Clarification

# Blast-Radius Clarification (ask "what" before "how")

Before Phase 1, find the unknowns whose answers would **change the architecture** and
resolve them in blast-radius order — biggest consequence first. The cheapest place to
settle an ambiguity is before code exists; the same ambiguity found mid-build is a
rework, and found post-merge is an incident. This is "ask what before you ask how" made
into a step.

## When to run

- Runs as **Step 0b**, after context discovery / worktree (Step 0a) and BEFORE Task
  Management + Phase 1.
- **Skip** in `low` effort, or when the feature is small and unambiguous (&lt; ~3 files, no
  schema / auth / contract surface).
- **Grep the codebase first** — never ask a question the code already answers.

## Blast-radius order (ask highest first; skip any tier already unambiguous)

| # | Tier | Why it's high blast-radius | Example question |
|---|------|----------------------------|------------------|
| 1 | Data model / schema / migration | An answer reshapes every downstream layer | "New table, or a column on `&lt;Y&gt;`? Nullable? Backfill?" |
| 2 | Auth / security / trust boundary | Sets who can act + the threat model | "Who calls this — portal user, admin, service token?" |
| 3 | API contract / breaking change | Ripples to every consumer | "Change an existing response shape, or add a new endpoint?" |
| 4 | Data volume / performance / scale | Sets the algorithm + index strategy | "Expected cardinality / hot path / concurrency?" |
| 5 | UX / copy / cosmetics | Cheap to change later — ask LAST | "Inline panel or modal?" |

## Protocol

1. One question at a time via `AskUserQuestion`, **highest blast-radius first**.
2. Ask ONLY the genuinely ambiguous, high-blast-radius items — not the obvious ones. Stop
   as soon as the remaining unknowns are low-blast-radius / cosmetic. **Cap ~5.**
3. Each answer becomes a row in the Decisions table.
4. Write the table to `.claude/chain/decisions.json` and surface it in the **PR body**
   (Phase 9 documentation) so the "why" lands where reviewers see it.
5. Feed the schema / auth / contract answers into **Phase 4 (Architecture)** as
   constraints — they are inputs to the architecture agents, not afterthoughts.

## Decisions table (written to state + PR body)

```markdown
## Decisions (blast-radius clarification)
| # | Question | Decision | Blast radius | Rationale |
|---|----------|----------|--------------|-----------|
| 1 | New table or column on projects? | new `project_metric` table | schema | needs its own lifecycle + FK |
| 2 | Who can write it? | admin + service token only | auth | portal users are read-only here |
```

## Why (the failure classes this closes)

- **"Start solo → 3 interrupts"** — the operator gets pulled in three separate times
  mid-build for questions a two-minute up-front interview would have batched.
- **Premature architecture / root-cause commitment** — building on an unstated schema or
  auth assumption, then discovering it was wrong after the architecture is set.

## Anti-patterns

- Asking cosmetic questions first — spends the user's attention on the cheapest unknowns.
- Interrogating the obvious, or asking what the codebase already answers (grep first).
- Asking everything → analysis paralysis. Cap and stop at low blast-radius.
- Proceeding on an ambiguous **schema or auth** question — the exact rework this step
  exists to prevent. If a tier-1/2 unknown is unresolved, do NOT start Phase 1.


### Cc Enhancements

# CC 2.1.30+ Enhancements

## Task Metrics

Task tool results now include `token_count`, `tool_uses`, and `duration_ms`. Use for scope monitoring:

```markdown
## Phase 5 Metrics (Implementation)
| Agent | Tokens | Tools | Duration |
|-------|--------|-------|----------|
| backend-system-architect #1 | 680 | 15 | 25s |
| backend-system-architect #2 | 540 | 12 | 20s |
| frontend-ui-developer #1 | 720 | 18 | 30s |

**Scope Check:** If token_count > 80% of budget, flag scope creep
```

## Tool Usage Guidance (CC 2.1.31)

Use the right tools for each operation:

| Task | Use | Avoid |
|------|-----|-------|
| Find files by pattern | `Glob("**/*.ts")` | `bash find` |
| Search code | `Grep(pattern="...", glob="*.ts")` | `bash grep` |
| Read specific file | `Read(file_path="/abs/path")` | `bash cat` |
| Edit/modify code | `Edit(file_path=...)` | `bash sed/awk` |
| Parse file contents | `Read` with limit/offset | `bash head/tail` |
| Git operations | `Bash git ...` | (git needs bash) |
| Run tests/build | `Bash npm/poetry ...` | (CLIs need bash) |

## Session Resume Hints (CC 2.1.31)

Before ending implementation sessions, capture context:

```bash
/ork:remember Implementation of {feature}:
  Completed: phases 1-6
  Remaining: verification, docs
  Key decisions: [list]
  Blockers: [if any]
```

Resume later with full context preserved.


### E2e Verification

# E2E Verification Guide

Concrete steps for Phase 8 end-to-end verification.

## Browser Testing (UI features)

```python
# Use agent-browser CLI for visual verification
Bash("agent-browser open http://localhost:3000/{route}")
Bash("agent-browser snapshot")  # Capture DOM state
Bash("agent-browser screenshot /tmp/e2e-{feature}.png")
Read("/tmp/e2e-{feature}.png")  # Visual inspection
```

## API Testing (Backend features)

```bash
# Verify endpoints return expected responses
curl -s http://localhost:8000/api/{endpoint} | jq .

# Run integration test suite against running server
pytest tests/integration/ -v --tb=short

# If docker-compose exists, test against real services
docker-compose -f docker-compose.test.yml up -d
pytest tests/integration/ -v
docker-compose -f docker-compose.test.yml down
```

## Full-Stack Verification

1. Start backend: verify API responses with curl/httpie
2. Start frontend: verify pages render with agent-browser
3. Test critical user flows end-to-end
4. Verify error states (invalid input, network failure, auth failure)

## What to Check

| Aspect | How |
|--------|-----|
| Happy path | Complete the primary user flow |
| Error handling | Submit invalid data, check error messages |
| Auth boundaries | Access protected routes without auth |
| Data persistence | Create → Read → Update → Delete cycle |
| Performance | Page load under 3s, API response under 500ms |

## When to Skip

- **Tier 1-2 (Interview/Hackathon):** Skip browser E2E, manual verification sufficient
- **No UI changes:** Skip browser testing, API tests only
- **Config-only changes:** Skip E2E entirely


### Feedback Loop

# Continuous Feedback Loop

Maintain a feedback loop throughout implementation.

## After Each Task Completion

Quick checkpoint:
- What was completed
- Tests pass/fail
- Actual vs estimated time
- Blockers encountered
- Scope deviations

Update task status with `TaskUpdate(taskId, status="completed")`.

## Feedback Triggers

| Trigger | Action |
|---------|--------|
| Task takes 2x estimated time | Pause, reassess scope |
| Test keeps failing | Consider design issue, not just implementation |
| Scope creep detected | Stop, discuss with user |
| Blocker found | Create blocking task, switch to parallel work |


### Interview Mode

# Interview / Take-Home Mode

When project tier is detected as **Interview** (STEP 0), apply these constraints:

## Constraints

| Constraint | Value |
|-----------|-------|
| Max files | 8-15 |
| Max LOC | 200-600 |
| Architecture | Flat (no layers) |
| Skip phases | 2 (Micro-Planning), 3 (Worktree), 7 (Scope Creep), 8 (E2E Browser), 10 (Reflection) |
| Agents | Max 2 (1 backend + 1 frontend, or 1 full-stack) |
| CI/Observability | Skip entirely |

## README Template

Include a "What I Would Change for Production" section:
- **Database:** would add migrations, connection pooling
- **Auth:** would add OAuth/JWT instead of basic auth
- **Testing:** would add integration + e2e tests
- **Monitoring:** would add structured logging, health checks

> This section demonstrates production awareness without over-engineering the take-home. Reviewers value this signal.


### Manual Worktree Pattern

# Manual Pre-Create Worktree Pattern

> **⚠ SUPERSEDED — CC 2.1.154, completed in CC 2.1.203.** Upstream fixed the root
> cause: *"subagents in background sessions bypassing the worktree-isolation guard
> and writing to the shared checkout"* (CC 2.1.154 changelog). On CC ≥ 2.1.154 you
> can use `Agent(isolation="worktree")` directly — parallel spawns each get a real
> isolated worktree, no HEAD thrash. 2.1.154 also fixed `worktree.baseRef:"head"`
> resolving to the main checkout's HEAD instead of the current worktree's when
> spawning from inside a linked worktree. **The 2.1.154 fix was partial:** a
> residual leak — isolated subagents *sometimes running shell commands in the
> parent checkout* (the exact symptom in "The bug" below: `git checkout` firing on
> the primary tree) — persisted through CC 2.1.202 and was closed in **CC 2.1.203**.
> **Prefer `isolation="worktree"` now;** the manual pre-create pattern below is
> retained for CC ≤ 2.1.153, as a partial mitigation on 2.1.154–2.1.202, and as a
> record of the original failure.

**Original context — workaround for the broken `Agent(isolation="worktree")`
behavior in CC ≤ 2.1.153.** Tracked at
[Yonatan-HQ/platform#3224](https://github.com/Yonatan-HQ/platform/issues/3224).

## TL;DR

Don't use `isolation="worktree"` on parallel agent spawns. Instead:

1. The **lead** creates one worktree per agent BEFORE spawning, using
   `git worktree add -b &lt;branch&gt; &lt;path&gt; origin/main`.
2. Each agent prompt starts with `FIRST: cd &lt;worktree-path&gt;. THEN ...`.
3. Each agent commits + pushes + opens a PR from its own worktree.

Result: 4-22 tool-uses per agent (vs 60-86 with broken isolation),
one-run completion, zero HEAD thrash.

## The bug

Spawned 4 parallel background agents on 2026-05-11 22:30 IDT with:

```python
Agent(subagent_type="<agent-a>", isolation="worktree", run_in_background=true)
Agent(subagent_type="<agent-b>", isolation="worktree", run_in_background=true)
Agent(subagent_type="<agent-c>", isolation="worktree", run_in_background=true)
Agent(subagent_type="<agent-d>", isolation="worktree", run_in_background=true)
```

**Expected:** Each agent operates in its own isolated worktree.

**Actual:** `git reflog` on the primary worktree showed:

```
checkout: moving from <branch-a> to <branch-b>
checkout: moving from <branch-b> to <branch-c>
checkout: moving from <branch-c> to <branch-d>
```

Sequential `git checkout` calls on the PRIMARY worktree. Each agent's
untracked files got auto-stashed when the next agent's checkout fired.
Three of four agents hit the ~60-tool-use cliff before push because
their `pnpm install` / `pre-push` hooks failed against thrashed
`node_modules`.

## The fix (Wave 2 / 3 pattern from M164)

Pre-creating worktrees from the LEAD context, before the agents start:

```python
backend_wt = setup_agent_worktree(REPO, SLUG, f"feat/{SLUG}-backend")
frontend_wt = setup_agent_worktree(REPO, SLUG, f"feat/{SLUG}-frontend")
tests_wt = setup_agent_worktree(REPO, SLUG, f"feat/{SLUG}-tests")
```

Then spawning with **no** `isolation` param, but with an explicit `cd`
as the first instruction:

```python
Agent(subagent_type="ork:backend-system-architect",
  prompt=f"FIRST: cd {backend_wt}. THEN implement backend: {feature}. "
         f"Commit + push + open PR from {backend_wt} when done.",
  run_in_background=true)
```

Result: M164 Wave 2/3 agents finished in 4-22 tool-uses each, one-run.
M164 Wave 1 (broken pattern) needed 60-86 tool-uses per agent and 3 of
4 hit cutoffs.

## Helper

```python
import subprocess

def setup_agent_worktree(repo_root: str, slug: str, branch: str) -> str:
    """Pre-create a worktree off origin/main; return absolute path."""
    path = f"{repo_root}/../{slug}-{branch.split('/')[-1]}"
    subprocess.run(
        ["git", "-C", repo_root, "worktree", "add",
         "-b", branch, path, "origin/main"],
        check=True,
    )
    return path
```

## Why this works

The bug appears to be in CC's `isolation` param handling — the param is
accepted but the worktree may not actually be created (or `cd`'d into)
before the agent's first Bash call fires. By the time the agent runs,
its CWD is still the primary tree. Manual pre-creation moves the
`worktree add` into the deterministic lead context BEFORE the agent
starts; the agent's prompt then explicitly `cd`s into the prepared
worktree.

## Constraints on the agent prompt

To make the pattern reliable:

1. **`cd` must be the FIRST Bash call.** Wrap it in a header like
   `FIRST: cd &lt;path&gt;. THEN: ...` so the agent can't skip it.
2. **Forbid touching the primary tree.** Add to the prompt: "Do not
   `cd` out of this worktree. All commits, pushes, and PRs originate
   from \{worktree-path\}."
3. **Push early.** Add: "As soon as you have a minimal working file +
   1 reference doc, commit + push + open PR. Iterate via follow-up
   commits." This converts the 60-tool cliff into an 18-22 first
   checkpoint.
4. **Explicit branch.** Always pass `-b feat/&lt;slug&gt;-&lt;role&gt;` to the
   `git worktree add` — never let the agent decide its own branch
   (collisions cause the original thrash).

## What this DOESN'T fix

- **Single-agent isolation:** if you only spawn ONE agent with
  `isolation="worktree"`, it MAY work — the bug surfaces under parallel
  spawns. Use the manual pattern anyway for consistency.
- **EnterWorktree (operator-level):** This is the model-managed,
  not-agent-managed worktree tool. It works fine and is unrelated.
  **CC 2.1.206:** `EnterWorktree` now asks for confirmation before entering a
  worktree OUTSIDE `.claude/worktrees/`. This `../\{slug\}-\{branch\}` convention is
  always outside that directory, so expect a one-time confirmation prompt per
  external worktree. Headless/non-interactive flows that can't answer the prompt
  should place worktrees under `.claude/worktrees/` instead.
- **The root-cause CC bug:** Filed as `#3224 Path A` if a fix is found
  upstream, this whole reference becomes deletable.

## Cleanup

After agents finish + PRs merge:

```bash
git worktree remove ../<slug>-backend --force
git worktree remove ../<slug>-frontend --force
git worktree remove ../<slug>-tests --force
git worktree prune
```

If a worktree has uncommitted local state when removing, capture or
discard explicitly — don't blindly `--force` away unmerged work.

## References

- `feedback_agent_worktree_isolation_unreliable.md` — original incident
- `Yonatan-HQ/platform#3224` — upstream tracking issue
- `Yonatan-HQ/platform#3132` — companion worktree-audit cron script


### Micro Planning Guide

# Micro-Planning Guide

Create detailed task-level plans before writing code to prevent scope creep and improve estimates.

## What to Include

| Section | Purpose |
|---------|---------|
| **Scope (IN)** | Explicit list of what will change |
| **Out of Scope** | What NOT to touch (prevents creep) |
| **Files to Touch** | Exact files, change type, description |
| **Acceptance Criteria** | How to know it's done |
| **Estimated Time** | Realistic time budget |

## Planning Process

### Step 1: Define Scope Boundaries

```markdown
### IN Scope
- Add User model with email, password_hash
- Add /register endpoint
- Add validation for email format

### OUT of Scope
- Password reset (separate task)
- OAuth providers (future task)
- Email verification (future task)
```

### Step 2: List Files Explicitly

```markdown
### Files to Touch
| File | Action | Description |
|------|--------|-------------|
| models/user.py | CREATE | User SQLAlchemy model |
| api/auth.py | CREATE | Register endpoint |
| tests/test_auth.py | CREATE | Registration tests |
| alembic/versions/xxx.py | CREATE | Migration |
```

### Step 3: Set Acceptance Criteria

```markdown
### Acceptance Criteria
- [ ] POST /register creates user
- [ ] Duplicate email returns 409
- [ ] Invalid email returns 422
- [ ] Password is hashed (not plaintext)
- [ ] Tests pass
- [ ] Types check
```

## Time-Boxing Techniques

| Task Size | Time Box | Break Point |
|-----------|----------|-------------|
| Small (1-3 files) | 30 min | 45 min |
| Medium (4-8 files) | 2 hours | 3 hours |
| Large (9+ files) | 4 hours | Split task |

### At Break Point

1. Stop and assess progress
2. If not 50%+ done, re-estimate
3. If blocked, create blocker task
4. Consider splitting remaining work

## When to Break Down Further

Split the task if:
- More than 8 files to modify
- Estimate exceeds 4 hours
- Multiple unrelated changes
- Requires learning new technology
- Has uncertain requirements

## Anti-Patterns

| Anti-Pattern | Fix |
|--------------|-----|
| Vague scope: "Add auth" | Specific: "Add /register endpoint" |
| No out-of-scope section | Always list what's excluded |
| Missing time estimate | Always estimate, even if rough |
| No acceptance criteria | Define "done" before starting |


### Orchestration Modes

# Orchestration Mode Selection

## Decision Logic

```python
# Agent Teams is GA since CC 2.1.33 (Issue #362)
import os
force_task_tool = os.environ.get("ORCHESTKIT_FORCE_TASK_TOOL") == "1"

if force_task_tool:
    mode = "task_tool"
else:
    # Teams available by default — use it for non-trivial work
    mode = "agent_teams" if avg_complexity >= 2.5 else "task_tool"
```

## Comparison Table

| Aspect | Task Tool (star) | Agent Teams (mesh) |
|--------|------------------|--------------------|
| Communication | All agents report to lead only | Teammates message each other |
| API contract | Lead relays between agents | Backend messages frontend directly |
| Cost | ~500K tokens (full-stack) | ~1.2M tokens (full-stack) |
| Wall-clock | Sequential phases | Overlapping (30-40% faster) |
| Quality review | After all agents complete | Continuous (reviewer on team) |
| Best for | Independent tasks, low complexity | Cross-cutting features, high complexity |

## Fallback

If Agent Teams mode encounters issues (teammate failures, messaging problems), fall back to Task tool mode for remaining phases. The approaches are compatible — work done in Teams mode transfers to Task tool continuation.


### Scope Creep Detection

# Scope Creep Detection

Identify when implementation exceeds original scope and take corrective action.

## Warning Signs

| Indicator | Example |
|-----------|---------|
| "While I'm here..." | Refactoring unrelated code |
| Premature optimization | Adding caching before measuring |
| Goldplating | Extra UI polish not requested |
| Future-proofing | "We might need this later" |
| Rabbit holes | Deep debugging unrelated issues |

## Detection Checklist

### Files Changed vs Planned

```
[ ] List files in original micro-plan
[ ] List files actually modified (git diff --name-only)
[ ] Flag any file not in original plan
[ ] Each unplanned file needs justification
```

### Features Added vs Planned

```
[ ] Compare implemented features to acceptance criteria
[ ] Identify features not in original scope
[ ] Mark as: necessary dependency / nice-to-have / out-of-scope
```

### Time Spent vs Estimated

```
[ ] Original estimate: ___ hours
[ ] Actual time: ___ hours
[ ] If >1.5x estimate, identify cause
```

## Quick Audit Command

```bash
# Compare planned vs actual files
git diff --name-only main...HEAD | sort > /tmp/actual.txt
# Compare against micro-plan's "Files to Touch" section
diff /tmp/planned.txt /tmp/actual.txt
```

## Scope Creep Score

| Score | Level | Action |
|-------|-------|--------|
| 0-2 | Minimal | Proceed normally |
| 3-5 | Moderate | Document, justify each addition |
| 6-8 | Significant | Discuss with user, consider splitting |
| 9-10 | Major | Stop, split into separate PR |

## Recovery Strategies

### If Score 3-5 (Moderate)
1. Document unplanned changes in PR description
2. Add "bonus" label to extra features
3. Ensure tests cover additions

### If Score 6-8 (Significant)
1. Revert unplanned changes to separate branch
2. Create follow-up issue for extras
3. Submit minimal PR matching original scope

### If Score 9-10 (Major)
1. Stop implementation
2. Split into multiple PRs
3. Re-scope with user before continuing

## Prevention Tips

- Review micro-plan before starting each file
- Time-box exploration (15 min max)
- Ask "Is this in scope?" before each change
- Use TODO comments for out-of-scope ideas


### Team Worktree Setup

# Team Worktree Setup

Per-teammate git worktree management for Agent Teams. Extends the general [Worktree Workflow](worktree-workflow.md) with team-specific patterns.

---

## Branch Naming Convention

```
feat/{feature}/{role}
```

Examples:
- `feat/user-auth/backend`
- `feat/user-auth/frontend`
- `feat/user-auth/tests`
- `feat/dashboard/backend`
- `feat/dashboard/frontend`

All branches are created from the feature branch (not main):

```bash
# Start from the feature branch
git checkout feat/{feature}

# Create role branches
git branch feat/{feature}/backend
git branch feat/{feature}/frontend
git branch feat/{feature}/tests
```

---

## Worktree Setup Commands

The **lead** creates worktrees before spawning teammates:

Worktrees go INSIDE the repo at `.worktrees/&lt;task&gt;`. A sibling path (`../\{project\}-backend`)
sits outside the session's project directory, so the harness silently bounces any `cd` into it
and the teammate ends up operating on the PRIMARY tree — platform#9870 (#3319).

```bash
# Create worktrees — one per implementing teammate
git worktree add .worktrees/backend  -b feat/{feature}/backend  origin/main
git worktree add .worktrees/frontend -b feat/{feature}/frontend origin/main
git worktree add .worktrees/tests    -b feat/{feature}/tests    origin/main

# Verify — both the registration AND that each branch is the one you asked for
git worktree list
```

**Directory layout after setup:**

&lt;!-- ascii-lint-disable: balanced-corners --&gt;
```
{project}/                  ← Primary tree (lead + code-reviewer)
└── .worktrees/
    ├── backend/            ← backend-architect works here
    ├── frontend/           ← frontend-dev works here
    └── tests/              ← test-engineer works here
```

`.worktrees/` is gitignored. Nesting inside the repo is what keeps each teammate's `cd` from
being bounced back to the project root.

---

## Teammate Assignment

Include the worktree path in each teammate's spawn prompt:

| Teammate | Worktree | Working Directory |
|----------|----------|-------------------|
| backend-architect | `../\{project\}-backend/` | Full project access, writes to backend dirs |
| frontend-dev | `../\{project\}-frontend/` | Full project access, writes to frontend dirs |
| test-engineer | `../\{project\}-tests/` | Full project access, writes to test dirs |
| code-reviewer | Main worktree | Read-only, reviews across all worktrees |

**Spawn prompt addition:**

```
## Your Working Directory
Work EXCLUSIVELY in: /path/to/{project}-backend/
Do NOT modify files in other worktrees.
Commit your changes to the feat/{feature}/backend branch.
```

---

## Merge Strategy

After all teammates complete, the lead merges each role branch:

### Squash Merge Per Role (Recommended)

```bash
# Switch to feature branch
git checkout feat/{feature}

# Merge each role as a single commit
git merge --squash feat/{feature}/backend
git commit -m "feat({feature}): backend implementation"

git merge --squash feat/{feature}/frontend
git commit -m "feat({feature}): frontend implementation"

git merge --squash feat/{feature}/tests
git commit -m "test({feature}): complete test suite"
```

### Handling Merge Conflicts

Conflicts typically occur in shared files:
- **Type definitions** — backend and frontend may define overlapping types
- **Package files** — both may add dependencies
- **Config files** — shared configuration

Resolution priority:
1. Backend types are authoritative (they own the API contract)
2. For package conflicts, combine both additions
3. For config conflicts, merge manually

---

## Cleanup

After successful merge and verification:

```bash
# Remove worktrees
git worktree remove ../{project}-backend
git worktree remove ../{project}-frontend
git worktree remove ../{project}-tests

# Delete role branches
git branch -d feat/{feature}/backend
git branch -d feat/{feature}/frontend
git branch -d feat/{feature}/tests

# Verify cleanup
git worktree list
git branch --list "feat/{feature}/*"
```

---

## When to Skip Worktrees

Not every Agent Teams session needs worktrees. Skip when:

| Condition | Skip Worktrees? | Reason |
|-----------|-----------------|--------|
| Read-only roles only (audit, review) | Yes | No file writes = no conflicts |
| Small feature (&lt; 5 files) | Yes | File overlap unlikely |
| Teammates work in non-overlapping directories | Yes | Natural isolation |
| Single-stack scope (backend-only or frontend-only) | Yes | One writer, others are reviewers |
| Research/debugging task | Yes | Exploration, not implementation |

When skipping worktrees, teammates work in the same directory. The lead should assign **clear file ownership** in spawn prompts to prevent conflicts:

```
## File Ownership
You own: src/api/, src/models/, src/services/
Do NOT modify: src/components/, src/features/, src/hooks/
```

---

## Config Sharing (CC 2.1.63+)

Project configs and auto-memory are **automatically shared** across worktrees (CC 2.1.63+). No manual setup needed:

- `.claude/settings.json` and `CLAUDE.md` available in every worktree
- Auto-memory persists — teammates inherit learned patterns
- Plugins are discovered from any worktree

---

## Worktree + Agent Teams Checklist

Before spawning teammates:

- [ ] Feature branch exists (`feat/\{feature\}`)
- [ ] Role branches created from feature branch
- [ ] Worktrees added for each implementing teammate
- [ ] Each teammate's spawn prompt includes worktree path
- [ ] Code-reviewer assigned to main worktree (read-only)

After all teammates complete:

- [ ] All role branches have commits
- [ ] Squash merge each role into feature branch
- [ ] Merge conflicts resolved
- [ ] Integration tests pass on merged branch
- [ ] Worktrees removed
- [ ] Role branches deleted


### Test Requirements Matrix

# Test Requirements Matrix

Phase 5 test-generator MUST produce tests matching the change type.

## Required Tests by Change Type

| Change Type | Required Tests | Testing Rules |
|-------------|---------------|--------------------------|
| API endpoint | Unit + Integration + Contract | `integration-api`, `verification-contract`, `mocking-msw` |
| DB schema/migration | Migration + Integration | `integration-database`, `data-seeding-cleanup` |
| UI component | Unit + Snapshot + A11y | `unit-aaa-pattern`, `integration-component`, `a11y-testing`, `e2e-playwright` |
| Business logic | Unit + Property-based | `unit-aaa-pattern`, `pytest-execution`, `verification-techniques` |
| LLM/AI feature | Unit + Eval | `llm-evaluation`, `llm-mocking` |
| Full-stack feature | All of the above | All matching rules |

## Real-Service Detection (Phase 6)

Before running integration tests, detect infrastructure:

```python
# Auto-detect real service testing capability (PARALLEL)
Glob(pattern="**/docker-compose*.yml")
Glob(pattern="**/testcontainers*")
Grep(pattern="testcontainers|docker-compose", glob="requirements*.txt")
Grep(pattern="testcontainers|docker-compose", glob="package.json")
```

If detected: run integration tests against real services, not just mocks. Reference `testing-integration` rules: `integration-database`, `integration-api`, `data-seeding-cleanup`.

## Phase 9 Gate

**Do NOT proceed to Phase 9 (Documentation) if test-generator produced 0 tests.** Return to Phase 5 and generate tests for the implemented code.

## Test Coverage Expectations

| Tier | Minimum Coverage | Notes |
|------|-----------------|-------|
| 1. Interview | Happy path only | Focus on correctness, not coverage |
| 2. Hackathon | None required | Tests are bonus |
| 3. MVP | Unit + 1 integration | Cover critical paths |
| 4-5. Growth/Enterprise | Unit + integration + e2e | Full matrix above applies |
| 6. Open Source | Exhaustive | Every public API must have tests |

## Test Runner Detection

```python
# Detect test framework (PARALLEL)
Glob(pattern="**/jest.config*")
Glob(pattern="**/vitest.config*")
Glob(pattern="**/pytest.ini")
Glob(pattern="**/pyproject.toml")
Grep(pattern="\"test\":", glob="package.json")
```

Use the detected runner for all generated tests. Do not introduce a new test framework unless the project has none.


### Tier Classification

# Tier Classification & Workflow Mapping

Project complexity tiers determine architecture ceilings and workflow phases.

## Auto-Detection Signals

Scan codebase for: README keywords (take-home, interview), `.github/workflows/`, Dockerfile, terraform/, k8s/, CONTRIBUTING.md.

## Tier Classification

| Signal | Tier | Architecture Ceiling |
|--------|------|---------------------|
| README says "take-home", time limit | **1. Interview** (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/interview-mode.md`) | Flat files, 8-15 files |
| &lt; 10 files, no CI | **2. Hackathon** | Single file if possible |
| `.github/workflows/`, managed DB | **3. MVP** | MVC monolith |
| Module boundaries, Redis, queues | **4. Growth** | Modular monolith, DI |
| K8s/Terraform, monorepo | **5. Enterprise** | Hexagonal/DDD |
| CONTRIBUTING.md, LICENSE | **6. Open Source** | Minimal API, exhaustive tests |

If confidence is low, use `AskUserQuestion` to ask the user. Pass detected tier to ALL downstream agents — see `scope-appropriate-architecture`.

## Tier → Workflow Mapping

| Tier | Phases | Max Agents |
|------|--------|-----------|
| 1. Interview | 1, 5 only | 2 |
| 2. Hackathon | 5 only | 1 |
| 3. MVP | 1-6, 9 | 3-4 |
| 4-5. Growth/Enterprise | All 10 | 5-8 |
| 6. Open Source | 1-7, 9-10 | 3-4 |

Use `AskUserQuestion` to verify scope (full-stack / backend-only / frontend-only / prototype) and constraints.

## Orchestration Mode

- Agent Teams (mesh) when complexity >= 2.5 (GA since CC 2.1.33)
- Task tool (star) otherwise; `ORCHESTKIT_FORCE_TASK_TOOL=1` to override
- Load orchestration modes: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/implement/references/orchestration-modes.md")`

## Tier Override

When auto-detection is ambiguous (e.g., a monorepo with no CI yet), prefer the **lower** tier to avoid over-engineering. The user can always escalate.

Manual override example:
```
AskUserQuestion(questions=[{
  "question": "Detected signals for both MVP and Growth. Which tier fits best?",
  "options": [
    {"label": "3. MVP", "description": "MVC monolith, 3-4 agents"},
    {"label": "4. Growth", "description": "Modular monolith with DI, up to 8 agents"}
  ]
}])
```


### Worktree Isolation Mode

# Worktree Isolation Mode

## When to Use

- Feature touches 5+ files across multiple directories
- Multiple developers working on same branch
- Risky refactoring that may need rollback
- Agent Teams mode with parallel agents editing overlapping files

## Workflow

### 1. Enter Worktree

```python
# CC 2.1.49: Create new worktree
EnterWorktree(name="feat-{feature-slug}")

# CC 2.1.105: Reuse existing worktree via path parameter
# Use this when resuming work on an existing feature branch
EnterWorktree(path="/path/to/existing/worktree")
```

This creates (or switches into):
- New branch `feat-\{feature-slug\}` from HEAD (or reuses existing worktree)
- Working directory at `.claude/worktrees/feat-\{feature-slug\}/`
- Session CWD switches to the worktree automatically

**Tip (CC 2.1.105+):** When a worktree already exists from a prior session, use the `path` parameter to switch into it instead of creating a new one. Check with `git worktree list` first.

### 2. Implement in Isolation

All implementation phases (4-8) run in the worktree. Benefits:
- Main branch stays clean — no partial changes
- Multiple agents can work without stepping on each other
- Easy rollback: just delete the worktree branch

### 3. Merge Back

After Phase 8 (E2E Verification) passes:

```bash
# Return to original branch
git checkout {original-branch}

# Merge the feature
git merge feat-{feature-slug}

# Clean up worktree (prompted on session exit)
```

### 4. Conflict Resolution

If merge conflicts arise:
1. Show conflicting files to user
2. Present diff with `AskUserQuestion` for resolution choices
3. Apply user's chosen resolution
4. Re-run Phase 6 verification on merged result

## Context Gate Integration

When running in a worktree, the `context-gate` SubagentStart hook raises concurrency limits:
- `MAX_CONCURRENT_BACKGROUND`: 6 → 10 (worktree isolation reduces contention)
- `MAX_AGENTS_PER_RESPONSE`: 8 → 12

This is safe because worktree agents operate on an isolated file tree.

## Config Sharing (CC 2.1.63+)

Project configs and auto-memory are **automatically shared** across git worktrees. No manual copying needed:

- `.claude/settings.json` — shared across all worktrees
- `.claude/memory/` — auto-memory persists across worktrees
- `CLAUDE.md` — project instructions available in every worktree
- Plugin configs — plugins discovered from any worktree

## CLI Alternative

Users can also start worktrees manually:

```bash
claude --worktree    # or -w
```

This creates the worktree before the session starts, equivalent to `EnterWorktree` but at CLI level.

## Limitations

- Cannot nest worktrees (worktree inside worktree)
- Session exit prompts to keep or remove the worktree
- Some git operations (rebase, bisect) may behave differently in worktrees


### Worktree Workflow

# Git Worktree Workflow

Isolate feature work in dedicated worktrees for clean development and easy rollback.

## When to Use Worktrees

| Scenario | Worktree? | Reason |
|----------|-----------|--------|
| Large feature (5+ files) | YES | Isolation prevents pollution |
| Experimental/risky changes | YES | Easy to discard entirely |
| Parallel feature development | YES | Work on multiple features |
| Hotfix while mid-feature | YES | Don't stash incomplete work |
| Quick bug fix (1-2 files) | No | Overhead not worth it |

## Setup Commands

Put the worktree INSIDE the repo, at `.worktrees/&lt;task&gt;`. Never at a sibling
`../&lt;repo&gt;-&lt;task&gt;`: a sibling path sits outside the session's project directory, and the
harness bounces any `cd` that leaves it. The command appears to succeed, then every later
command runs in the PRIMARY tree. That is the failure behind platform#9870, where work was
committed onto another agent's branch (#3319).

```bash
# Create worktree with new branch — helper does the safety checks and prints the path
WT=$(~/.claude/hooks/worktree-new.sh <task> feature/feature-name) && cd "$WT"

# By hand, if you must — note the path is INSIDE the repo
git worktree add .worktrees/<task> -b feature/feature-name origin/main

# From an existing branch
git worktree add .worktrees/<task> existing-branch

# List all worktrees
git worktree list

# Confirm the move actually took — the cd reset is silent
pwd
```

## Workflow

```bash
# 1. Create worktree
WT=$(~/.claude/hooks/worktree-new.sh auth feature/user-auth) && cd "$WT"
pwd   # must be the worktree, NOT the repo root

# 2. Work in isolation
# ... make changes, commit normally ...

# 3. Merge back (from the primary tree)
cd /path/to/myapp
git checkout main
git merge feature/user-auth

# 4. Cleanup
git worktree remove .worktrees/auth
git branch -d feature/user-auth
```

## Merge Strategies

| Strategy | When to Use |
|----------|-------------|
| **Merge commit** | Default, preserves history |
| **Squash merge** | Many small commits, clean history wanted |
| **Rebase first** | Linear history preferred |

```bash
# Squash merge (single commit)
git merge --squash feature/user-auth
git commit -m "feat: Add user authentication"

# Rebase then merge (linear).
# Prefer `git -C <path>` over cd — it never depends on the cd sticking.
git -C .worktrees/auth rebase main
git merge feature/user-auth
```

## Cleanup with Uncommitted Changes

```bash
# Check for uncommitted changes
git -C .worktrees/auth status

# If changes exist, either:
# Option A: Commit them
git -C .worktrees/auth add . && git -C .worktrees/auth commit -m "WIP: save progress"

# Option B: Stash them
git -C .worktrees/auth stash push -m "feature-auth-wip"

# Option C: Discard (CAREFUL!)
git -C .worktrees/auth checkout -- .

# Then remove worktree (run from the primary tree)
git worktree remove .worktrees/auth
```

## Best Practices

1. **Location:** Always `.worktrees/&lt;task&gt;` inside the repo, never a sibling `../project-task`
2. **Short-lived:** Merge within 1-3 days
3. **One feature per worktree:** Don't mix concerns
4. **Regular sync:** Rebase from main frequently
5. **Clean before remove:** Always check `git status`



---

## Checklists (1)

### Implementation Review

# Implementation Review Checklist

Use this checklist before marking implementation as complete.

## Scope Verification

- [ ] All acceptance criteria from micro-plan are met
- [ ] No unplanned files were modified
- [ ] No features were added beyond original scope
- [ ] If scope changed, it was documented and justified

## Code Quality

- [ ] All tests pass
- [ ] Type checking passes (mypy/tsc)
- [ ] Linting passes (no warnings)
- [ ] No TODO/FIXME left behind (or tracked in issues)

## Testing Coverage

- [ ] Unit tests for new functions/methods
- [ ] Integration tests for API endpoints
- [ ] Edge cases covered
- [ ] Error paths tested

## Documentation

- [ ] Code comments for complex logic
- [ ] API documentation updated (if endpoints added)
- [ ] README updated (if setup changed)

## Scope Creep Score

- [ ] Score 0-2: Proceed
- [ ] Score 3-5: Document additions in PR
- [ ] Score 6+: Split into separate PR

## Final Checks

- [ ] PR description matches implementation
- [ ] Commit messages are clear
- [ ] No sensitive data committed
- [ ] Works in development environment

## Sign-off

```
Reviewer: _______________
Date: _______________
Scope Creep Score: ___/10
Ready to merge: [ ] Yes [ ] No - needs: _______________
```
