Intro
You're about to read a lot of lines about how to manage AI coding agents. Yes, I had an AI write most of this. No, the irony is not lost on me.
Think of this as a parenting book for AI agents. You have to repeat to the AI agents, about the the same number of times that you have to repeat to your kids to put on their shoes in the morning. And this number is not low!!
But unlike your kids, at least the agents don't roll their eyes at you — they just quietly hallucinate instead.
1. Why Agent Teams
A single agent conversation works well for small, focused tasks. But real engineering work often involves multiple concerns -- security, performance, test coverage, documentation, migration -- that benefit from specialized attention.
Agent teams let you:
- Parallelize work - three agents reviewing a codebase simultaneously finish in the time it takes one to review a third of it
- Specialize context - an agent prompted as a "security auditor" catches things a general-purpose agent misses because its entire context window is dedicated to that lens
- Reduce hallucination - smaller, focused tasks produce more accurate results than asking one agent to "review everything"
- Scale to large codebases - each agent can explore a different part of the codebase without hitting context limits
2. Designing Effective Agents
2.1 Define Agents with Clear Roles
Every agent should have a single, well-defined responsibility. In OpenCode, you define agents as markdown files or in opencode.json:
<!-- .opencode/agents/security-auditor.md -->
---
description: Performs security audits and identifies vulnerabilities
mode: subagent
tools:
write: false
edit: false
---
You are a security expert. Focus on identifying potential security issues.
Look for:
- Input validation vulnerabilities
- Authentication and authorization flaws
- Data exposure risks
- Dependency vulnerabilities
- Configuration security issues
- Hardcoded secrets and credentials
For each finding, report:
- Severity (CRITICAL / HIGH / MEDIUM / LOW)
- File path and line number
- Description of the vulnerability
- Recommended fix
Key principles:
- One concern per agent. A security agent should not also be reviewing performance
- Explicit output format. Tell the agent exactly how to structure its findings
- Tool restrictions match the role. A review agent should not have write access. A build agent needs this permission
2.2 Choose the Right Agent Mode
OpenCode supports two agent modes:
| Mode | Purpose | How to invoke |
|---|---|---|
| Primary | Main agents you interact with directly. Switch with Tab. | Tab key or keybind |
| Subagent | Specialized agents invoked by primary agents or via @mention. |
@agent-name or automatically by the Task tool |
Use primary agents for modes of working (Build vs. Plan). Use subagents for specialized tasks that the primary agent delegates to.
2.3 Match Models to Tasks
Not every task needs the most capable model. OpenCode lets you assign models per agent:
{
"agent": {
"build": {
"model": "anthropic/claude-opus-4-6"
},
"explore": {
"model": "anthropic/claude-haiku-4-20250514"
},
"security-review": {
"model": "anthropic/claude-sonnet-4-20250514"
}
}
}
Guidelines:
- Exploration / search tasks: Use a fast, cheap model (Haiku, GPT-4o mini). These tasks are IO-bound, not intelligence-bound
- Code generation: Use a strong model (Claude Opus, GPT-5). Quality matters here
- Code review: A mid-tier model (Claude Sonnet) is often sufficient - it reads more than it writes
- Planning: Consider using a reasoning model with higher reasoning effort for complex architectural decisions
3. Isolating Agent Work with Git Worktrees
This is the most important technique for agent teams that write code.
When multiple agents need to make changes to the same repository, they will conflict unless each agent has its own isolated workspace.
3.1 What Are Git Worktrees?
Git worktrees let you check out multiple branches of the same repository simultaneously in separate directories.
Unlike cloning the repo multiple times, worktrees share the same .git object store -- they are lightweight and fast.
my-project/ # main worktree (main branch)
my-project-wt-security/ # worktree on fix/security branch
my-project-wt-performance/ # worktree on fix/performance branch
my-project-wt-tests/ # worktree on fix/test-coverage branch
3.2 The Worktree Workflow for Agent Teams
Step 1: Create worktrees from main.
git worktree add ../my-project-wt-security -b fix/security
git worktree add ../my-project-wt-performance -b fix/performance
git worktree add ../my-project-wt-tests -b fix/test-coverage
Step 2: Spawn agents, each pointing at its own worktree.
Each agent operates in a completely independent directory. It can read, write, run tests, and commit without affecting the others.
In OpenCode, you achieve this by spawning Task agents with different working directories. Each subagent receives a prompt that includes the worktree path and instructions to commit to its branch.
Step 3: After all agents finish, merge branches back.
git checkout main
git merge fix/security
git merge fix/performance
git merge fix/test-coverage
Step 4: Clean up worktrees.
git worktree remove ../my-project-wt-security
git worktree remove ../my-project-wt-performance
git worktree remove ../my-project-wt-tests
3.3 Avoiding Merge Conflicts
The biggest risk with parallel agent work is merge conflicts. Mitigate this by:
- Assigning non-overlapping file scopes. If Agent A fixes
application.yamland Agent B adds test files undersrc/test/, they won't conflict. - Separating by concern layer. Security fixes touch config and auth code. Performance fixes touch repositories and services. Test additions create new files.
- Using a merge agent. If conflicts are expected, spawn a dedicated agent after the merge step to resolve them.
- Preferring additive changes. Agents that add new files (tests, docs, migrations) rarely conflict with agents that modify existing files.
3.4 Why Not Just Use Branches Without Worktrees?
You could have agents work on branches sequentially, but:
- Worktrees let agents run in parallel -- each has a real filesystem checkout.
- No need to stash, switch, or reset between agent runs.
- Build artifacts (
target/,node_modules/,dist/) are per-worktree, so builds don't collide. - The
.gitobject store is shared, so disk usage is minimal.
3.5 Alternative: GitHub PR-Based Workflow
For teams that want CI validation before merging, push each branch and create PRs:
- Agents push commits to their respective branches
- Open one PR per branch against main
- CI runs on each PR independently
- Review and merge PRs after checks pass
This trades local speed for proper CI validation and human review gates.
4. Orchestrating Agent Teams
4.1 Parallel vs. Sequential Execution
Parallel - when agents work on independent concerns:
- Security review + performance review + test coverage review
- Frontend changes + backend changes + database migrations
- Multiple independent bug fixes
Sequential - when one agent's output feeds into another:
- Plan agent creates a design -> Build agent implements it
- Build agent writes code -> Review agent checks it
- Research agent gathers context -> Implementation agent uses it
4.2 The Orchestrator Pattern
For complex workflows, designate one primary agent as the orchestrator. It:
- Breaks the task into subtasks.
- Spawns subagents for each subtask (in parallel where possible).
- Collects results.
- Synthesizes a final output or takes the next action.
In OpenCode, the primary Build agent naturally acts as an orchestrator when it uses the Task tool to spawn subagents.
You can control which subagents an orchestrator can invoke using task permissions:
{
"agent": {
"orchestrator": {
"mode": "primary",
"permission": {
"task": {
"*": "deny",
"security-review": "allow",
"performance-review": "allow",
"test-review": "allow"
}
}
}
}
}
4.3 Custom Commands for Repeatable Workflows
If you run the same agent team pattern frequently, encode it as a custom command:
<!-- .opencode/commands/full-review.md -->
---
description: Run a full code review with security, performance, and test coverage agents
agent: build
---
Spawn three review agents in parallel:
1. @security-auditor - Review the codebase for security vulnerabilities
2. @performance-reviewer - Review the codebase for performance issues
3. @test-coverage-reviewer - Review the codebase for test coverage gaps
After all three complete, synthesize their findings into a single report
organized by priority. Save the report to docs/review-findings.md.
Now the team can run /full-review anytime.
5. Prompt Engineering for Agents
5.1 Be Specific About Output Format
Bad:
Review the code for security issues.
Good:
Review the codebase for security vulnerabilities. For each finding, report:
- Severity: CRITICAL / HIGH / MEDIUM / LOW
- File: exact path and line number
- Description: what the vulnerability is
- Fix: specific remediation steps
Organize findings by severity. If a category has no issues, state that explicitly.
5.2 Constrain the Scope
Agents perform better with boundaries:
- "Review only files under
src/main/java/.../authn/" is better than "review the whole codebase." - "Focus on the changes in the last 5 commits" is better than "review everything."
- "Check for N+1 queries in the repository layer" is better than "find performance issues."
5.3 Tell the Agent What NOT to Do
Explicit constraints prevent wasted work:
DO NOT write any code. This is a READ-ONLY review.
DO NOT suggest changes to test files.
DO NOT report issues in files under src/main/java/.../tools/ (these are excluded from production).
5.4 Use AGENTS.md for Project Context
OpenCode reads AGENTS.md (or CLAUDE.md for Claude Code compatibility) from your project root. This file gives every agent baseline context about your project:
# My Project
## Stack
Java 21, Spring Boot 3.x, PostgreSQL, gRPC, Kafka
## Architecture
Event-driven microservice. Kafka notifications are consumed, matched to
plugin instances via SpEL expressions, and dispatched via gRPC.
## Conventions
- All database access goes through Spring Data JPA repositories
- gRPC services are in the `service/v1/` package
- Tests use JUnit 5 + Mockito + Testcontainers
- Feature flags are in `application.yaml` under `featureflags:`
## What NOT to modify
- Files in `src/main/java/.../tools/` are developer utilities, not production code
- Database migrations in `src/main/resources/db/migration/` should only be appended to, never modified
This context is automatically included in every agent's prompt.
5.5 Use Skills for Reusable Behaviors
OpenCode supports Agent Skills -- reusable instruction sets that agents can load on demand:
<!-- .opencode/skills/spring-security-review/SKILL.md -->
---
name: spring-security-review
description: Review Spring Boot applications for common security misconfigurations
---
## What I check
- Default Spring profiles and their security implications
- Actuator endpoint exposure
- CORS configuration
- CSRF protection (for REST APIs)
- Bean Validation scope (`spring-boot-starter-validation` in compile vs test)
- Hardcoded credentials in application.yaml
- Feature flags that disable security controls
Agents automatically see available skills and load them when relevant.
6. Permissions and Safety
6.1 Principle of Least Privilege
Every agent should have only the permissions it needs:
| Agent Role | read | edit | bash | webfetch |
|---|---|---|---|---|
| Code reviewer | allow | deny | deny | deny |
| Build agent | allow | allow | allow | allow |
| Plan agent | allow | ask | ask | allow |
| Explorer | allow | deny | deny | deny |
In OpenCode, configure this per agent:
{
"agent": {
"reviewer": {
"mode": "subagent",
"permission": {
"edit": "deny",
"bash": "deny"
}
}
}
}
6.2 Granular Bash Permissions
The bash tool is the most powerful and most dangerous. Use pattern-based permissions:
{
"permission": {
"bash": {
"*": "ask",
"git status *": "allow",
"git diff *": "allow",
"git log *": "allow",
"npm test *": "allow",
"npm run build *": "allow",
"rm *": "deny",
"git push *": "deny",
"git reset --hard *": "deny"
}
}
}
This allows safe read-only git commands and test/build runs, requires approval for everything else, and blocks destructive operations.
6.3 Protect Sensitive Files
OpenCode denies reading .env files by default. Extend this for your project:
{
"permission": {
"read": {
"*": "allow",
"*.env": "deny",
"*.env.*": "deny",
"**/secrets/*": "deny",
"**/keypair/*": "deny"
}
}
}
6.4 The Doom Loop Guard
OpenCode detects when an agent repeats the same tool call 3 times with identical input (the "doom loop") and prompts for approval. Keep this enabled -- it prevents runaway agents from wasting tokens on stuck operations.
7. Managing Context Windows
Context window management is one of the most impactful factors in agent quality. Every token of irrelevant context dilutes the agent's attention on the actual task.
7.1 Use Subagents to Partition Context
The primary reason to use subagents is context isolation. Each subagent gets a fresh context window, which means:
- A security review agent's 200K context is 100% focused on security.
- An explore agent searching for files doesn't pollute the build agent's context with search results.
- Failed approaches in one subagent don't confuse another.
7.2 Use the Explore Agent for Search
When you need to find files or search code, delegate to the Explore subagent rather than running grep/glob directly in your primary context. The Explore agent is:
- Read-only (cannot modify files).
- Fast (optimized for search operations).
- Context-isolated (search results stay in the subagent's context, only the summary returns).
7.3 Use Plan Mode Before Build Mode
OpenCode's Plan agent (Tab to switch) analyzes code without making changes. Use it to:
- Understand the problem.
- Create an implementation plan.
- Switch to Build mode and execute.
This prevents wasted edits and reverts that consume context.
7.4 Keep Prompts Focused
Every message you send becomes part of the context. Avoid:
- Pasting entire files into the chat (use
@filenamereferences instead). - Asking multiple unrelated questions in one message.
- Repeating instructions the agent already has in AGENTS.md.
7.5 Use /compact for Long Sessions
When context gets large, OpenCode automatically compacts it. You can also trigger this manually.
The compaction agent summarizes the conversation while preserving key decisions and code references.
8. Verification and Quality Gates
8.1 Always Verify Agent Output
Never trust agent output blindly. Build verification into your workflow:
- After code generation: Run the test suite. Run the linter. Run the build.
- After code review: Spot-check the highest-severity findings manually. Agents sometimes report false positives.
- After refactoring: Run the full test suite and compare behavior.
8.2 Use the Build-Test-Fix Loop
The most reliable pattern for code-writing agents:
- Agent writes code.
- Agent runs tests.
- If tests fail, agent reads the error and fixes the code.
- Repeat until tests pass.
Encode this in your prompts:
After making changes, run `mvn test` to verify. If any tests fail,
read the failure output and fix the issues. Repeat until all tests pass.
Do not consider the task complete until the build succeeds.
8.3 Use Todo Lists for Complex Tasks
OpenCode's TodoWrite tool helps agents track multi-step work. Encourage its use:
Before starting, create a todo list breaking down the implementation into
discrete steps. Mark each step as completed when done. Do not batch
completions -- mark each step done immediately after finishing it.
This gives you real-time visibility into agent progress and ensures nothing is forgotten.
8.4 Commit Incrementally
For agents making multiple changes, instruct them to commit after each logical unit of work:
Commit after each fix is verified. Use conventional commit messages.
Do not batch all changes into a single commit.
This makes it easy to revert individual changes if something goes wrong.
9. Cost and Performance Optimization
9.1 Right-Size Your Models
The single biggest cost lever. A Haiku-class model costs ~20x less than an Opus-class model. Use the cheapest model that produces acceptable quality for each task.
9.2 Limit Agent Steps
For cost-sensitive environments, cap the number of agentic iterations:
{
"agent": {
"quick-fix": {
"steps": 10,
"description": "Fast fixes with limited iterations"
}
}
}
9.3 Scope Your Searches
Instead of "search the entire codebase," tell agents exactly where to look:
Search only in src/main/java/.../authn/ for authentication-related code.
Do not explore test files or configuration files for this task.
9.4 Parallelize Independent Work
When spawning multiple subagents, launch them all in a single message. This runs them concurrently rather than sequentially, cutting wall-clock time proportionally.
9.5 Cache Project Context in AGENTS.md
A well-written AGENTS.md prevents agents from spending tokens rediscovering project structure. Include:
- Tech stack and framework versions.
- Directory layout.
- Key architectural patterns.
- Build and test commands.
- Naming conventions.
10. Common Anti-Patterns
10.1 The "Do Everything" Agent
Problem: Asking one agent to "review the code for security, performance, test coverage, code style, and documentation."
Why it fails: The agent's attention is split across too many concerns. It produces shallow findings across all categories instead of deep findings in any one.
Fix: Spawn specialized agents, each focused on one concern.
10.2 The Unsupervised Writer
Problem: Giving an agent full write access and a vague instruction like "fix the bugs."
Why it fails: The agent may make sweeping changes, introduce new bugs, or modify files it shouldn't touch.
Fix: Use Plan mode first. Review the plan. Then switch to Build mode with explicit scope constraints.
10.3 The Context Hog
Problem: Pasting entire files, logs, and stack traces into the chat, then asking a question.
Why it fails: The relevant information is buried in noise. The agent may hallucinate connections between unrelated pieces of context.
Fix: Use @file references. Use the Explore subagent for search. Paste only the relevant snippet.
10.4 The Parallel Writer Without Isolation
Problem: Spawning multiple agents that write to the same files on the same branch.
Why it fails: Race conditions. Lost writes. Corrupted state.
Fix: Use git worktrees. One branch per agent. Merge after all agents complete.
10.5 The Infinite Retry Loop
Problem: Agent hits an error, retries the same approach, hits the same error, retries again.
Why it fails: Wastes tokens and time. The agent lacks the context to try a different approach.
Fix: Instruct agents to try at most 2-3 times, then report the error and move on. Use the doom loop guard.
10.6 Skipping Verification
Problem: Accepting agent output without running tests or reviewing changes.
Why it fails: Agents produce plausible-looking code that may have subtle bugs, especially in edge cases.
Fix: Always run the test suite after agent changes. Use git diff to review before committing.
11. Recipes: Real-World Agent Team Configurations
11.1 The Code Review Team
Three read-only agents reviewing in parallel:
{
"agent": {
"security-reviewer": {
"mode": "subagent",
"description": "Reviews code for security vulnerabilities",
"model": "anthropic/claude-sonnet-4-20250514",
"tools": { "write": false, "edit": false, "bash": false }
},
"performance-reviewer": {
"mode": "subagent",
"description": "Reviews code for performance issues",
"model": "anthropic/claude-sonnet-4-20250514",
"tools": { "write": false, "edit": false, "bash": false }
},
"test-coverage-reviewer": {
"mode": "subagent",
"description": "Reviews test coverage and test quality",
"model": "anthropic/claude-sonnet-4-20250514",
"tools": { "write": false, "edit": false, "bash": false }
}
}
}
11.2 The Fix Team (with Worktrees)
Three agents, each fixing issues on its own branch:
# Setup
git worktree add ../project-wt-security -b fix/security
git worktree add ../project-wt-performance -b fix/performance
git worktree add ../project-wt-tests -b fix/test-coverage
# Spawn agents (each pointed at its worktree directory)
# Agent 1: Fix security findings in ../project-wt-security
# Agent 2: Fix performance issues in ../project-wt-performance
# Agent 3: Add missing tests in ../project-wt-tests
# Merge
git checkout main
git merge fix/security
git merge fix/performance
git merge fix/test-coverage
# Cleanup
git worktree remove ../project-wt-security
git worktree remove ../project-wt-performance
git worktree remove ../project-wt-tests
11.3 The Plan-Build-Verify Pipeline
Sequential agents, each building on the previous:
- Plan agent (read-only) analyzes the task and produces a plan.
- Build agent (full access) implements the plan.
- Verify agent (read-only + bash for tests) runs the test suite and reports results.
<!-- .opencode/commands/implement.md -->
---
description: Plan, implement, and verify a feature
agent: build
---
Follow this workflow:
1. Switch to Plan mode. Analyze $ARGUMENTS and create a detailed
implementation plan. List the files to change and the changes to make.
2. Switch to Build mode. Implement the plan step by step. Commit after
each logical change.
3. Run the full test suite. If any tests fail, fix them. Repeat until
all tests pass.
4. Run the linter. Fix any issues.
5. Summarize what was done and what was changed.
11.4 The Documentation Team
{
"agent": {
"api-documenter": {
"mode": "subagent",
"description": "Generates API documentation from source code",
"tools": { "bash": false }
},
"readme-writer": {
"mode": "subagent",
"description": "Updates README and getting-started guides",
"tools": { "bash": false }
},
"changelog-writer": {
"mode": "subagent",
"description": "Generates changelog entries from git history",
"permission": {
"bash": {
"*": "deny",
"git log *": "allow",
"git diff *": "allow"
}
}
}
}
}
Summary
| Practice | Why |
|---|---|
| One concern per agent | Deeper analysis, fewer hallucinations |
| Git worktrees for parallel writes | Isolation prevents conflicts |
| Least-privilege permissions | Prevents accidental damage |
| Right-sized models per task | 10-20x cost savings without quality loss |
| AGENTS.md with project context | Eliminates redundant exploration |
| Verification after every change | Catches agent mistakes early |
| Plan before Build | Reduces wasted edits and reverts |
| Subagents for context isolation | Better focus, less noise |
| Custom commands for repeatable workflows | Consistency across team members |
| Incremental commits | Easy rollback of individual changes |
The best agent workflows are not about trusting agents more -- they are about structuring work so that trust is not required. Isolate, specialize, verify, and iterate.