Home / Session 6
session-6.md — ~/hacking-with-ai
6

Production Gap Analysis with Agent Teams

Scale AI work across codebases with worktrees and parallel agents

60 min Agent Teams + Worktree Isolation Loading...
Session 6 of 8

// Overview

Pick any project. Compare it against a reference implementation using your team's .claude/rules/. Claude produces a gap analysis. Then spin up a team of agents — each in its own git worktree — to fix the gaps in parallel. Each agent creates an independent PR with gh. No merge conflicts.

Learning Objectives

// Theory

Why Agent Teams?

10 min

One agent, one context window — it fills up on large codebases. Agent teams: each agent gets its own context window, its own worktree, its own branch. Worktree isolation = git-level parallelism. Each agent has a full copy of the repo on a separate branch. Gap analysis is a natural fit: analysis is read-only (safe), fixes are independent (parallelizable).

Key Concepts

  • One agent hits context limits on large codebases. Agent teams split work across multiple context windows.
  • Worktree isolation = git-level parallelism. Each agent gets a full copy of the repo on its own branch. They can all work at the same time without stepping on each other.
  • The gap analysis workflow is a natural fit: Phase 1 (analysis) is read-only and safe. Phase 2 (fixes) splits into independent tasks — one per gap area.
  • Key concept: assign non-overlapping file sets to each agent. Agent 1 edits chart/ files, Agent 2 edits src/ files, Agent 3 edits build config. No file appears in two agents' scope = no merge conflicts.
  • claude --teammate-mode=in-process starts agents in the same process — simplest way to run teams. No tmux setup needed.
  • Subagents vs Agent Teams: subagents are spawned within a session, share the parent's context, and handle short-lived tasks. Agent teams are separate processes with their own worktrees, own context windows, and are designed for long-lived parallel work.
  • Teammates can request plan approval before implementing — configure this so agents check in before making changes.
  • Teammate messaging: use Shift+Down to cycle between teammates; send direct messages to specific agents or broadcast to all.
  • Task dependencies let you define ordering between agent tasks. Tasks expire after 3 days if not completed.
  • TeammateIdle and TaskCompleted hooks enable quality gates — run checks when an agent finishes or goes idle.

Agent Teams + Worktrees

10 min

claude --teammate-mode=in-process starts agents as in-process subagents (no tmux needed). Each agent gets isolation: worktree — a temporary git worktree at .claude/worktrees/. Worktree = separate working directory + separate branch, sharing the same .git repo. Agents can run in parallel because they never touch the same files on the same branch. gh pr create from each worktree branch creates independent, conflict-free PRs.

Key Concepts

  • claude --teammate-mode=in-process starts agents as in-process subagents — no tmux needed.
  • Each agent gets isolation: worktree — a temporary git worktree at .claude/worktrees/.
  • Worktree = separate working directory + separate branch, sharing the same .git repo.
  • Agents can run in parallel because they never touch the same files on the same branch.
  • gh pr create from each worktree branch creates independent, conflict-free PRs.
  • Status line hooks include a worktree field (name, path, branch, original repo dir).
  • PR review status shows in the footer as a clickable link — color-coded by state: green=approved, yellow=changes requested, red=failing checks, gray=pending, purple=merged. Useful for monitoring PRs created by agent teams without leaving Claude Code.

// Setup

Ensure you have a target project and a reference implementation available

bash
cd <your-target-project>
ls ../<reference-project>/        # Reference implementation
ls .claude/rules/                 # Team standards
Verify: Target project, reference project, and .claude/rules/ files all accessible

// Challenge

Gap Analysis → Parallel Fix

35m +15m bonus

Phase 1 (15 min): Ask Claude to compare your target project against the reference using .claude/rules/. Claude produces a full report document with: executive summary, standards framework, gap areas (K8s, observability, resilience, quality, testing, CI/CD, security), compliance checklist, and remediation roadmap. Review the report — this is your working document, not a commit artifact. The report structure follows the pattern from gap-analysis.md: each finding cites STANDARD, CURRENT, REFERENCE, IMPACT, SEVERITY. Phase 2 (20 min): Start claude --teammate-mode=in-process. Paste or reference the gap analysis report as input. Tell Claude: "Read this gap analysis. Create a team of agents to fix the MUST items. Each agent works in its own worktree on non-overlapping files." Claude reads the report, creates agents, each agent fixes its assigned gaps and creates a PR with gh pr create. Verify PRs are independent and conflict-free.

✓ Success Criteria

  • Gap analysis report produced with full structure (exec summary, standards, gaps, checklist, roadmap)
  • Report used as input to drive agent team work — agents reference specific findings from the report
  • At least 2 agents ran in parallel with worktree isolation
  • Each agent created an independent PR via gh pr create
  • PRs don't conflict with each other
⚠ Hints (click to reveal)
  • Start with the MUST items from the report — they're the highest priority and safest to fix
  • The report is the input, not a deliverable to commit — it tells Claude what to fix and why
  • Tell each agent which files/directories to touch — this prevents overlap
  • Use ultrathink when generating the initial gap analysis — it needs deep cross-project comparison
  • Run claude agents to verify agent definitions before creating the team
  • Use /diff to review what each agent changed before creating PRs — catch issues early
  • After agent teams finish, clean up worktrees: git worktree list to see them, git worktree remove to delete. Also prune stale branches with git branch -d.

Code Playground

Interactive

Try These Prompts

