Agents Concept Architecture Worktrees AGENTS.md Lifecycle Commands Merge QA Sprint Plan Approaches Safety Resources

Multi-Agent
Development

How stitchwand uses parallel Claude Code agents in isolated git worktrees to build across all four packages simultaneously. A learning document for operating the system.

Last updated: 2026-04-09

Contents

1. The Concept

A single Claude Code session can only work in one place at a time. When your monorepo has four packages and 31 pages, a single agent becomes a bottleneck. The solution: run multiple Claude Code instances in parallel, each in its own git worktree with its own branch, scoped to a specific part of the codebase by an AGENTS.md file.

This is sometimes called the "paperclip pattern" after the Paperclip orchestration framework, but Claude Code supports it natively through three mechanisms: manual worktrees (what we use), subagents (automated delegation), and Agent Teams (experimental coordinated sessions).

stitchwand monorepo | |-- main branch (coordinator) | +-- ../stitchwand-agent-core branch: agent/core-engine | scope: packages/core/ | +-- ../stitchwand-agent-mcpcli branch: agent/mcp-cli | scope: packages/mcp-server/ + packages/cli/ | +-- ../stitchwand-agent-web branch: agent/web-app scope: apps/web/

Each agent is a separate terminal window running claude in its worktree directory. They don't talk to each other. They share the same git history but have isolated file systems. When done, you merge branches back to main in dependency order.

2. Architecture — How It Maps to This Codebase

The stitchwand monorepo has a strict dependency chain that determines how agents are scoped and in what order branches merge:

Dependency Chain @stitchwand/core ←←←←←←←←←←←←←←← NO dependencies @stitchwand/mcp-server ←←←←←←← depends on core @stitchwand/cli ←←←←←←←←←←←← depends on core @stitchwand/web ←←←←←←←←←←←← depends on core

This means:

Agent Assignment

Agent 1

Core Engine
packages/core/

27 exports, 315+ tests, 8 modules. Parsers, validation, diff, convert, types. The brain.

Agent 2

MCP + CLI
packages/mcp-server/
packages/cli/

6 MCP tools, 5 CLI commands. Thin wrappers over core.

Agent 3

Web App
apps/web/

31 pages, admin dashboard, Starter Kits, Design Swarm. All UI.

This split works because packages never import from each other laterally. MCP doesn't import from CLI. Web doesn't import from MCP. Everything goes through core.

3. Git Worktrees Explained

A git worktree is a second (or third, or fourth) working directory for the same repository. Each worktree has its own branch, its own staged files, and its own node_modules. But they all share the same .git history.

Creating Worktrees

terminal — from main repo root
# Create 3 sibling directories, each on its own branch
git worktree add ../stitchwand-agent-core   -b agent/core-engine
git worktree add ../stitchwand-agent-mcpcli -b agent/mcp-cli
git worktree add ../stitchwand-agent-web    -b agent/web-app

# Each needs its own node_modules
cd ../stitchwand-agent-core   && npm install && npx turbo build --filter=@stitchwand/core
cd ../stitchwand-agent-mcpcli && npm install && npx turbo build --filter=@stitchwand/core
cd ../stitchwand-agent-web    && npm install && npx turbo build --filter=@stitchwand/core
Disk space: Each npm install creates ~175MB of node_modules. With 3 worktrees that's ~525MB. Check df -h before creating worktrees. If space is tight, you can symlink node_modules from the main repo, but Vite/turbo may have path resolution issues.

Listing & Removing Worktrees

terminal
# List all worktrees
git worktree list

# Remove a worktree (after merging)
git worktree remove ../stitchwand-agent-core

# Delete the branch too
git branch -d agent/core-engine

Filesystem Layout

/Users/you/dev/ | +-- stitchwand/ main repo, branch: main | .git/ shared git database | node_modules/ | packages/core/ | packages/mcp-server/ | packages/cli/ | apps/web/ | +-- stitchwand-agent-core/ worktree, branch: agent/core-engine | .git (file, not dir — points to main .git) | node_modules/ | AGENTS.md scope: packages/core/ only | +-- stitchwand-agent-mcpcli/ worktree, branch: agent/mcp-cli | AGENTS.md scope: packages/mcp-server/ + cli/ | +-- stitchwand-agent-web/ worktree, branch: agent/web-app AGENTS.md scope: apps/web/ only

