---
title: "Implement: References"
description: "19 references for the Implement skill: Agent Phases; Agent Teams Full Stack; Agent Teams Phases; Agent Teams Security Audit; Blast Radius Clarification; Cc Enhancements; Claude Code; E2e Verification; Feedback Loop; Interview Mode; Manual Worktree Pattern; Micro Planning Guide; Orchestration Modes; Scope Creep Detection; Team Worktree Setup; Test Requirements Matrix; Tier Classification; Worktree Isolation Mode; Worktree Workflow"
canonical: "https://orchestkit.yonyon.ai/docs/reference/skills/implement/references"
---

# Implement: References

19 references for the Implement skill: Agent Phases; Agent Teams Full Stack; Agent Teams Phases; Agent Teams Security Audit; Blast Radius Clarification; Cc Enhancements; Claude Code; E2e Verification; Feedback Loop; Interview Mode; Manual Worktree Pattern; Micro Planning Guide; Orchestration Modes; Scope Creep Detection; Team Worktree Setup; Test Requirements Matrix; Tier Classification; Worktree Isolation Mode; Worktree Workflow

> Part of the [Implement](/docs/reference/skills/implement) skill reference. The main page carries the skill itself; this page holds material that used to sit at the bottom of it.

## References (19)

### 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.


### Claude Code

# Claude Code adapter: implement

Slash invoke: `/ork:implement`

YAML `hooks:` / `command:` lines in this skill's frontmatter stay Claude-only.
They use `$\{CLAUDE_PLUGIN_ROOT\}/hooks/bin/run-hook.mjs` and are ignored by pi.

Session chain files live at `.claude/chain/` (state.json, decisions.json, capabilities.json).
Other hosts should persist equivalent run state in their own session store.

Agent spawn form, when used: `Agent(ork:...)` is Claude Code. Portable body text uses the skill name.

Lines that still mention a Claude-only path in the body:

```
Host-neutral workflow. Invoke by skill name (`implement`). Claude Code slash routing, YAML hook loaders, and `.claude/chain` live in `references/claude-code.md`.
Write(".claude/chain/capabilities.json", JSON.stringify({
Read(".claude/chain/state.json")
Write(".claude/chain/state.json", JSON.stringify({
Write(".claude/chain/state.json", JSON.stringify(state))
If `.claude/chain/assess-verdict.json` exists with a `feature` matching this run and `verdict == "fail"` (composite < the 5.5 `min_pass` in `../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`):
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("references/blast-radius-clarification.md")`.
> **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).
```

## Session recovery

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).


### 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`