Gap Analysis
ultrathink Compare this project against <reference-project>/ using the standards in .claude/rules/. For each gap: cite the rule, show what the reference does, show what this project is missing, and rate severity (MUST/SHOULD/NICE). Focus on: K8s readiness, observability, resilience, code quality, testing.
ultrathink triggers deep analysis — Claude examines both codebases thoroughly
Expected: Standards-grounded gap report with concrete findings
Create Agent Team
Create a team of 3 agents to fix the top gaps. Each agent should work in its own worktree: agent-infra (K8s config in chart/), agent-code (observability + resilience in src/), agent-quality (build config + static analysis). Use patterns from <reference-project>/ as the template.
Start Claude with --teammate-mode=in-process first
Expected: 3 agents spawn, each in its own worktree with a separate branch
Create PRs
Each agent: commit your changes, then run gh pr create with a descriptive title and body referencing the gap analysis.
gh pr create --title '...' --body '...' from each worktree branch
Expected: 3 independent PRs created, no merge conflicts
Review Agent Changes with /diff
/diff
Run /diff in each agent's context to review changes before creating PRs — catch unintended edits early
Expected: Shows a diff of all changes made by the agent in its worktree
Verify Independence
List all PRs with gh pr list. For each, check files changed with gh pr view <number> --json files. Confirm no file appears in more than one PR.
If files overlap, the task split was wrong — refine agent assignments
Expected: Clean separation of concerns across PRs

Code Examples

Gap Analysis Report Structure
Gap Analysis Report Format
===========================
For each finding, cite three layers:

STANDARD:     <Industry standard> + <Team rule from .claude/rules/>
CURRENT:      What the target project does today
REFERENCE:    What the reference implementation does
IMPACT:       What breaks or degrades because of this gap
SEVERITY:     MUST / SHOULD / NICE

Example:
  STANDARD:     CNCF: Startup probes prevent liveness killing slow-starting JVM apps
                .claude/rules/spring-boot.md: Configure health probes
  CURRENT:      Liveness + readiness only. No startup probe.
  REFERENCE:    startupProbe with 100s budget (10 checks x 10s)
  IMPACT:       JVM + DB migration takes 60-90s. Liveness fires at 30s = restart loops
  SEVERITY:     MUST
Agent Team Workflow
Agent Team Workflow
===================
1. START
   claude --teammate-mode=in-process

2. ANALYZE (you + Claude, single context)
   "ultrathink Compare this project against <reference> using .claude/rules/"
   -> Gap report with MUST/SHOULD/NICE ratings

3. SPLIT WORK (assign non-overlapping file sets)
   Agent 1: chart/ files         -> branch: fix/infra
   Agent 2: src/**/*.java        -> branch: fix/code
   Agent 3: build config files   -> branch: fix/quality

4. PARALLEL FIX (each agent in its own worktree)
   +-- agent-infra ---- chart/ ----------- fix/infra ---+
   |-- agent-code ----- src/**/*.java ---- fix/code ----|
   +-- agent-quality -- build.gradle ----- fix/quality -+

5. CREATE PRs (from each worktree branch)
   gh pr create --title "Fix: ..." --body "..."

6. VERIFY
   gh pr list -> 3 PRs, independent files, no conflicts
   gh pr view <n> --json files -> confirm no overlap
Worktree Mechanics
Git Worktrees for Agent Teams
==============================
What is a worktree?
  A second (or third, fourth...) working directory for the same repo.
  Each worktree has its own branch, its own files, but shares .git history.

  repo/                        <- main branch (your working copy)
  .claude/worktrees/agent-1/   <- fix/infra branch (agent 1's copy)
  .claude/worktrees/agent-2/   <- fix/code branch (agent 2's copy)

Why no conflicts?
  Each agent edits different files on different branches.
  PRs are independent — reviewable and mergeable separately.

How Claude Code uses them:
  isolation: worktree           <- in agent definitions
  claude -w                     <- start Claude in a worktree
  --worktree                    <- same as -w

Creating PRs from worktrees:
  cd .claude/worktrees/agent-1/
  git add -A && git commit -m "Fix: ..."
  gh pr create --title "..." --body "..."

Key rule: assign non-overlapping file sets to each agent.
  If two agents edit the same file -> merge conflict.
  Split by directory or by concern.
Subagents vs Agent Teams
Subagents vs Agent Teams
========================
Feature              Subagents                    Agent Teams
-----------          ----------                   -----------
Spawning             Within a session             Separate processes
Context              Shares parent's window       Own context window each
Worktree             Same working directory       Own worktree + branch
Lifetime             Short-lived (single task)    Long-lived (parallel work)
Use case             Quick delegated subtask      Multi-area codebase changes
Isolation            None (same branch)           Full git-level isolation
PR creation          From parent's branch         Each agent creates own PR

When to use subagents:
  - Small, focused tasks within a larger session
  - Tasks that need the parent's context (files already read, decisions made)
  - Quick lookups or code generation that feed back into the main task

When to use agent teams:
  - Multiple independent changes across a codebase
  - Work that benefits from git-level isolation (no merge conflicts)
  - Tasks large enough to fill their own context window
  - Gap analysis remediation, multi-module refactoring, parallel feature work
Agent Team Cleanup
Agent Team Cleanup
==================
After agent team sessions, clean up stale worktrees and branches.

1. List worktrees:
   git worktree list
   # Shows all worktrees including .claude/worktrees/agent-*

2. Remove finished worktrees:
   git worktree remove .claude/worktrees/agent-infra
   git worktree remove .claude/worktrees/agent-code

3. Prune stale worktree references:
   git worktree prune

4. Clean up merged branches:
   git branch --merged main | grep 'fix/' | xargs git branch -d

5. Verify PRs are merged before cleanup:
   gh pr list --state merged --author @me

Best practices:
  - Clean up worktrees after PRs are merged
  - Don't delete worktrees with unmerged changes
  - Use git worktree prune to remove stale refs
  - Tasks expire after 3 days if not completed

// Key Takeaways

// Resources

Agent Teams Documentation Git Worktrees documentation GitHub CLI (gh) reference