4. AGENTS.md — Scoping Each Agent

AGENTS.md is a markdown file placed at the root of each worktree. When you run claude in that directory, Claude Code reads it automatically and treats it as project instructions. It defines:

AGENTS.md vs CLAUDE.md: CLAUDE.md is Claude Code's native config file (checked into the repo). AGENTS.md is a cross-tool universal standard (adopted by Cursor, Copilot, Codex, etc.). Claude Code reads both. In our worktrees, we use AGENTS.md at the worktree root because it's not committed to the main branch.

Example: Core Engine AGENTS.md

../stitchwand-agent-core/AGENTS.md
# Agent 1 — Core Engine

## Scope
`packages/core/` only. Do not modify files outside this directory.

## Branch
`agent/core-engine` — forked from `main`.

## Responsibilities
- Parsers (DESIGN.md, design tokens)
- Validation engine, Diff engine, Convert pipeline
- Type definitions, Test coverage (target 80%+)

## Sprint Tasks
- P1-004: Extraction accuracy
- P2-002: Test coverage gaps

## Key Rules
1. Only additive exports — never rename/remove existing signatures
2. Strict TypeScript — no `any`
3. Use Result<T, E> error pattern
4. Run `npx vitest run` before every commit

The Web Agent Includes Next.js 16 Warning

The web agent's AGENTS.md preserves the critical Next.js 16 compatibility warning from the existing apps/web/AGENTS.md:

../stitchwand-agent-web/AGENTS.md (excerpt)
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file
structure may all differ from your training data. Read the relevant
guide in `node_modules/next/dist/docs/` before writing any code.
<!-- END:nextjs-agent-rules -->

5. Agent Lifecycle — Start, Monitor, Stop

Starting Agents

Open a separate terminal window for each agent. Each runs an independent Claude Code session:

Terminal 1 — Core Engine
cd /Users/dilshaus/dev/stitchwand-agent-core && claude
Terminal 2 — MCP + CLI
cd /Users/dilshaus/dev/stitchwand-agent-mcpcli && claude
Terminal 3 — Web App
cd /Users/dilshaus/dev/stitchwand-agent-web && claude

Monitoring Progress

Terminal 4 — Coordinator (main repo)
# See all worktrees and their HEAD commits
git worktree list

# See what each agent has committed
git log --oneline agent/core-engine..HEAD    # core agent commits
git log --oneline agent/mcp-cli..HEAD        # mcp+cli agent commits
git log --oneline agent/web-app..HEAD        # web agent commits

# See changed files per agent branch
git diff --stat main..agent/core-engine
git diff --stat main..agent/mcp-cli
git diff --stat main..agent/web-app

# Watch commits in real-time (run in a 4th terminal)
watch -n 5 'echo "=== CORE ===" && git log --oneline -3 agent/core-engine && echo "\n=== MCP+CLI ===" && git log --oneline -3 agent/mcp-cli && echo "\n=== WEB ===" && git log --oneline -3 agent/web-app'

Stopping an Agent

In the agent's terminal, type /exit or press Ctrl+C. The worktree and branch persist — you can resume later by running claude in the same directory. Claude Code will read AGENTS.md again on startup.

Mid-Sprint: Cherry-Picking Core Changes

If the core agent adds a new export that other agents need:

terminal — update mcp agent with core changes
# In the MCP+CLI worktree
cd /Users/dilshaus/dev/stitchwand-agent-mcpcli
git cherry-pick <commit-hash-from-core>
npx turbo build --filter=@stitchwand/core

6. Claude Code Commands & Prompts

These are copy-pasteable prompts to give your agents when starting them. Each prompt tells the agent what to work on and how to verify its work.

Starting Prompt — Core Engine

Paste into Claude Code (core worktree)
Read AGENTS.md for your scope and rules. You are the Core Engine agent.

Your sprint tasks:
1. P1-004: Improve token extraction accuracy in packages/core/src/convert/
   - Audit parsers against real design system docs (Red Hat, Material, Polaris)
   - Add accuracy test fixtures comparing extracted vs known-good values
