Orchestration - Automated Multi-Agent Coordination
Scheduling
Goal
Automatically orchestrate multi-agent execution with task decomposition, native/fallback dispatch, memory coordination, progress monitoring, verification, QA cross-review, retry, and result collection.
Intent signature
- User asks to orchestrate, run in parallel, automate multi-agent execution, or coordinate full-stack work end to end.
- Task requires multiple specialist agents and a persistent review/remediation loop.
When to use
- Complex feature requires multiple specialized agents working in parallel
- User wants automated execution without manually spawning agents
- Full-stack implementation spanning backend, frontend, mobile, and QA
- User says "run it automatically", "run in parallel", or similar automation requests
When NOT to use
- Simple single-domain task -> use the specific agent directly
- User wants step-by-step manual control -> use oma-coordination
- Quick bug fixes or minor changes
Expected inputs
- Complex feature or workflow request
- Project config, model/vendor routing, agent types, task constraints, and workspace/session needs
- Acceptance criteria and verification expectations
Expected outputs
- Orchestrator session state, task board, progress files, result files, and final summary
- Specialist agent outputs after mechanical checks, automated verify, and QA cross-review
- Review history and retry/remediation status when loops fail
Dependencies
.agents/oma-config.yaml, .codex/agents/*.toml, .gemini/agents/*.md, or fallback oma agent spawn
- Memory provider config, subagent prompt template, scripts, task templates, verify script, and session metrics
Control-flow features
- Branches by vendor/native dispatch availability, priority tiers, agent completion/failure, verification status, QA verdict, retry limits, and clarification debt
- Spawns processes/agents and reads/writes memory/result files
- Blocks termination until persistent workflows complete
Structural Flow
Entry
- Resolve agent vendor routing and runtime dispatch path.
- Decompose request into priority-tiered tasks.
- For each task, classify into one or more
domain_tags by matching against the Intent signature block of each installed .agents/skills/oma-*/SKILL.md. Tasks that match no domain confidently inherit the union of their parent feature's tags.
- Build a per-task
exposed_skill_set = skills whose name is in domain_tags. If |exposed_skill_set| < 2 after classification, fall back to the full installed set (flat exposure) and record exposure_fallback: true in the task board.
- Create session memory and task board with
exposed_skill_set and exposure_fallback per task.
Scenes
- PREPARE: Plan, setup session ID, and initialize memory files.
- ACT: Spawn agents by priority tier within parallelism limits.
- VERIFY: Run self-check,
oma verify, and QA cross-review loop.
- RECOVER: Retry failed agents with review history when limits allow.
- FINALIZE: Collect result files, compile summary, and clean progress files.
Transitions
- If native dispatch is available for current runtime/vendor, use it.
- If vendors differ or native path is unavailable, use fallback spawn.
- If verify or QA fails, feed feedback back to the implementation agent.
- If review loop limits are exceeded, report review history and quality warning.
- If a task's
exposed_skill_set excludes a skill that a recovered failure indicates was needed, re-classify the task and re-dispatch with the expanded set rather than retrying against the original narrow set.
Failure and recovery
- Retry failed agents up to configured limits.
- Re-spawn with review history when review loop is exhausted.
- Pause or request re-specification when clarification debt thresholds are exceeded.
Exit
- Success: all tasks complete, verify/review pass, and results are summarized.
- Partial success: failed agents, exhausted review loops, or clarification debt are explicit.
Logical Operations
Actions
| Action |
SSL primitive |
Evidence |
| Read config and task context |
READ |
oma config, routing, request |
| Classify task into domain tags |
INFER |
task text vs each skill's Intent signature |
| Compute exposed skill set |
SELECT |
intersection of domain tags and installed skills |
| Select dispatch path |
SELECT |
Native vs fallback |
| Write session state |
WRITE |
task board and memory files |
| Spawn agents |
CALL_TOOL |
native CLI or oma agent spawn |
| Poll progress |
READ |
progress/result files |
| Run verification |
CALL_TOOL |
oma verify, tests, QA |
| Update retry state |
UPDATE_STATE |
loop counters and CD metrics |
| Report final result |
NOTIFY |
compiled summary |
Tools and instruments
- Native CLI subagent dispatch, fallback spawn scripts, memory tools, verify script, QA agent
- Session metrics, prompt templates, task templates
Canonical command path
oma agent spawn <agent-type> "<task>" <session-id> -w <workspace>
oma verify <agent-type> --workspace <workspace> --json
When native runtime dispatch is available, prefer the runtime-specific native path listed in this skill before falling back to oma agent spawn.
Resource scope
| Scope |
Resource target |
LOCAL_FS |
Session, task-board, progress, result, config files |
PROCESS |
Agent CLI processes and verify scripts |
MEMORY |
Session state and clarification debt |
CODEBASE |
Workspaces owned by spawned agents |
Preconditions
- Task is decomposable into specialist agent work.
- Runtime/vendor dispatch path or fallback exists.
Effects and side effects
- Spawns agents and writes session/progress/result artifacts.
- May cause code changes through specialist agents.
- May trigger iterative review and retries.
Guardrails
- Orchestrate per-agent dispatch from the project configuration before spawning any agent.
- If
target_vendor === current_runtime_vendor and the runtime has a verified native path, use native dispatch.
- Otherwise fall back to
oma agent spawn.
- Never exceed the configured parallelism or retry limits.
- Keep session state, task-board state, progress files, and result files aligned throughout the run.
- Domain gating must be soft: prefer a narrower
exposed_skill_set, but fall back to flat exposure when classification confidence is low rather than starving a task of a required specialist.
Current native executor paths:
- Claude Code: Agent tool with
.claude/agents/{agent}.md definitions (multiple Agent tool calls in one message run in parallel; results return synchronously — no polling)
- OpenCode: native
task tool with subagent_type: {agent-id}; do not use oma agent spawn for same-session OpenCode work because it will not appear as a native child task
- Codex CLI:
codex exec "@agent ..." using .codex/agents/*.toml
- Gemini CLI:
gemini -p "@agent ..." using .gemini/agents/*.md
Vendor-specific execution protocols are injected automatically for fallback CLI runs.
Configuration
| Setting |
Default |
Description |
| MAX_PARALLEL |
3 |
Max concurrent subagents |
| MAX_RETRIES |
2 |
Retry attempts per failed task |
| POLL_INTERVAL |
30s |
Status check interval |
| MAX_TURNS (impl) |
20 |
Turn limit for backend/frontend/mobile |
| MAX_TURNS (review) |
15 |
Turn limit for qa/debug |
| MAX_TURNS (plan) |
10 |
Turn limit for pm |
These are skill-level defaults applied by the orchestrating agent; they are not read from config/cli-config.yaml (which carries only vendor CLI and execution settings such as results_dir and timeout).
Memory Configuration
Memory provider and tool names are configurable via .agents/mcp.json (not the repo-root .mcp.json, which is the Claude Code MCP server config):
{
"memoryConfig": {
"provider": "file",
"basePath": ".agents/state/memories",
"tools": {
"read": "Read",
"write": "Write",
"edit": "Edit"
}
}
}
Workflow Phases
PHASE 1 - Plan: Analyze request -> decompose tasks -> generate session ID
PHASE 1.5 - Domain gate: For each task, intersect Intent signature matches across installed skills to derive exposed_skill_set. Record exposure_fallback: true when the intersection is too small to be useful and the flat library is used instead.
PHASE 2 - Setup: Use memory write tool to create orchestrator-session.md + task-board.md (include exposed_skill_set per task)
PHASE 3 - Execute: Spawn agents by priority tier (never exceed MAX_PARALLEL); inject only exposed_skill_set into each subagent's available specialist list
PHASE 4 - Monitor: Poll every POLL_INTERVAL; handle completed/failed/crashed agents
PHASE 4.5 - Verify: Run mechanical checks for every completed agent; run oma verify {agent-type} only for backend, frontend, mobile, qa, debug, and pm; then run QA cross-review for every completed implementation
PHASE 5 - Collect: Read all result-{agent}-{sessionId}.md, compile summary, cleanup progress files
See resources/subagent-prompt-template.md for prompt construction.
See resources/memory-schema.md for memory file formats.
Memory File Ownership
| File |
Owner |
Others |
orchestrator-session.md |
orchestrator |
read-only |
task-board.md |
orchestrator |
read-only |
progress-{agent}[-{sessionId}].md |
that agent |
orchestrator reads |
result-{agent}[-{sessionId}].md |
that agent |
orchestrator reads |
Agent-to-Agent Review Loop (PHASE 4.5)
After each agent completes, enter an iterative review loop, not a single-pass verification.
Loop Flow
Agent completes work
↓
[1] Mechanical Self-Check: lint, type-check, tests, diff scope
↓
[2] Verify: For supported types, run `oma verify {agent-type} --workspace {workspace}`
Unsupported (`db`, `refactor`, `architecture`, `tf-infra`, `docs`) → record SKIP and continue
↓ FAIL → Agent receives feedback, fixes, back to [1]
↓ PASS
[3] Cross-Review: QA agent reviews the changes
↓ FAIL → Agent receives review feedback, fixes, back to [1]
↓ PASS
Accept result
Step Details
[1] Mechanical Self-Check (formerly "Self-Review"):
Before requesting external review, the implementation agent must:
- Run lint, type-check, and tests in the workspace
- Verify only planned files were modified (diff scope check)
- Fix any mechanical failures (compile errors, test failures)
Quality judgment is NOT performed in this step.
Design quality, architecture alignment, and acceptance criteria satisfaction
are evaluated exclusively in [3] Cross-Review by the QA agent.
Reason: Self-evaluation bias causes agents to consistently overrate their own output
(ref: Anthropic harness design research).
[2] Automated Verify:
oma verify {agent-type} --workspace {workspace} --json
- Run only for
backend, frontend, mobile, qa, debug, and pm.
- For
db, refactor, architecture, tf-infra, and docs, record that automated verify is unsupported and continue to QA cross-review after the mechanical checks.
- PASS (exit 0): Proceed to cross-review
- FAIL (exit 1): Feed verify output back to the agent as correction context
[3] Cross-Review: Spawn QA agent to review the changes:
- QA agent reads the diff, runs checks, evaluates against acceptance criteria
- If
docs/CODE-REVIEW.md exists, QA agent uses it as the review checklist
- QA agent outputs: PASS (with optional nits) or FAIL (with specific issues)
- On FAIL: issues are fed back to the implementation agent for fixing
Loop Limits
| Counter |
Max |
On Exceeded |
| Self-check + fix cycles |
3 |
Escalate to cross-review regardless |
| Cross-review rejections |
2 |
Report to user with review history |
| Total loop iterations |
5 |
Force-complete with quality warning |
Review Feedback Format
When feeding review results back to the implementation agent:
## Review Feedback (iteration {n}/{max})
**Reviewer**: {self / verify / qa-agent}
**Verdict**: FAIL
**Issues**:
1. {specific issue with file and line reference}
2. {specific issue}
**Fix instruction**: {what to change}
This replaces single-pass verification. Most "nitpicking" should happen agent-to-agent.
Human review is reserved for final approval, not catching lint errors.
Retry Logic (after review loop exhaustion)
Before starting any retry, check the termination conditions (OR, whichever fires first wins):
- Retry cap: retry count for this agent has reached MAX_RETRIES — do not start another cycle.
- Session cost cap: if a quota cap is configured (
loadQuotaCap() from cli/io/session-cost.ts; no cap → skip), call checkCap(sessionId, cap). On exceeded === true, save the agent's partial results, report early termination due to quota, and do not spawn the next retry or any remaining agents in the tier.
If neither condition fires:
- 1st retry: Re-spawn agent with full review history as context
- 2nd retry: Re-spawn with "Try a different approach" + review history
- After MAX_RETRIES exhausted (cost cap not exceeded): activate the Exploration Loop (see
orchestrate.md Step 5): generate 2-3 alternative hypotheses, spawn the same agent type with different hypothesis prompts in parallel separate workspaces, score with Quality Score when available, keep the highest-scoring approach, and record all experiments in the Experiment Ledger.
- Final failure: Report to user with complete review trail, ask whether to continue or abort
Clarification Debt (CD) Monitoring
Track user corrections during session execution. See ../_shared/core/session-metrics.md for full protocol.
Event Classification
When user sends feedback during session:
- clarify (+10): User answering agent's question
- correct (+25): User correcting agent's misunderstanding
- redo (+40): User rejecting work, requesting restart
Threshold Actions
| CD Score |
Action |
| CD >= 50 |
RCA Required: QA agent must add entry to lessons-learned.md |
| CD >= 80 |
Session Pause: Request user to re-specify requirements |
redo >= 2 |
Scope Lock: Request explicit allowlist confirmation before continuing |
Recording
After each user correction event:
[EDIT]("session-metrics.md", append event to Events table)
At session end, if CD >= 50:
- Include CD summary in final report
- Trigger QA agent RCA generation
- Update
lessons-learned.md with prevention measures
References
- Prompt template:
resources/subagent-prompt-template.md
- Memory schema:
resources/memory-schema.md
- Config:
config/cli-config.yaml
- Scripts:
scripts/spawn-agent.sh, scripts/parallel-run.sh, scripts/verify.sh
- Task templates:
templates/
- Skill-to-agent mapping:
../_shared/core/skill-routing.md
- Verification:
scripts/verify.sh <agent-type>
- Session metrics:
../_shared/core/session-metrics.md
- API contract template (SSOT):
../_shared/core/api-contracts/template.md; read generated contracts from .agents/results/api-contracts/ (run artifact) or docs/plans/contracts/ (durable spec)
- Context loading:
../_shared/core/context-loading.md
- Difficulty guide:
../_shared/core/difficulty-guide.md
- Clarification protocol:
../_shared/core/clarification-protocol.md
- Context budget:
../_shared/core/context-budget.md
- Lessons learned:
../_shared/core/lessons-learned.md
1---
2name: oma-orchestration
3description: Automated multi-agent orchestration that spawns CLI subagents in
4 parallel, coordinates via MCP Memory, and monitors progress. Use for
5 orchestration, parallel execution, and automated multi-agent workflows.
6---
7
8# Orchestration - Automated Multi-Agent Coordination
9
10## Scheduling
11
12### Goal
13Automatically orchestrate multi-agent execution with task decomposition, native/fallback dispatch, memory coordination, progress monitoring, verification, QA cross-review, retry, and result collection.
14
15### Intent signature
16- User asks to orchestrate, run in parallel, automate multi-agent execution, or coordinate full-stack work end to end.
17- Task requires multiple specialist agents and a persistent review/remediation loop.
18
19### When to use
20- Complex feature requires multiple specialized agents working in parallel
21- User wants automated execution without manually spawning agents
22- Full-stack implementation spanning backend, frontend, mobile, and QA
23- User says "run it automatically", "run in parallel", or similar automation requests
24
25### When NOT to use
26- Simple single-domain task -> use the specific agent directly
27- User wants step-by-step manual control -> use oma-coordination
28- Quick bug fixes or minor changes
29
30### Expected inputs
31- Complex feature or workflow request
32- Project config, model/vendor routing, agent types, task constraints, and workspace/session needs
33- Acceptance criteria and verification expectations
34
35### Expected outputs
36- Orchestrator session state, task board, progress files, result files, and final summary
37- Specialist agent outputs after mechanical checks, automated verify, and QA cross-review
38- Review history and retry/remediation status when loops fail
39
40### Dependencies
41- `.agents/oma-config.yaml`, `.codex/agents/*.toml`, `.gemini/agents/*.md`, or fallback `oma agent spawn`
42- Memory provider config, subagent prompt template, scripts, task templates, verify script, and session metrics
43
44### Control-flow features
45- Branches by vendor/native dispatch availability, priority tiers, agent completion/failure, verification status, QA verdict, retry limits, and clarification debt
46- Spawns processes/agents and reads/writes memory/result files
47- Blocks termination until persistent workflows complete
48
49## Structural Flow
50
51### Entry
521. Resolve agent vendor routing and runtime dispatch path.
532. Decompose request into priority-tiered tasks.
543. For each task, classify into one or more `domain_tags` by matching against the `Intent signature` block of each installed `.agents/skills/oma-*/SKILL.md`. Tasks that match no domain confidently inherit the union of their parent feature's tags.
554. Build a per-task `exposed_skill_set` = skills whose name is in `domain_tags`. If `|exposed_skill_set| < 2` after classification, fall back to the full installed set (flat exposure) and record `exposure_fallback: true` in the task board.
565. Create session memory and task board with `exposed_skill_set` and `exposure_fallback` per task.
57
58### Scenes
591. **PREPARE**: Plan, setup session ID, and initialize memory files.
602. **ACT**: Spawn agents by priority tier within parallelism limits.
613. **VERIFY**: Run self-check, `oma verify`, and QA cross-review loop.
624. **RECOVER**: Retry failed agents with review history when limits allow.
635. **FINALIZE**: Collect result files, compile summary, and clean progress files.
64
65### Transitions
66- If native dispatch is available for current runtime/vendor, use it.
67- If vendors differ or native path is unavailable, use fallback spawn.
68- If verify or QA fails, feed feedback back to the implementation agent.
69- If review loop limits are exceeded, report review history and quality warning.
70- If a task's `exposed_skill_set` excludes a skill that a recovered failure indicates was needed, re-classify the task and re-dispatch with the expanded set rather than retrying against the original narrow set.
71
72### Failure and recovery
73- Retry failed agents up to configured limits.
74- Re-spawn with review history when review loop is exhausted.
75- Pause or request re-specification when clarification debt thresholds are exceeded.
76
77### Exit
78- Success: all tasks complete, verify/review pass, and results are summarized.
79- Partial success: failed agents, exhausted review loops, or clarification debt are explicit.
80
81## Logical Operations
82
83### Actions
84| Action | SSL primitive | Evidence |
85|--------|---------------|----------|
86| Read config and task context | `READ` | oma config, routing, request |
87| Classify task into domain tags | `INFER` | task text vs each skill's `Intent signature` |
88| Compute exposed skill set | `SELECT` | intersection of domain tags and installed skills |
89| Select dispatch path | `SELECT` | Native vs fallback |
90| Write session state | `WRITE` | task board and memory files |
91| Spawn agents | `CALL_TOOL` | native CLI or `oma agent spawn` |
92| Poll progress | `READ` | progress/result files |
93| Run verification | `CALL_TOOL` | `oma verify`, tests, QA |
94| Update retry state | `UPDATE_STATE` | loop counters and CD metrics |
95| Report final result | `NOTIFY` | compiled summary |
96
97### Tools and instruments
98- Native CLI subagent dispatch, fallback spawn scripts, memory tools, verify script, QA agent
99- Session metrics, prompt templates, task templates
100
101### Canonical command path
102```bash
103oma agent spawn <agent-type> "<task>" <session-id> -w <workspace>
104oma verify <agent-type> --workspace <workspace> --json
105```
106
107When native runtime dispatch is available, prefer the runtime-specific native path listed in this skill before falling back to `oma agent spawn`.
108
109### Resource scope
110| Scope | Resource target |
111|-------|-----------------|
112| `LOCAL_FS` | Session, task-board, progress, result, config files |
113| `PROCESS` | Agent CLI processes and verify scripts |
114| `MEMORY` | Session state and clarification debt |
115| `CODEBASE` | Workspaces owned by spawned agents |
116
117### Preconditions
118- Task is decomposable into specialist agent work.
119- Runtime/vendor dispatch path or fallback exists.
120
121### Effects and side effects
122- Spawns agents and writes session/progress/result artifacts.
123- May cause code changes through specialist agents.
124- May trigger iterative review and retries.
125
126### Guardrails
1271. Orchestrate per-agent dispatch from the project configuration before spawning any agent.
1282. If `target_vendor === current_runtime_vendor` and the runtime has a verified native path, use native dispatch.
1293. Otherwise fall back to `oma agent spawn`.
1304. Never exceed the configured parallelism or retry limits.
1315. Keep session state, task-board state, progress files, and result files aligned throughout the run.
1326. Domain gating must be soft: prefer a narrower `exposed_skill_set`, but fall back to flat exposure when classification confidence is low rather than starving a task of a required specialist.
133
134Current native executor paths:
135- Claude Code: Agent tool with `.claude/agents/{agent}.md` definitions (multiple Agent tool calls in one message run in parallel; results return synchronously — no polling)
136- OpenCode: native `task` tool with `subagent_type: {agent-id}`; do not use `oma agent spawn` for same-session OpenCode work because it will not appear as a native child task
137- Codex CLI: `codex exec "@agent ..."` using `.codex/agents/*.toml`
138- Gemini CLI: `gemini -p "@agent ..."` using `.gemini/agents/*.md`
139
140Vendor-specific execution protocols are injected automatically for fallback CLI runs.
141
142### Configuration
143
144| Setting | Default | Description |
145|---------|---------|-------------|
146| MAX_PARALLEL | 3 | Max concurrent subagents |
147| MAX_RETRIES | 2 | Retry attempts per failed task |
148| POLL_INTERVAL | 30s | Status check interval |
149| MAX_TURNS (impl) | 20 | Turn limit for backend/frontend/mobile |
150| MAX_TURNS (review) | 15 | Turn limit for qa/debug |
151| MAX_TURNS (plan) | 10 | Turn limit for pm |
152
153These are skill-level defaults applied by the orchestrating agent; they are not read from `config/cli-config.yaml` (which carries only vendor CLI and execution settings such as `results_dir` and `timeout`).
154
155### Memory Configuration
156
157Memory provider and tool names are configurable via `.agents/mcp.json` (not the repo-root `.mcp.json`, which is the Claude Code MCP server config):
158```json
159{
160 "memoryConfig": {
161 "provider": "file",
162 "basePath": ".agents/state/memories",
163 "tools": {
164 "read": "Read",
165 "write": "Write",
166 "edit": "Edit"
167 }
168 }
169}
170```
171
172### Workflow Phases
173
174**PHASE 1 - Plan**: Analyze request -> decompose tasks -> generate session ID
175**PHASE 1.5 - Domain gate**: For each task, intersect `Intent signature` matches across installed skills to derive `exposed_skill_set`. Record `exposure_fallback: true` when the intersection is too small to be useful and the flat library is used instead.
176**PHASE 2 - Setup**: Use memory write tool to create `orchestrator-session.md` + `task-board.md` (include `exposed_skill_set` per task)
177**PHASE 3 - Execute**: Spawn agents by priority tier (never exceed MAX_PARALLEL); inject only `exposed_skill_set` into each subagent's available specialist list
178**PHASE 4 - Monitor**: Poll every POLL_INTERVAL; handle completed/failed/crashed agents
179**PHASE 4.5 - Verify**: Run mechanical checks for every completed agent; run `oma verify {agent-type}` only for `backend`, `frontend`, `mobile`, `qa`, `debug`, and `pm`; then run QA cross-review for every completed implementation
180**PHASE 5 - Collect**: Read all `result-{agent}-{sessionId}.md`, compile summary, cleanup progress files
181
182See `resources/subagent-prompt-template.md` for prompt construction.
183See `resources/memory-schema.md` for memory file formats.
184
185### Memory File Ownership
186
187| File | Owner | Others |
188|------|-------|--------|
189| `orchestrator-session.md` | orchestrator | read-only |
190| `task-board.md` | orchestrator | read-only |
191| `progress-{agent}[-{sessionId}].md` | that agent | orchestrator reads |
192| `result-{agent}[-{sessionId}].md` | that agent | orchestrator reads |
193
194### Agent-to-Agent Review Loop (PHASE 4.5)
195
196After each agent completes, enter an iterative review loop, not a single-pass verification.
197
198### Loop Flow
199
200```
201Agent completes work
202 ↓
203[1] Mechanical Self-Check: lint, type-check, tests, diff scope
204 ↓
205[2] Verify: For supported types, run `oma verify {agent-type} --workspace {workspace}`
206 Unsupported (`db`, `refactor`, `architecture`, `tf-infra`, `docs`) → record SKIP and continue
207 ↓ FAIL → Agent receives feedback, fixes, back to [1]
208 ↓ PASS
209[3] Cross-Review: QA agent reviews the changes
210 ↓ FAIL → Agent receives review feedback, fixes, back to [1]
211 ↓ PASS
212Accept result
213```
214
215### Step Details
216
217**[1] Mechanical Self-Check** (formerly "Self-Review"):
218Before requesting external review, the implementation agent must:
219- Run lint, type-check, and tests in the workspace
220- Verify only planned files were modified (diff scope check)
221- Fix any mechanical failures (compile errors, test failures)
222
223**Quality judgment is NOT performed in this step.**
224Design quality, architecture alignment, and acceptance criteria satisfaction
225are evaluated exclusively in [3] Cross-Review by the QA agent.
226Reason: Self-evaluation bias causes agents to consistently overrate their own output
227(ref: Anthropic harness design research).
228
229**[2] Automated Verify**:
230```bash
231oma verify {agent-type} --workspace {workspace} --json
232```
233- Run only for `backend`, `frontend`, `mobile`, `qa`, `debug`, and `pm`.
234- For `db`, `refactor`, `architecture`, `tf-infra`, and `docs`, record that automated verify is unsupported and continue to QA cross-review after the mechanical checks.
235- **PASS (exit 0)**: Proceed to cross-review
236- **FAIL (exit 1)**: Feed verify output back to the agent as correction context
237
238**[3] Cross-Review**: Spawn QA agent to review the changes:
239- QA agent reads the diff, runs checks, evaluates against acceptance criteria
240<!-- oma-docs:ignore-start -->
241- If `docs/CODE-REVIEW.md` exists, QA agent uses it as the review checklist
242<!-- oma-docs:ignore-end -->
243- QA agent outputs: PASS (with optional nits) or FAIL (with specific issues)
244- On FAIL: issues are fed back to the implementation agent for fixing
245
246### Loop Limits
247
248| Counter | Max | On Exceeded |
249|---------|-----|-------------|
250| Self-check + fix cycles | 3 | Escalate to cross-review regardless |
251| Cross-review rejections | 2 | Report to user with review history |
252| Total loop iterations | 5 | Force-complete with quality warning |
253
254### Review Feedback Format
255
256When feeding review results back to the implementation agent:
257```
258## Review Feedback (iteration {n}/{max})
259**Reviewer**: {self / verify / qa-agent}
260**Verdict**: FAIL
261**Issues**:
2621. {specific issue with file and line reference}
2632. {specific issue}
264**Fix instruction**: {what to change}
265```
266
267This replaces single-pass verification. Most "nitpicking" should happen agent-to-agent.
268Human review is reserved for final approval, not catching lint errors.
269
270### Retry Logic (after review loop exhaustion)
271
272Before starting any retry, check the termination conditions (OR, whichever fires first wins):
2731. **Retry cap**: retry count for this agent has reached MAX_RETRIES — do not start another cycle.
2742. **Session cost cap**: if a quota cap is configured (`loadQuotaCap()` from `cli/io/session-cost.ts`; no cap → skip), call `checkCap(sessionId, cap)`. On `exceeded === true`, save the agent's partial results, report early termination due to quota, and do not spawn the next retry or any remaining agents in the tier.
275
276If neither condition fires:
277- 1st retry: Re-spawn agent with full review history as context
278- 2nd retry: Re-spawn with "Try a different approach" + review history
279- After MAX_RETRIES exhausted (cost cap not exceeded): activate the **Exploration Loop** (see `orchestrate.md` Step 5): generate 2-3 alternative hypotheses, spawn the same agent type with different hypothesis prompts in parallel separate workspaces, score with Quality Score when available, keep the highest-scoring approach, and record all experiments in the Experiment Ledger.
280- Final failure: Report to user with complete review trail, ask whether to continue or abort
281
282### Clarification Debt (CD) Monitoring
283
284Track user corrections during session execution. See `../_shared/core/session-metrics.md` for full protocol.
285
286### Event Classification
287When user sends feedback during session:
288- **clarify** (+10): User answering agent's question
289- **correct** (+25): User correcting agent's misunderstanding
290- **redo** (+40): User rejecting work, requesting restart
291
292### Threshold Actions
293| CD Score | Action |
294|----------|--------|
295| CD >= 50 | **RCA Required**: QA agent must add entry to `lessons-learned.md` |
296| CD >= 80 | **Session Pause**: Request user to re-specify requirements |
297| `redo` >= 2 | **Scope Lock**: Request explicit allowlist confirmation before continuing |
298
299### Recording
300After each user correction event:
301```
302[EDIT]("session-metrics.md", append event to Events table)
303```
304
305At session end, if CD >= 50:
3061. Include CD summary in final report
3072. Trigger QA agent RCA generation
3083. Update `lessons-learned.md` with prevention measures
309
310
311
312## References
313- Prompt template: `resources/subagent-prompt-template.md`
314- Memory schema: `resources/memory-schema.md`
315- Config: `config/cli-config.yaml`
316- Scripts: `scripts/spawn-agent.sh`, `scripts/parallel-run.sh`, `scripts/verify.sh`
317- Task templates: `templates/`
318- Skill-to-agent mapping: `../_shared/core/skill-routing.md`
319- Verification: `scripts/verify.sh <agent-type>`
320- Session metrics: `../_shared/core/session-metrics.md`
321- API contract template (SSOT): `../_shared/core/api-contracts/template.md`; read generated contracts from `.agents/results/api-contracts/` (run artifact) or `docs/plans/contracts/` (durable spec)
322- Context loading: `../_shared/core/context-loading.md`
323- Difficulty guide: `../_shared/core/difficulty-guide.md`
324- Clarification protocol: `../_shared/core/clarification-protocol.md`
325- Context budget: `../_shared/core/context-budget.md`
326- Lessons learned: `../_shared/core/lessons-learned.md`