8. Best Practices
Task Decomposition Strategies
Clear boundaries principle:
Good decomposition:
- Agent 1: Backend API endpoints (/api/users/*)
- Agent 2: Frontend components (src/components/users/*)
- Agent 3: Database migrations (db/migrations/users/)
Why good:
- Non-overlapping file sets (no merge conflicts)
- Clear interfaces (API contracts)
- Independent testing (each layer testable)Bad decomposition:
- Agent 1: User authentication
- Agent 2: User authorization
- Agent 3: User session management
Why bad:
- Overlapping files (auth.ts touched by all 3)
- Interdependencies (auth needs sessions, sessions need auth)
- Sequential coupling (can't parallelize effectively)Interface-first approach:
- Define contracts: Agree on function signatures, API schemas before parallel work
- Type stubs: Create TypeScript types/interfaces first, implement separately
- Mock boundaries: Each agent works with mocked dependencies initially
- Integration phase: Team lead coordinates final integration
Example:
// Team lead defines interface first
interface UserService {
authenticate(email: string, password: string): Promise<User>;
authorize(user: User, resource: string): Promise<boolean>;
}
// Agent 1 implements authenticate
// Agent 2 implements authorize
// No merge conflicts (different functions)Coordination Patterns
Fan-out, fan-in:
Team lead
│
├─ Agent 1: Task A ──┐
├─ Agent 2: Task B ──┼──> Team lead synthesizes
└─ Agent 3: Task C ──┘Sequential phases with parallelization:
Phase 1 (Sequential):
Team lead: Define architecture
Phase 2 (Parallel):
├─ Agent 1: Implement backend
├─ Agent 2: Implement frontend
└─ Agent 3: Write tests
Phase 3 (Sequential):
Team lead: Integration + validationHierarchical delegation:
Team lead
│
├─ Agent 1 (Backend lead)
│ ├─ Agent 1a: Controllers
│ └─ Agent 1b: Services
│
└─ Agent 2 (Frontend lead)
├─ Agent 2a: Components
└─ Agent 2b: State managementAGENTS.md for Compound Learning
Agent teams benefit from a shared context file that accumulates cross-session learnings: patterns that worked, pitfalls to avoid, codebase-specific gotchas. This file is called AGENTS.md (analogous to CLAUDE.md but scoped to agentic workflows).
What to put in AGENTS.md:
## Proven Patterns
- Use Interface-First decomposition for this codebase (see src/types/)
- Backend agent must run `db:migrate` before tests — env is not auto-seeded
## Pitfalls
- Do NOT modify auth.ts and session.ts in parallel — circular imports cause test failures
- Linter runs on save; do not commit with lint errors, the CI gate is strict
## Style
- All API responses must follow the ApiResponse<T> wrapper type
- Error codes live in src/constants/errors.ts — always reuse, never hardcode stringsCritical rule: never let agents write AGENTS.md directly. ETH Zürich research (Gloaguen et al., 2026) confirms that LLM-generated context files reduce task success by ~3% and increase inference costs by 20%+, compared to a ~4% improvement from developer-written files. The mechanism: agents generate generic, bloated context that creates cognitive overhead for every subsequent agent reading it.
Every line in AGENTS.md should be approved by a human. If a teammate identifies a new pattern worth documenting, it sends a suggestion to the team lead, and the lead decides whether to add it.
Maintenance: Review AGENTS.md after each team session (Retro step of the Factory Model). Remove entries that are no longer relevant. Stale instructions are actively harmful, not neutral.
Git Worktree Management
Why worktrees matter:
- Each agent works in separate git worktree (isolated file system)
- Prevents file locking conflicts
- Enables parallel file modifications
Setup:
# Main repository
git worktree add ../project-agent1 main
# Agent 1 works in project-agent1/
# Agent 2 works in project-agent2/
# Team lead works in project/
# All sync via git commitsBest practices:
- ✅ One worktree per agent
- ✅ Frequent commits (continuous merge)
- ✅ Descriptive branch names (
agent1-backend-api,agent2-frontend-ui) - ❌ Don't modify same files across worktrees without coordination
Cost Optimization
Token-saving strategies:
Lazy spawning: Only spawn agents when parallelization clearly benefits
Bad: "Spawn 3 agents to implement this button" Good: "Spawn agents for multi-layer security review"Context pruning: Remove irrelevant files from agent context
# Tell agent what to ignore "Review backend API, ignore frontend files"Progressive escalation: Start with single agent, escalate to teams if needed
Step 1: Single agent attempts task Step 2: If complexity high, spawn teamResult caching: Reuse agent findings across similar tasks
"Agent 1 found security issues in auth.ts. Agent 2, check if user.ts has same patterns."Hard token budgets per agent: Assign domain-specific limits to prevent runaway consumption
bash# In task brief to each teammate "Frontend agent: stay under 180k tokens total. Backend agent: stay under 280k tokens total. Auto-pause and report status at 85% of your budget."Token costs scale linearly with team size: a 5-agent team can consume 5× the tokens of a single session. Caps prevent one agent's rabbit hole from blowing the entire session budget.
Quality Assurance
Validation checklist:
- [ ] All agents completed: No hanging tasks
- [ ] Merge conflicts resolved: Clean git history
- [ ] Tests passing: Automated test suite green
- [ ] Human review: Code inspection (don't trust blindly)
- [ ] Cross-agent consistency: Naming, patterns aligned
Red flags:
- ⚠️ Agents finished at very different times (imbalanced load)
- ⚠️ Many merge conflicts (poor task decomposition)
- ⚠️ Tests failing after merge (integration issues)
- ⚠️ Inconsistent code style (agents didn't follow shared standards)
Mitigation:
# After agent teams complete
git diff main..agent-teams-branch # Review all changes
npm test # Run full test suite
npm run lint # Check code styleLoop Guardrails
Agent teams can get stuck in unproductive retry cycles without hard iteration limits. Two mechanisms prevent this:
MAX_ITERATIONS per teammate:
Set a hard cap in the task brief for each teammate:
"Maximum 8 attempts on any single failing task.
Before retrying, answer: What specifically failed? What one change would fix it?
If still blocked after 8 attempts, stop and report to team lead."The mandatory reflection prompt ("What failed? What specific change would fix it?") reduces stuck agents substantially. It forces the agent to change approach rather than repeat the same failing action with minor variations.
Kill and reassign criteria:
- Stuck 3+ iterations on the same blocker → kill the task, reassign with more specific context
- Task consumed >85% of its token budget with no commit → pause and report
- No progress after 2 reflection cycles → escalate to team lead
Dedicated Reviewer Teammate
For production agent teams, adding a read-only reviewer agent improves output quality without slowing throughput:
Setup:
Reviewer brief:
- Model: Claude Opus 5 (for thoroughness)
- Tools available: lint, run tests, security-scan only — no file writes
- Trigger: automatically review on every TaskCompleted event
- Scope: the specific files changed in that task, not the full codebase
- Output: structured findings (blocking / non-blocking) added to shared task listRatio: 1 reviewer per 3-4 builders. With fewer builders, the reviewer becomes a bottleneck; with more, the review queue backs up.
Why read-only matters: a reviewer with write access will start fixing issues itself, which creates merge conflicts and defeats the purpose of parallel isolation.