2. P2-002: Fill test coverage gaps
   - Add DESIGN.md round-trip tests (parse -> generate -> parse = same result)
   - Add prompt completeness tests (all tokens appear in generated output)
   - Target 80%+ coverage: npx vitest run --coverage

After each change, run: npx vitest run
Only commit when all tests pass. Only modify files in packages/core/.

Starting Prompt — MCP + CLI

Paste into Claude Code (mcpcli worktree)
Read AGENTS.md for your scope and rules. You are the MCP + CLI agent.

Your sprint tasks:
1. Integration test coverage for all 6 MCP tools and 5 CLI commands
   - Test each tool with real input data, not mocks
   - Verify error messages are clear and actionable
2. Error handling audit
   - Ensure all Result<T, E> errors from core are properly unwrapped
   - CLI should show human-readable error messages with exit code 1
   - MCP tools should return structured error responses

After each change, run: npx vitest run
Only modify files in packages/mcp-server/ and packages/cli/.
Never duplicate business logic from core — thin wrappers only.

Starting Prompt — Web App

Paste into Claude Code (web worktree)
Read AGENTS.md for your scope and rules. You are the Web App agent.

CRITICAL: Read node_modules/next/dist/docs/ before using any Next.js API.
This is Next.js 16 with breaking changes from your training data.

Your sprint tasks (ordered by priority):
1. P1-001: Add Copy-to-clipboard buttons on ALL output panels
   - /design-md library preview, editor output, merge output
   - All export displays across the app
2. P1-002: Fix MarkdownPreview rendering (tables, token sections, nested lists)
3. P1-003: Add "MUST USE attached DESIGN.md" instructions to ALL generated prompts
   - Starter Kits, Prompt Library, Console, Doc Writer, Live PRD, Brand Voice
4. P1-005: Stitch preview auto-refresh on DESIGN.md content change
5. P2-001: Finish bug tracker panel in admin dashboard

Dev server: port 3333. After each change, run: npx vitest run
Only modify files in apps/web/.

Monitoring Prompt — Check Agent Status

Paste into Claude Code (main repo)
Check the status of all 3 agent worktrees:
1. Run `git worktree list` to confirm all 3 exist
2. For each branch (agent/core-engine, agent/mcp-cli, agent/web-app):
   - Show the last 5 commits with `git log --oneline -5 <branch>`
   - Show changed file count with `git diff --stat main..<branch> | tail -1`
3. Report which agent has the most/least activity

Stopping Prompt — Graceful Agent Shutdown

Paste into any agent before stopping
Before I stop you, please:
1. Run npx vitest run and confirm all tests pass
2. Commit any uncommitted work with a descriptive message
3. List what you completed and what remains from your sprint tasks
4. Note any issues or blockers for the next session

Resume Prompt — Restarting an Agent

Paste into Claude Code when resuming
Read AGENTS.md for your scope. Check `git log --oneline -10` to see
what was done in previous sessions on this branch. Then run
`npx vitest run` to confirm the baseline is green.

Continue from where the last session left off. The remaining tasks are
listed in AGENTS.md under "Sprint Tasks".

7. Merge-Back Workflow

Order matters. The dependency chain dictates merge sequence:

1. agent/core-engine main rebuild core dist 2. agent/mcp-cli main resolve package-lock conflicts 3. agent/web-app main final merge 4. Full verification turbo build && turbo test
terminal — full merge-back sequence
# Step 1: Merge core (no dependencies)
cd /Users/dilshaus/dev/stitchwand
git merge agent/core-engine
npx turbo build --filter=@stitchwand/core
npx turbo test --filter=@stitchwand/core

# Step 2: Merge MCP + CLI
git merge agent/mcp-cli
npm install  # resolve any package-lock conflicts
npx turbo build --filter=@stitchwand/mcp-server --filter=@stitchwand/cli
npx turbo test --filter=@stitchwand/mcp-server --filter=@stitchwand/cli

# Step 3: Merge web
git merge agent/web-app
npx turbo build
npx turbo test

# Step 4: Full verification
npx turbo build && npx turbo test

# Step 5: Cleanup
git worktree remove ../stitchwand-agent-core
git worktree remove ../stitchwand-agent-mcpcli
git worktree remove ../stitchwand-agent-web
git branch -d agent/core-engine agent/mcp-cli agent/web-app
Most common merge conflict: package-lock.json. Fix: accept either side, then run npm install to regenerate it correctly.

8. QA Step

QA happens after all merges, before code freeze. It has two parts:

Automated QA

Full turbo build && turbo test from main. All 443+ tests must pass. Zero failures. If anything breaks, bisect which merge caused it.

Manual QA

Click through every P1 fix in the browser. Copy buttons work? Preview renders tables? Prompts say "MUST USE DESIGN.md"? Extraction matches source docs?

QA Checklist

CheckHow to VerifyPass Criteria
Full test suitenpx turbo build && npx turbo test443+ tests, 0 failures
P1-001: Copy buttonsOpen /design-md, click Copy on every output panelClipboard contains correct content
P1-002: PreviewPaste real DESIGN.md, check Preview tabTables, sections, lists render correctly
P1-003: Prompt refsGenerate a Starter Kit, read the Stitch Prompt outputContains "MUST USE attached DESIGN.md"
P1-004: ExtractionConvert 3 real design systems, spot-check 10 valuesAll values match official docs
P1-005: Preview refreshReplace DESIGN.md content in editorPreview updates immediately

9. Finishing the App — Multi-Agent Sprint Plan

Everything after MCP + CLI (day-5 in the action list) runs as multi-agent. Below is the aggressive parallel plan. Each sprint creates fresh worktrees, runs agents, merges back, QAs, and cleans up.

Sprint naming convention: Worktree branches follow agent/<phase>-<package> pattern. Example: agent/p2-core, agent/p3-web.

Sprint 1 Wire Core Pages (days 6-7)

Wire Convert, DESIGN.md, Analyze, Prompt Library, and Components pages to real @stitchwand/core functions. Replace all setTimeout/mock data.

AgentTasksFiles
CoreAdd any missing exports needed by web pages. Ensure convert(), validate(), diff() handle all edge cases. Add round-trip tests.packages/core/src/
MCP+CLIAdd integration tests for all 6 tools and 5 commands. Error handling audit.packages/mcp-server/, packages/cli/
WebWire /convert, /design-md, /analyze to real API routes. Wire /prompts and /components with localStorage CRUD. Remove ALL setTimeout calls.apps/web/src/app/

Sprint 2 Advanced Features + Polish (days 8-9a)

Starter Kits, Design Swarm, Doc Writer, UI polish, Labs gating. All running in parallel.

AgentTasksFiles
CoreExtraction accuracy audit (5 major design systems). Coverage push to 80%+.packages/core/src/
MCP+CLIAdd lint, analyzeComponent as new MCP tools + CLI commands. Polish help text and error messages.packages/mcp-server/, packages/cli/
WebWire Starter Kits (wizard, generation, export), Design Swarm (session UI, agent chat), Doc Writer (markdown editor, templates). UI polish (Copy buttons, preview rendering, prompt refs). Labs feature flags.apps/web/src/

Sprint 3 Deploy + Launch (days 9-10)

Deployment is sequential but prep work parallelizes.

AgentTasksFiles
Corenpm publish prep: package.json metadata, README, CHANGELOG. Final coverage report.packages/core/
MCP+CLInpm publish prep for both packages. Smithery listing prep. MCP Inspector final test.packages/mcp-server/, packages/cli/
WebVercel deployment config. OG images, meta tags, analytics. Admin dashboard final polish. Loading states, error boundaries.apps/web/

Phase 2 Growth & Extension (May)

AgentTasks
CoreA11y linter engine with axe-core (6 rule categories). Export as a11yLint().
MCP+CLIAdd a11y_lint as MCP tool #7 and CLI command. Chrome extension content script scaffold.
WebWire A11y linter into Analyze tab. Curate 20+ Stitch-optimized prompt templates. Chrome extension popup UI.

Phase 3 Billing & Auth (June-July)

Adds a 4th agent for infrastructure. Auth0 setup happens on main before forking worktrees.

AgentTasks
CoreDrizzle ORM schema (users, teams, designSystems, usageEvents). Migration helpers. Tests against in-memory SQLite.
MCP+CLIAuth-aware tool wrappers (API key check). CLI login/logout commands. Usage event reporting.
WebAuth0 middleware on /app/* routes. Stripe checkout + customer portal. localStorage → DB migration. Plan-gated features. Admin role system.
InfraGitHub Actions CI (validate DESIGN.md on PR). Stripe webhook handler. Sentry error tracking.
phase 3 worktree setup
# Pre-fork: set up Auth0 + Neon on main first
npm install @auth0/nextjs-auth0 drizzle-orm @neondatabase/serverless
git commit -m "Add auth + DB dependencies"

# Then fork worktrees
git worktree add ../stitchwand-agent-core   -b agent/p3-core
git worktree add ../stitchwand-agent-mcpcli -b agent/p3-mcp-cli
git worktree add ../stitchwand-agent-web    -b agent/p3-web
git worktree add ../stitchwand-agent-infra  -b agent/p3-infra

Phase 4 Platform (Aug-Oct)

Adds a VS Code extension as a new package. 4 agents.

AgentTasks
CoreFigma Variables API bridge (two-way sync). Design Systems Manager data model (versioning, sharing).
MCP+CLIfigma_sync + manage_systems MCP tools. CLI stitch figma-sync and stitch systems commands.
WebEnterprise SSO (SAML/OIDC via Auth0). Team management UI. Design Systems Manager dashboard.
VS CodeNew packages/vscode-ext: DESIGN.md syntax highlighting, token autocomplete, inline validation, webview preview.

10. Three Approaches to Multi-Agent

Claude Code offers three ways to run multiple agents. We use Approach 1 (manual worktrees) because it gives the most control and transparency.

1. Manual Worktrees

What we use. You create worktrees with git worktree add, run claude in each, merge manually. Full control. Works today.

2. Subagents

Define .claude/agents/*.md files with YAML frontmatter. Parent Claude delegates to child agents automatically. Set isolation: worktree for safe parallel edits.

3. Agent Teams

Experimental. One "team lead" spawns teammates that coordinate via shared task lists and messaging. Requires CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.

Subagent Definition Example

If you want to try subagents in future sprints, create .claude/agents/core-engine.md:

.claude/agents/core-engine.md
---
name: core-engine
description: Works on packages/core exclusively. Parsers, validation, diff, types.
isolation: worktree
tools: Read, Glob, Grep, Bash, Edit, Write
model: opus
maxTurns: 50
---

You are the Core Engine agent for stitchwand.
Only modify files in packages/core/.
Run `npx vitest run` after every change.
Never rename or remove existing exports.

Agent Teams (Experimental)

Enable Agent Teams
# Add to .claude/settings.json
{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}

Then prompt Claude Code to spawn teammates:

Agent Teams prompt example
Create an agent team with 3 teammates:
- core-engine: works on packages/core/, fixes extraction accuracy
- mcp-cli: works on packages/mcp-server/ and packages/cli/, adds integration tests
- web-app: works on apps/web/, adds copy buttons and fixes preview rendering
Each teammate should work in its own worktree.

11. Cross-Package Safety Rules

RuleWhy
Core agent: only ADD exportsRenaming or removing breaks MCP, CLI, and web simultaneously
MCP/CLI: thin wrappers onlyBusiness logic belongs in core. Duplicating it means bugs live in two places
Web: import from @stitchwand/coreNever reach into core's internal modules — use the barrel export
All: run tests before committingBroken tests on a branch = broken tests after merge
Merge in dependency orderCore → MCP+CLI → Web. Never merge web before core.
package-lock.json will conflictAccept either side, run npm install to regenerate
If core changes mid-sprint: Cherry-pick the specific commit into other agent branches. Don't merge the entire core branch early — it defeats the purpose of isolation.

12. Resources & Links

Internal stitchwand Documents

Related files in the repo:

  • AGENTS-SETUP-REPORT.md — Setup report for the v0.9 sprint agent session
  • V0.9-LAUNCH-PLAN.md — Sprint timeline, bug tracker, testing philosophy
  • CLAUDE.md — Project context (read by all agents)
  • apps/web/AGENTS.md — Next.js 16 compatibility warning