원클릭으로
wave-executor
Executes wave-structured plans with personality-injected agents — parallel or sequential per CLI adapter
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Executes wave-structured plans with personality-injected agents — parallel or sequential per CLI adapter
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
DEPRECATED compatibility shim; workflow-common-core is canonical for all conventions referenced here
Interprets --just-* and --skip-* command flags for /legion:build and /legion:review, validates flag combinations against rules, and resolves the matching team template from intent-teams.yaml. Use when the user passes intent flags to build or review commands, asks about flag combinations, or needs to filter agent teams by intent.
Dev-QA loop engine with structured feedback, fix routing, and user escalation for /legion:review
Maps all 48 Legion agents by division, capability, and task type for intelligent team assembly
Engine for /legion:map. Analyzes an existing codebase, generates CODEBASE.md for backward-compatible architecture context, and writes .planning/codebase/ index artifacts consumed by /legion:start, /plan, /build, /review, /status, and /quick.
Design system creation, UX research workflows, and three-lens design review cycles for design-focused phases
SOC 직업 분류 기준
| name | wave-executor |
| description | Executes wave-structured plans with personality-injected agents — parallel or sequential per CLI adapter |
| triggers | ["build","execute","parallel","wave","dispatch","spawn"] |
| token_cost | high |
| summary | Executes wave-structured plans via the active CLI adapter. Parallel within waves (if adapter supports it), sequential between. Full personality injection, adapter-based result collection. Core engine for /legion:build. |
Engine for /legion:build. Takes the plan files in a phase directory and executes them in wave order — spawning personality-injected agents in parallel within each wave, waiting for completion before advancing to the next wave. The full flow: discover plans, validate structure, inject personalities, spawn parallel agents, collect results, write summaries, report.
These rules govern all execution decisions. Do not deviate from them.
MANDATORY: Follow the active CLI adapter's Execution Protocol.
Before executing any plans, load the active adapter (see workflow-common CLI Detection Protocol). The adapter defines how agents are spawned, coordinated, and cleaned up.
If adapter.parallel_execution is true AND adapter.structured_messaging is true (e.g., Claude Code): Use the adapter's full coordination lifecycle (e.g., TeamCreate → TaskCreate → Agent with team_name → SendMessage → TeamDelete on Claude Code). On Claude Code specifically:
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMSmust be enabled. If Teams are unavailable, stop and tell the user to enable the flag.If adapter.parallel_execution is true but adapter.structured_messaging is false (e.g., Cursor): Spawn agents in parallel. Collect results via file system per adapter.collect_results.
If adapter.parallel_execution is false (e.g., Codex CLI, Gemini CLI, Aider): Execute plans sequentially within each wave. No agent spawning may be needed — use adapter.spawn_agent_personality or execute inline per adapter protocol.
This is not optional. Always consult the adapter before spawning agents.
adapter.parallel_execution is true, or sequentially if false..md file. No summaries, no excerpts, no paraphrasing. On CLIs without agent spawning, personality is a prompt prefix in the current session.adapter.model_execution. This matches the Cost Profile Convention from workflow-common.md.workflow-common.md.{NN}-{PP}-SUMMARY.md file to the phase directory, whether the result is success or failure./legion:build command itself does not execute plan work. It reads, validates, dispatches, and collects. On CLIs without spawning, personality injection is temporary and dropped after each plan.execution.use_worktrees is true, this constraint is relaxed — each agent operates in its own git worktree, providing filesystem-level isolation. See Section 1.5.sequential_files, the wave-executor must serialize dispatch for plans that share a sequential file. Plans with no sequential file overlap still execute in parallel. This constraint applies even when adapter.parallel_execution is true.> verification: commands from the task's action block. If any verification command returns a non-zero exit code, the task is marked as failed and the agent must report the failure. Do not proceed to the next task until all verifications pass.read-before-write -> evidence-before-action -> minimal diff -> verify-before-report. Agents must read listed context before editing, prove source evidence before acting, keep diffs inside files_modified, run verification before reporting, and emit BLOCKED instead of guessing on ambiguity, missing files, conflicting instructions, forbidden operations, or unverifiable success.When settings.json execution.use_worktrees is true, the wave-executor creates isolated git worktrees for each agent in a wave, eliminating the need for files_modified disjointness checking.
files_modified disjointness constraint (Principle 8) is too restrictive for the taskadapter.parallel_execution must be true (worktrees are pointless for sequential execution)Phase Start:
For each wave with 2+ parallel plans:
Step 1: Create worktrees
For each plan in the wave:
- branch_name = "legion-wt-{NN}-{PP}-{timestamp}"
- Run: git worktree add .legion-worktrees/{NN}-{PP} -b {branch_name} HEAD
- Store worktree_path = .legion-worktrees/{NN}-{PP}
Step 2: Spawn agents in worktrees
For each plan:
- Set agent cwd to the worktree path instead of the project root
- All agent file operations happen in the isolated worktree
- Agent personality injection and execution is unchanged
Step 3: Collect results
Wait for all agents in the wave to complete (same as standard execution)
Step 4: Merge worktrees back
For each completed worktree (in plan order):
a. Check for changes: git -C {worktree_path} diff --name-only HEAD
b. If no changes: skip (agent made no modifications)
c. Commit changes in worktree:
git -C {worktree_path} add -A
git -C {worktree_path} commit -m "legion: plan {NN}-{PP} execution"
d. Merge into main working tree:
git merge {branch_name} --no-ff -m "legion: merge plan {NN}-{PP}"
e. If merge conflict:
- Record conflicting files
- Abort merge: git merge --abort
- Add to conflict_report for user resolution
- Continue with remaining worktrees
Step 5: Cleanup
For each worktree:
- git worktree remove .legion-worktrees/{NN}-{PP} --force
- git branch -D {branch_name}
- Remove .legion-worktrees/ directory if empty
Step 6: Report conflicts (if any)
If conflict_report is non-empty:
Display:
"## Merge Conflicts Detected
The following plans produced conflicting changes:
| Plan | Conflicting Files |
|------|------------------|
| {NN}-{PP} | {file_list} |
Resolve conflicts manually, then run `/legion:build --resume` to continue."
Halt execution — do not proceed to next wave
When worktree mode is active:
| Adapter Capability | Worktree Support |
|---|---|
| Claude Code | Full support — Agent tool accepts cwd override |
| Cursor/Windsurf | Partial — file-based result collection works, but agents may not respect cwd |
| Sequential CLIs | N/A — worktrees disabled for sequential execution |
/legion:build, check for stale .legion-worktrees/ and offer cleanupHow to find, read, and organize plan files for a phase before any execution begins.
Step 1: Determine the phase directory path
- Read .planning/STATE.md to find the current phase number and slug
- Or accept a --phase argument from the build command
- Construct the directory: .planning/phases/{NN}-{phase-slug}/
- Example: .planning/phases/04-parallel-execution/
Step 2: List all files in the phase directory
- Read directory contents
- Filter for files matching: {NN}-{PP}-PLAN.md
- Exclude: {NN}-CONTEXT.md, {NN}-{PP}-SUMMARY.md, and any other files
- Sort plans by plan number (PP) ascending
Step 3: Read each plan file's YAML frontmatter
Schema reference: docs/schemas/plan-frontmatter.schema.json defines the required
and optional frontmatter fields. Plan files MUST conform to this schema. The
/legion:validate command checks plan frontmatter against this schema.
For each plan file, parse the frontmatter block (between --- delimiters):
- wave: integer (required — which execution wave this plan belongs to)
- depends_on: list of "NN-PP" strings (plans that must complete before this one)
- autonomous: boolean (true = no agent needed, false = agent-delegated)
- files_modified: list of file paths this plan creates or modifies
- sequential_files: list of file paths requiring single-agent sequential access (optional)
- requirements: list of requirement IDs covered by this plan
Step 4: Build the wave map
Construct a data structure grouping plans by wave number:
{
1: [plan-04-01, plan-04-02], -- runs first, in parallel
2: [plan-04-03], -- runs after wave 1 completes
3: [plan-04-04, plan-04-05], -- runs after wave 2 completes
}
Step 5: Validate the plan structure
Check all of the following before proceeding:
a) At least one plan file exists. If not: error "No plans found for Phase {N}.
Run /legion:plan {N} first."
b) All depends_on references point to plans in earlier (lower) waves. If a plan
in wave 2 depends on another wave 2 plan: error "Circular wave dependency
detected in plan {NN}-{PP}. Plans within the same wave cannot depend on
each other. Re-run /legion:plan {N} to fix the plan structure."
c) Each wave number is a positive integer with no gaps above wave 1 (wave 1
always present; wave 3 allowed only if wave 2 exists).
d) All files_modified lists are disjoint within each wave (no two plans in the
same wave modify the same file). If a conflict is found: warn the user —
do not abort, but flag for review.
e) If directory mappings exist, verify files_modified paths are valid or have overrides.
If invalid and strictness=strict: error before execution begins.
f) MANDATORY — Verify all agent personality files exist BEFORE execution begins.
For every plan where autonomous: false, extract the agent-id from frontmatter
and use the Read tool to open {AGENTS_DIR}/{agent-id}.md. This is NOT optional.
Do NOT skip this step. Do NOT assume files are missing without actually attempting
to Read them. If Read succeeds: the file exists, record this fact. If Read returns
a file-not-found error: apply the fuzzy match logic from Step 1.5 (Section 3).
If fuzzy match also fails: STOP and error — do not fall back to autonomous mode.
Report: "Agent file not found for {agent-id}. Checked: {AGENTS_DIR}/{agent-id}.md
and fuzzy matches. Run /legion:update to reinstall agent files."
This step prevents the most common execution failure: hallucinating that agent
files are missing and silently degrading to personality-less autonomous execution.
g) MANDATORY — Verify plan harness sections before execution:
- `<execution_contract>`, `<stop_gates>`, and `<recovery>` exist.
- All read targets named in `<context>` and `<execution_contract>` exist or
are explicitly marked optional.
- `files_modified` covers every write target named in the contract.
- `files_forbidden` does not conflict with any write target.
- `<stop_gates>` contains `BLOCKED` conditions for ambiguity, missing files,
forbidden operations, and unverifiable success.
If any check fails: STOP and mark the plan `BLOCKED`; do not execute.
If validation fails on (a), (b), (c), (e), (f), or (g): stop and report the error. Do not execute.
Step 6: Report discovery results
Before executing, show a discovery summary:
"Found {total} plans across {wave_count} waves:
Wave 1: {plan names} ({count} plans)
Wave 2: {plan names} ({count} plans)
..."
How to load a full agent personality and construct the execution prompt for each plan.
For each plan where autonomous: false:
Step 1: Identify the assigned agent
- Read the agent-id from the plan's frontmatter `agents:` field
- Path format: {AGENTS_DIR}/{agent-id}.md (AGENTS_DIR resolved via workflow-common-core Agent Path Resolution Protocol)
- The standard installed path is ~/.claude/agents/{agent-id}.md — this is where
npm-installed Legion places all 48 agent files. Use this path preferentially.
- Example: ~/.claude/agents/engineering-senior-developer.md
Step 1.5: Validate the agent-id against actual files (MANDATORY — DO NOT SKIP)
- Use the Read tool to open {AGENTS_DIR}/{agent-id}.md
- You MUST actually invoke the Read tool here. Do NOT skip this and claim the file
is missing based on assumption. The files exist for all installed Legion instances.
- If Read succeeds (returns file content): proceed to Step 2 with this agent-id
- If Read returns a file-not-found error: run fuzzy-match fallback per the
single canonical algorithm below.
**Fuzzy-match fallback (canonical — applies in Sections 2, 3, and 6 identically):**
Division prefixes are enumerated in agent-registry.md Section 1 (CATALOG). Current set
(as of Legion 4.7): `engineering`, `design`, `marketing`, `product`, `testing`,
`project-management`, `support`, `specialized`, plus spatial-computing sub-prefixes
`macos`, `terminal`, `visionos`, `xr`. Do not hardcode; derive from agent-registry Section 1
at runtime. If the original agent-id starts with any division prefix, strip it and use the
remainder as `suffix`; otherwise `suffix = original-id`.
a) Run: Glob `{AGENTS_DIR}/*-{suffix}.md`
b) If exactly ONE match: use that file's agent-id instead.
Log: `"Agent ID corrected: {original-id} → {matched-id}"` — proceed with matched-id.
c) If MULTIPLE matches: **STOP — do NOT pick the first.**
Fail with: `"Ambiguous agent-id '{original-id}' matched {N} candidates: {list}. Plan must specify division prefix explicitly."` Escalate to caller; abort this plan.
d) If ZERO matches: try broader search: `Glob {AGENTS_DIR}/*{last-word-of-id}*.md`
- If exactly one match: use it. Log: `"Agent ID broadened: {original-id} → {matched-id}"`.
- If MULTIPLE matches: **STOP** with the same ambiguity error as (c).
- If ZERO matches: fall back to autonomous mode and log: `"No agent file found for {original-id}. Executing plan autonomously."`
This replaces the previous "pick the first" behavior (non-deterministic / filesystem-order
dependent). Deterministic "STOP on ambiguity" is safer for dispatch correctness.
Step 2: Read the complete personality file (RETRIEVAL-LED — MANDATORY)
- IMPORTANT: Use retrieval-led reasoning, not pre-training-led reasoning.
Do NOT rely on what you "know" about an agent's role. The personality file
IS the agent's identity. Without reading it, you are hallucinating a persona.
- Use the Read tool to load the ENTIRE agent .md file from the Dynamic Knowledge
Index in AGENTS.md: {AGENTS_DIR}/{agent-id}.md
- Do not truncate, summarize, or excerpt any portion
- The personality content includes: the agent's identity, specialization, behavioral
traits, communication style, technical focus areas, and working principles
- Capture this as: PERSONALITY_CONTENT
- If you skip this step, the spawned agent will operate on generic pre-trained
behavior instead of Legion's carefully designed specialist persona. This is
the single most common failure mode in agent orchestration.
Step 3: Read the complete plan file
- Use the Read tool to load the full plan .md file
- Capture the section starting from <objective> through end of file as: PLAN_CONTENT
Step 3.5: Load codebase map context (optional)
- Check if .planning/CODEBASE.md exists
- If yes:
a. Read .planning/CODEBASE.md
b. If `.planning/codebase/index.jsonl` and `.planning/codebase/symbols.json` exist:
- Build a map query from the current plan objective, task text, expected_artifacts, files_modified, and assigned agent domains
- Follow codebase-mapper Section 18 to retrieve at most 5 relevant chunks
- Include chunk id, path, line range, kind, and summary in CODEBASE_CONTEXT
c. Extract these sections:
- "## Agent Guidance" → Preferred and Avoid directives
- "## Conventions Detected" → all convention bullet points
- "## Risk Areas" → filter to rows where the Area or file paths overlap
with the current plan's files_modified list
- "## Dependency Graph" → dependency warnings for files_modified when present
- "## Directory Mappings" → placement expectations for new files
d. Compose a CODEBASE_CONTEXT block:
## Codebase Context
### Retrieved Map Chunks
{top matching index.jsonl chunks, or "No map index chunks were available."}
Note: These are summaries for context. Always read the original source files
before making code changes based on these chunks.
### Conventions
{bullet list from Conventions Detected}
### Agent Guidance
- **Preferred**: {from Agent Guidance}
- **Avoid**: {from Agent Guidance}
### Risk Areas
{filtered Risk Areas table rows, or "No risk areas overlap with this plan's files."}
### Directory Mappings
{applicable mappings for files_modified or new file categories, if available}
- If CODEBASE.md does not exist: set CODEBASE_CONTEXT = "" (empty string, no block injected)
Step 3.5b: Receive control mode profile
The control mode profile is pre-resolved by workflow-common-core's Settings Resolution
Protocol at invocation start. The wave-executor receives the resolved profile — it does
NOT read `.planning/config/control-modes.yaml` directly.
The profile contains 5 boolean flags:
- authority_enforcement, domain_filtering, human_approval_required, file_scope_restriction, read_only
If no profile was resolved (legacy invocation): default to guarded profile
(authority_enforcement=true, domain_filtering=true, human_approval_required=true,
file_scope_restriction=false, read_only=false)
Step 3.6: Load authority constraints
- If mode_profile.authority_enforcement is false:
Set AUTHORITY_CONTEXT = "" (skip all authority boundary injection)
Skip to Step 3.7
- Load active agents for this wave from wave map
- For current agent, identify its exclusive_domains from authority matrix
- Build AUTHORITY_CONTEXT block:
## Authority Boundaries
You have exclusive authority over these domains:
{list of exclusive_domains for this agent}
When you are active, other agents must respect your judgment on these topics.
Other agents active in this wave with their exclusive domains:
{for each other agent in wave:
- {agent-id}: {exclusive_domains}}
You must NOT critique or override findings from other agents in their exclusive domains.
You may critique general code quality, but must respect domain owners for specialist topics.
- If authority matrix does not exist: AUTHORITY_CONTEXT = "" (no constraints)
Step 3.7: Enforce authority during agent spawn
- If mode_profile.authority_enforcement is false:
Skip authority enforcement during agent spawn (no domain conflict warnings)
Before spawning each agent:
1. Load authority matrix: `.planning/config/authority-matrix.yaml`
2. Get list of all agents in current wave
3. For target agent, identify other agents with overlapping domains
4. If conflicts detected, add warning to wave report:
"Warning: Agents {agent1} and {agent2} both claim domain {domain}.
Both will be active — findings will be merged with severity escalation."
Step 3.8: Validate file placement against directory mappings (ENV-04)
Before constructing the agent prompt, validate that the plan's files_modified
are consistent with the project's directory structure. This prevents files
from being created in incorrect locations during execution.
3.8.1: Load directory mappings
Check if `.planning/config/directory-mappings.yaml` exists:
- If yes: Load mappings and enforcement configuration
- If no: Skip placement validation (no mappings available)
3.8.2: Validate each file in files_modified
For each file path in the plan's `files_modified` frontmatter:
a. Skip validation for exempt patterns:
- Files in `.planning/` (planning state has flexible structure)
- Root-level config files (README.md, .gitignore, etc.)
- Files matching enforcement.exceptions patterns
b. Infer the expected category for the file:
- Use same inference logic as spec-pipeline Section 8.1
- Check file extension, name patterns, and content type
- Examples:
- `**/*.test.js` → tests
- `**/routes/**` → routes
- `**/components/**` → components
- `**/SKILL.md` → skills (Legion-specific)
- `commands/*.md` → commands (Legion-specific)
c. Look up allowed directories for the category:
- Find category in mappings.mappings
- Get the list of allowed paths
- Note the enforcement strictness (strict/warn/off)
d. Validate the file path:
- Extract directory portion of file path
- Check if directory matches any allowed path for category
- Handle nested directories (child of allowed path is valid)
3.8.3: Handle validation results
Collect validation results:
| File | Category | Directory | Valid | Action |
|------|----------|-----------|-------|--------|
| {file} | {category} | {dir} | {yes/no} | {allow/warn/block} |
Action based on strictness and violations:
- strict + violations: Block wave execution
```
ERROR: File placement violations detected in plan {NN}-{PP}:
- {file}: Expected in {allowed_dirs} for {category}, got {actual_dir}
Fix: Move files to correct directories or update directory mappings.
Execution blocked until resolved.
```
Halt wave execution and report to user.
- warn + violations: Add warning to wave report, allow execution
```
WARNING: File placement issues in plan {NN}-{PP}:
- {file}: Should be in {suggested_path} for {category}
Files will be created as specified, but this may deviate from project conventions.
```
Continue execution but flag in wave summary.
- no violations: Continue normally
Log: "All {N} files validated against directory mappings ✓"
3.8.4: Allow plan-level overrides
Plans can override placement validation via frontmatter:
```yaml
---
phase: XX-name
plan: NN
path_override: true
path_override_reason: "Creating new category not yet in mappings"
---
When override is present:
After constructing the base agent prompt (personality + task + authority), apply mode-specific constraints from the resolved profile:
When mode_profile.read_only is true:
auto_commit regardless of settings.json value — no commits in advisory modeWhen mode_profile.file_scope_restriction is true:
files_modified were touchedWhen mode_profile.human_approval_required is false:
Step 4: Construct the agent execution prompt Combine personality and plan using this exact format:
Step 4.1: Add file placement guidance (conditional)
If placement validation found warnings or suggestions:
FILE_PLACEMENT_CONTEXT = """
This plan includes files that should be placed in specific directories:
| File | Target Directory | Category |
|---|---|---|
| {file} | {directory} | {category} |
Important: Create files in the specified directories to maintain project structure. If a directory doesn't exist, create it first before writing the file. """
If no warnings: FILE_PLACEMENT_CONTEXT = "" (empty)
Step 4.2: Assemble the full prompt
""" {PERSONALITY_CONTENT}
You are executing a plan as part of Legion. Follow the tasks below precisely.
{AUTHORITY_CONTEXT}
{CODEBASE_CONTEXT}
{FILE_PLACEMENT_CONTEXT}
{PLAN_CONTENT}
> verification: lines from each task's block and run them as bash commands> verification: line is a bash command that must return exit code 0When all tasks and verification are complete, report your results:
If adapter.structured_messaging is true (e.g., Claude Code):
If adapter.structured_messaging is false (e.g., Codex CLI, Cursor, Aider):
.planning/phases/{NN}/{NN}-{PP}-RESULT.mdYour summary MUST include these fields:
> verification: commands executedStep 4.9: Estimate prompt size and warn if approaching adapter limit Before spawning, estimate the token count of the assembled prompt:
Step 5: Spawn the agent per adapter protocol Use adapter.spawn_agent_personality with:
On CLIs without agent spawning (adapter.agent_spawning = false):
For autonomous plans (autonomous: true):
Step 1: Skip personality loading entirely
Step 2: Read the complete plan file
Step 3: Construct the autonomous execution prompt: """
You are executing a plan as part of Legion. No specialist agent personality is needed for this plan — execute the tasks directly.
{CODEBASE_CONTEXT}
{PLAN_CONTENT}
> verification: lines from each task's block and run them as bash commands> verification: line is a bash command that must return exit code 0When all tasks and verification are complete, report your results:
If adapter.structured_messaging is true (e.g., Claude Code):
If adapter.structured_messaging is false (e.g., Codex CLI, Cursor, Aider):
.planning/phases/{NN}/{NN}-{PP}-RESULT.mdYour summary MUST include these fields:
> verification: commands executedStep 4: Spawn the agent per adapter protocol Use adapter.spawn_agent_autonomous with:
### Personality Loading Notes
- If the personality file does not exist at the expected path after actually attempting to Read it (not assumed — you must have a real file-not-found error from the Read tool): STOP execution for this plan. Do NOT fall back to autonomous mode. Personality injection is non-negotiable for non-autonomous plans. Error: "Agent file {agent-id}.md not found at {path}. Run /legion:update to reinstall." Note: Step 5f pre-validation should catch this before you reach this point. If you're here, the pre-check was skipped — go back and run it.
- The personality content may be 200-500 lines. This is expected and intentional — full injection is the core mechanism that gives agents their specialist behavior.
- Cross-reference agent-registry.md (Section 1: Agent Catalog) for the canonical file path when in doubt.
### Future Optimization: Selective Personality Loading
> **Note**: This documents a future optimization path. No behavioral change is implemented — full injection remains the current approach.
For agents over 300 lines, a future version could split personality into two tiers:
- **Core personality** (~100 lines, always injected): Identity & Memory, Core Mission, Critical Rules, Communication Style — the sections that shape the agent's voice, decision-making, and behavioral boundaries.
- **Extended sections** (loaded conditionally): Technical Deliverables (code templates, report templates, framework configs) — loaded only when the task type matches the template domain.
This would reduce context consumption for large agents (currently 600+ lines) during parallel wave execution, where multiple agents each receive full personality injection. The Wave 3 standardization effort (target: 100-350 lines per agent) is the immediate mitigation — trimming verbose code examples in the largest agents while expanding thin stubs.
---
## Section 4: Wave Execution
How to execute each wave in order, dispatching plans in parallel within each wave.
Step 0: Initialize phase coordination (once, before the wave loop) Follow the active adapter's Execution Protocol for initialization:
If adapter.parallel_execution is true AND adapter.structured_messaging is true (e.g., Claude Code):
If adapter.parallel_execution is true but no structured messaging (e.g., Cursor):
If adapter.parallel_execution is false (e.g., Codex CLI, Aider):
For each wave number in ascending order (1, 2, 3, ...):
Step 1: Identify plans in the current wave
Step 2: Pre-execution dependency check
Step 3: Construct agent prompts for all plans in the wave
Sequential Files Pre-Dispatch Check (before Step 4 agent spawning):
Dispatch specification — Wave plan agents (canonical)
| Field | Value |
|---|---|
| When | For each wave in ascending wave-number order, after dependency check (Step 2), prompt construction (Step 3), and sequential-files check (above) complete. Fires once per wave. |
| Why parallel is safe | files_modified lists from plan frontmatter are collected across the wave and checked for pairwise intersection. If any overlap exists (including sequential_files-declared files), the wave falls back to sequential dispatch. Under parallel dispatch, no two agents can write the same file — verified by construction. |
| How many | Exactly the count of plans in the wave (N = len(wave.plans)). Do not reduce fan-out. |
| Mechanism | Same-response fan-out requirement — When adapter.parallel_execution == true AND no files_modified overlap exists: issue all N agent spawn calls in a SINGLE LLM response (same tool-call block). Do NOT split spawns across turns; splitting serializes them. For adapters that spawn via Bash: each spawn uses run_in_background: true and all N Bash calls must be in the same response block. For adapters with native agent-spawn tool: issue all N calls in parallel within one response. Sequential path: N calls ordered by plan number, with commit between each. Model: adapter.model_execution (or adapter.model_{tier} per agent frontmatter's model_tier field; default: execution). |
Step 4: Execute plans for this wave (adapter-conditional)
If adapter.parallel_execution is true (e.g., Claude Code, Cursor):
For a SINGLE plan in the wave:
For MULTIPLE plans in the wave (N = number of plans in the wave):
When to dispatch in parallel:
Why parallel is safe here:
How many agents to spawn:
Mechanism — Claude Code (adapter.parallel_execution=true, structured_messaging=true):
Mechanism — other adapters with parallel_execution=true:
Counter-example (DO NOT do this):
Correct example:
Post-dispatch verification (self-check before Step 5):
Count the Agent calls you just emitted in this single response.
If the count is less than N: STOP — you serialized the wave. Cancel any pending work and re-dispatch all N calls in one response.
Each agent gets its own fully-constructed prompt (personality + plan)
Agents in the same wave are fully independent — they share no state
If adapter.parallel_execution is false (e.g., Codex CLI, Gemini CLI, Aider):
Step 5: Collect results (adapter-conditional)
If adapter.structured_messaging is true (e.g., Claude Code):
If adapter.structured_messaging is false (e.g., Cursor, Codex CLI):
In all cases, track: which plans succeeded, which failed, what files were modified.
Step 6: Process wave results
Step 7: Post-wave decision
Step 8: After all waves complete
Step 9: Cleanup coordination (adapter-conditional)
### CLI-Specific Execution Details
The exact tools and lifecycle depend on the active adapter. See the adapter's Execution Protocol section for the complete implementation.
**Claude Code example** (parallel execution with Teams):
- TeamCreate → TaskCreate → parallel Agent calls → SendMessage collection → TeamDelete
- See `adapters/claude-code.md` for the full lifecycle
**Codex CLI / Gemini CLI example** (sequential execution):
- WAVE-CHECKLIST.md → sequential plan execution → RESULT.md files
- See `adapters/codex-cli.md` or `adapters/gemini-cli.md`
**Cursor example** (parallel execution via async subagents):
- Spawn subagents asynchronously → poll for RESULT.md files
- See `adapters/cursor.md`
All execution models share these invariants:
- The orchestrator waits until all plans in a wave complete before advancing
- Within a wave, agents share no state — each operates on its own plan
- Results are written to SUMMARY.md files regardless of the collection mechanism
---
## Section 5: Agent Result Processing
How to interpret what each agent returns and write the plan summary file.
For each completed agent (success or failure):
Step 1: Parse the agent's completion report The agent's report (received per adapter.collect_results) contains a structured summary with these fields:
> verification: commands executedUse the Status field directly to determine the result:
Step 2: Determine result status
> verification: command
returned non-zero exit code and the agent could not fix it after one attemptIMPORTANT: Verification failure is a hard gate. Unlike <verify> block outputs which
are advisory, > verification: command failures block plan completion. A plan with
any failed verification command MUST have Status: Failed or Status: Partial
(never Status: Complete).
Step 3: Generate the plan summary file Path: .planning/phases/{NN}-{phase-slug}/{NN}-{PP}-SUMMARY.md
Write the file using this format:
Status: Complete | Partial | Complete with Warnings | Failed Wave: {wave_number} Agent: {agent-id} | Autonomous Completed: {timestamp}
This section is auto-generated from agent-registry score_export data. Omitted for autonomous tasks where no recommendation was run.
| Candidate | Semantic | Heuristic | Memory | Total | Source |
|---|---|---|---|---|---|
| {selected agent} | {strong/moderate/weak} | {score} | {boost} | {total} | {semantic/heuristic/memory/mandatory} |
| {runner-up 1} | ... | ... | ... | ... | ... |
| {runner-up 2} | ... | ... | ... | ... | ... |
If the plan's autonomous: true or no score_export data is available, omit the
"Agent Selection Rationale" section entirely. Do not output an empty section.
Data source: The executing agent reconstructs the rationale from the plan's context
(plan frontmatter agents field, task descriptions, and agent-registry scoring criteria).
This is an LLM-native approach — the agent re-derives WHY this agent was selected based on
the task requirements and agent-registry's scoring rules, rather than consuming a serialized
data payload. The score_export structure in agent-registry Section 3 defines what fields
to populate, but the executing agent computes these at SUMMARY.md generation time.
{Summary of actions taken, derived from the agent's return message. Should be specific: "Created skills/wave-executor/SKILL.md (312 lines) with 6 sections covering plan discovery, personality injection, wave execution, result processing, and error handling."}
{Output from the plan's verification steps, as reported by the agent. Include actual command outputs where available.}
| Command | Exit Code | Result |
|---|---|---|
test -f path/to/file.md | 0 | PASS |
grep -q "Section 1:" path/to/file.md | 0 | PASS |
wc -l < path/to/file.md | xargs test 50 -le | 1 | FAIL — file has 42 lines |
{Notable implementation decisions, ambiguities resolved, approaches chosen. If none: "No significant decisions — followed plan as written."}
{Any problems, deviations, or warnings. If none: "None."}
{If the agent raised any blocks during execution, list them here. If none: "None."}
| # | Severity | Type | Decision | Status | Resolution |
|---|---|---|---|---|---|
| 1 | {severity} | {type} | {decision text} | {pending/approved/rejected/deferred} | {resolution details or "Awaiting decision"} |
deferred may appear only after the user explicitly selects Defer in the escalation
prompt. Agent-authored output never sets an escalation to deferred; new escalation
blocks start as pending until routed by the orchestrator.
{List the requirement IDs from the plan's frontmatter}
For FAILED plans, also include:
{Full error output from the agent. Do not truncate — this is used for diagnosis in /legion:review. Include: error messages, stack traces if available, which task failed, what the state of the filesystem is (what was partially completed).}
Step 4: Confirm summary file was written
### Phase Decision Summary (decision_capture)
After all per-plan SUMMARY.md files are written for a phase, produce a phase-level decision summary appended to the final wave's completion report:
```markdown
### Phase Decision Summary
| Plan | Agent | Confidence | Adapter | Model Tier | Escalations |
|------|-------|------------|---------|------------|-------------|
| 01 | {agent-id} | {HIGH/MEDIUM/LOW} | {adapter} | {tier} | {count or "none"} |
| 02 | ... | ... | ... | ... | ... |
Escalations are decisions where an agent encountered an out-of-scope action and
documented it per the authority matrix escalation protocol.
This summary is reconstructed from the individual SUMMARY.md files' Agent Selection Rationale sections. If a plan was autonomous, its row shows "Autonomous" for Agent and dashes for Confidence/Adapter/Model Tier.
Summary files follow the Plan File Convention from workflow-common.md:
.planning/phases/{NN-name}/{NN}-{PP}-SUMMARY.md
Examples:
.planning/phases/04-parallel-execution/04-01-SUMMARY.md.planning/phases/04-parallel-execution/04-02-SUMMARY.mdThe presence of a SUMMARY.md file is the signal used in Section 4, Step 2 to verify that a dependency plan completed. A failed plan still gets a SUMMARY.md (with Status: Failed) so that the dependency check correctly identifies and blocks dependent waves.
After each agent completes a task, scan its output for <escalation> blocks and route them according to the escalation protocol defined in .planning/config/escalation-protocol.yaml.
After receiving an agent's completion report (Section 5, Step 1):
1. Scan the full agent output text for <escalation> ... </escalation> blocks
2. For each escalation block found:
a. Parse the YAML-formatted content inside the block tags
b. Extract required fields: severity, type, decision, context
c. Extract optional fields if present: alternatives, affected_files, related_domain
3. Validate each escalation block:
- All 4 required fields must be present
- severity must be one of: info | warning | blocker
- type must be one of: architecture | dependency | scope | schema | api | deletion | infrastructure | quality
- If any required field is missing or invalid, treat the escalation as severity: warning
and append a note: "Malformed escalation block — defaulted to warning severity"
- Ignore any agent-authored `status` or `resolution` field. New escalation blocks
always start as status: pending until the orchestrator routes them.
4. Collect all parsed escalation blocks into an escalation_list for this agent
Before routing escalations, check the current control_mode profile
(resolved by workflow-common-core Settings Resolution Protocol):
1. Read the effective control_mode from the resolved settings profile
2. Apply control_mode_behaviors from escalation-protocol.yaml:
autonomous mode:
- Override ALL escalation severities to "info"
- Agent proceeds with the action — escalations are logged only
- No user prompts, no task halting
guarded mode (default):
- Use declared severity as-is — no override
- Route according to severity_levels routing rules
advisory mode:
- Override ALL escalation severities to "info"
- Agents are read-only so nothing to halt
- Log all escalations for informational review
surgical mode:
- Use declared severity as-is, but floor is "warning" (never downgrade to info)
- Auto-generate blocker escalation_block for any file access not in plan files_modified:
severity: blocker
type: scope
decision: "Agent attempted to modify {file_path} which is not in files_modified."
context: "Surgical mode requires all file modifications to be pre-approved in the plan. This file was not listed."
- This auto-escalation happens even without an explicit <escalation> block from the agent
3. Store the effective severity (after override) on each escalation_block
For each escalation_block in the escalation_list (using effective severity after control mode override):
info:
1. Append to SUMMARY.md Escalations table with status: "logged"
2. Continue to next escalation or next agent — no interruption
warning:
1. Append to SUMMARY.md Escalations table with status: "logged"
2. Display escalation to orchestrator output with highlight:
"[ESCALATION WARNING] {type}: {decision}"
3. Continue to next escalation or next agent — no interruption
blocker:
1. Append to SUMMARY.md Escalations table with status: "pending"
2. Display full escalation details to user:
## Escalation: {type}
**Severity**: BLOCKER
**Agent**: {agent_id}
**Decision needed**: {decision}
**Context**: {context}
**Alternatives**: {alternatives, if provided}
**Affected files**: {affected_files, if provided}
3. Prompt user via adapter.ask_user:
"How would you like to proceed? [A]pprove / [R]eject / [D]efer"
4. Record resolution:
- Approve: Update SUMMARY.md escalation status to "approved",
note what was approved. Agent may proceed with the action if
re-executed (blocker escalations do not auto-retry — the approved
action is recorded for reference in subsequent builds).
If the blocked task could not complete, mark the plan as
"Partial" and inform the user they must re-run
`/legion:build` to execute the approved action.
- Reject: Update SUMMARY.md escalation status to "rejected",
note the rejection reason. Agent must find an alternative approach
within its authorized scope. If no authorized alternative completes
the task, mark the plan "Partial" or "Failed" with evidence.
- Defer: Update SUMMARY.md escalation status to "deferred",
note deferral rationale. This option is valid only when selected by
the user through adapter.ask_user. Task remains incomplete; mark the
affected plan "Partial" or "Failed", stop dependent waves, and track
the decision for future phase resolution.
After processing all escalation_blocks for all agents in a wave:
1. Count escalations by severity and type across all agents
2. Include escalation counts in the Phase Decision Summary table (Section 5):
- "Escalations" column shows: "{blocker_count}B / {warning_count}W / {info_count}I"
- If no escalations: show "none"
3. If any blocker escalations were approved-but-not-executed, rejected without an
alternative, or explicitly deferred by the user:
- Flag the affected plan as "Partial" or "Failed" (never "Complete" or
"Complete with Warnings")
- Stop dependent waves because planned work remains incomplete
- Include approved/rejected/deferred escalation details in the Issues Encountered section
def detect_and_route_escalations(agent_output, agent_id, control_mode, plan_files_modified):
"""
Scan agent output for escalation blocks and route by severity.
Called after each agent completes (Section 5, Step 1).
"""
escalation_list = []
# Step 1: Parse escalation blocks from agent output
escalation_blocks = extract_blocks(agent_output, tag="escalation")
for block in escalation_blocks:
parsed = parse_yaml(block.content)
# Validate required fields
required = ["severity", "type", "decision", "context"]
if not all(f in parsed for f in required):
parsed["severity"] = "warning"
parsed["_note"] = "Malformed escalation block - defaulted to warning"
parsed.pop("status", None)
parsed.pop("resolution", None)
parsed["status"] = "pending"
valid_severities = ["info", "warning", "blocker"]
if parsed.get("severity") not in valid_severities:
parsed["severity"] = "warning"
escalation_list.append(parsed)
# Step 1b: Surgical mode auto-escalation for out-of-scope files
if control_mode == "surgical":
modified_files = extract_modified_files(agent_output)
for file_path in modified_files:
if file_path not in plan_files_modified:
escalation_list.append({
"severity": "blocker",
"type": "scope",
"decision": f"Agent modified {file_path} not in files_modified",
"context": "Surgical mode file scope violation",
"_auto_generated": True
})
# Step 2: Apply control mode severity override
for escalation_block in escalation_list:
if control_mode == "autonomous" or control_mode == "advisory":
escalation_block["effective_severity"] = "info"
elif control_mode == "surgical":
if escalation_block["severity"] == "info":
escalation_block["effective_severity"] = "warning"
else:
escalation_block["effective_severity"] = escalation_block["severity"]
else: # guarded (default)
escalation_block["effective_severity"] = escalation_block["severity"]
# Step 3: Route by effective severity
for escalation_block in escalation_list:
route_escalation(escalation_block, agent_id)
return escalation_list
When dispatching Wave 2+ agents, the wave executor compiles and injects structured handoff context from prior waves. This enables forward-only information flow between agents without runtime messaging.
Protocol defined in .planning/config/agent-communication.yaml.
Before spawning each agent (regardless of wave), compile discovery context and inject it into the agent's prompt after personality injection (Section 3) and before task instructions:
For each plan being dispatched:
1. Compile discovery context:
- current_wave: "Wave {N} of {total_waves}"
- wave_agents: list of other agent-ids executing in the same wave (parallel peers)
- Format: "{agent-id} (Plan {NN}-{PP})" for each peer
- If solo: "solo"
- prior_wave_agents: list of agent-ids that executed in earlier waves
- Format: "{agent-id} (Plan {NN}-{PP})" for each prior agent
- If Wave 1: "None (first wave)"
- own_domains: agent's exclusive_domains from authority-matrix.yaml
2. Inject discovery context into agent prompt:
## Execution Context
- Wave: {N} of {total_waves}
- Parallel peers: {wave_agents or "solo"}
- Prior wave: {prior_wave_agents or "None (first wave)"}
- Your domains: {comma-separated domain list}
3. This block is injected AFTER the agent personality and BEFORE
any handoff context or task instructions.
When dispatching a plan in Wave 2 or later:
1. Identify dependency summaries:
a. Read the plan's frontmatter depends_on list
b. For each dependency, locate its SUMMARY.md:
- Path: .planning/phases/{phase-dir}/{NN}-{PP}-SUMMARY.md
c. If a dependency SUMMARY.md does not exist:
- Log warning: "Dependency {NN}-{PP} SUMMARY.md not found for plan {current-plan}"
- Continue without that dependency's handoff context
- The agent will operate with incomplete context (graceful degradation)
2. Extract handoff context from each dependency SUMMARY.md:
a. Parse the "## Handoff Context" section
b. Extract fields: key_outputs, decisions_made, open_questions, conventions_established
c. If the Handoff Context section is missing or malformed:
- Fall back to extracting "## Files Modified" and "## Completed Tasks" as minimal context
- Log warning: "SUMMARY.md for {NN}-{PP} missing Handoff Context section — using minimal handoff"
3. Extract pending escalations from each dependency SUMMARY.md:
a. Parse the "## Escalations" section (if present)
b. Filter for escalations with status: pending or deferred
c. Collect these as escalations_pending for downstream injection
4. Compile the handoff briefing:
- Merge handoff context from all dependencies
- Group by source plan for clarity
- Append any pending escalations as a separate section
After compiling the handoff briefing (Step 2), inject it into the
agent's spawn prompt between the discovery context and task instructions:
## Handoff Context from Prior Wave
### From Plan {NN}-{PP}: {plan title}
**Key outputs**: {key_outputs}
**Decisions made**: {decisions_made}
**Open questions**: {open_questions}
**Conventions established**: {conventions_established}
{Repeat for each dependency plan}
{If escalations_pending is non-empty:}
### Pending Escalations
The following escalations from prior waves remain unresolved:
| Severity | Type | Decision | Status |
|----------|------|----------|--------|
| {severity} | {type} | {decision} | {status} |
{If no handoff context available (all dependencies missing):}
## Handoff Context from Prior Wave
No handoff context available from prior waves. Proceed with task instructions.
def compile_and_inject_handoff(plan, phase_dir, wave_number):
"""
Compile handoff context from dependency plans and inject into agent prompt.
Called during agent dispatch for Wave 2+ plans.
"""
if wave_number <= 1 and not plan.depends_on:
return "" # No handoff needed for Wave 1 without explicit dependencies
handoff_sections = []
pending_escalations = []
for dep_id in plan.depends_on:
summary_path = f"{phase_dir}/{dep_id}-SUMMARY.md"
if not file_exists(summary_path):
log_warning(f"Dependency {dep_id} SUMMARY.md not found for plan {plan.id}")
continue
summary_content = read_file(summary_path)
# Extract handoff context section
handoff = extract_section(summary_content, "## Handoff Context")
if handoff:
handoff_sections.append({
"plan_id": dep_id,
"title": extract_plan_title(summary_content),
"context": handoff
})
else:
# Graceful fallback: use Files Modified + Completed Tasks
minimal = extract_minimal_handoff(summary_content)
handoff_sections.append({
"plan_id": dep_id,
"title": extract_plan_title(summary_content),
"context": minimal,
"_fallback": True
})
# Extract pending escalations
escalations = extract_section(summary_content, "## Escalations")
if escalations:
pending = filter_escalations(escalations, statuses=["pending", "deferred"])
pending_escalations.extend(pending)
return format_handoff_briefing(handoff_sections, pending_escalations)
After each plan completes and its SUMMARY.md is written, validate that the file conforms to the export standard defined in .planning/config/agent-communication.yaml.
After a plan's SUMMARY.md is written (Section 5, after result collection):
1. Read the SUMMARY.md file that the agent produced
2. Check for required sections (all must be present):
- "## Completed Tasks"
- "## Files Modified"
- "## Handoff Context"
- "## Verification Results"
3. For each missing required section:
- Log advisory warning:
"[SUMMARY VALIDATION] Plan {NN}-{PP}: missing required section '{section_name}'"
- This is advisory, NOT blocking — the plan is not failed for missing sections
- Missing sections degrade handoff quality but do not halt execution
4. Check for conditional sections when applicable:
- If agent output contained <escalation> blocks but SUMMARY.md has no "## Escalations":
Log: "[SUMMARY VALIDATION] Plan {NN}-{PP}: escalation blocks detected but no Escalations section"
5. Report validation results in wave completion output:
- "SUMMARY.md validation: {plan_id} — {pass_count}/{total} required sections present"
Rationale: This maintains Legion's "degrade gracefully" principle.
A missing handoff section means downstream agents get less context,
but execution is never blocked by incomplete documentation.
At each wave boundary (after all plans in a wave complete, before starting next wave):
1. Log wave completion summary to build output:
=== Wave {N} Complete ===
Plans completed: {count} ({list of plan IDs})
Plans failed: {count} ({list of plan IDs, or "none"})
Handoff context available: {count} plans with valid Handoff Context sections
Pending escalations carried forward: {count} ({or "none"})
2. If proceeding to next wave:
- Log: "Advancing to Wave {N+1} with handoff context from {count} prior plans"
- List each prior plan and its handoff status (full / minimal / missing)
3. If stopping after wave (due to failures or final wave):
- Log: "Wave execution complete. Final wave: {N} of {total_waves}"
- Include aggregate handoff summary for post-build review
How to handle common failure modes without retrying or hiding problems.
1. AGENT SPAWN FAILURE
Symptom: The Agent tool call itself returns an error (model unavailable,
invalid parameters, context too large, team_name invalid, etc.)
Action:
- Mark the plan as failed in the wave results
- Call TaskUpdate to mark the plan's task as failed (if task was created)
- Capture the tool error message
- Write a SUMMARY.md with Status: Failed and the spawn error details
- Continue executing other plans in the same wave that haven't failed
- After wave collection, apply post-wave decision logic (Section 4, Step 7)
Example errors:
- "Failed to spawn agent for plan 04-01: model sonnet unavailable"
- "Failed to spawn agent for plan 04-01: team 'phase-04-execution' not found"
2. AGENT TIMEOUT / CONTEXT OVERFLOW
Symptom: Agent runs but produces incomplete output; context limit reached
Action:
- Capture whatever output the agent produced before stopping
- Treat as a failure — do not try to resume the agent
- Write SUMMARY.md with Status: Failed and note: "Agent context limit reached.
The plan may need to be split into smaller tasks."
- Include partial output in Error Details for diagnosis
3. VERIFICATION FAILURE
Symptom: Agent completes all tasks but verify commands produce unexpected results
(file missing, grep finds wrong content, line count too low, etc.)
Action:
- If any `> verification:` command failed and could not be fixed after one attempt,
mark Status as Partial or Failed based on whether any planned outputs are usable
- Use Status: Complete with Warnings only for non-critical `<verify>` checklist
concerns after all `> verification:` commands passed
- Include the failing verify outputs in the Verification Results section
- Note in Issues Encountered: "Verify step N returned unexpected result: {output}"
- The plan is not retried; /legion:review will assess whether it's acceptable
4. FILE MODIFICATION CONFLICT (same-wave file collision)
Symptom: Two plans in the same wave have overlapping files_modified entries
Detection: During plan discovery (Section 2, Step 5d)
Action:
- Do NOT abort — continue execution with a warning
- Log: "Warning: plans {NN}-{PP} and {NN}-{PP2} both modify {file path}.
The second agent's changes will overwrite the first. Review the phase plan."
- In the wave completion report, flag the conflict explicitly
- Suggest the user re-plan the phase to move one plan to a later wave
5. MISSING PERSONALITY FILE
Symptom: The agent .md file does not exist at {AGENTS_DIR}/{agent-id}.md
IMPORTANT: This is almost always a MODEL ERROR, not a real missing file.
The 48 agent files ship with Legion and exist at both ~/.claude/agents/ and
agents/ (local dev). If you believe a file is missing, you MUST have actually
attempted to Read it and received a file-not-found error. Do NOT claim files
are missing based on assumption or pre-trained knowledge.
Action:
- FIRST: Confirm you actually attempted to Read the file (Step 5f pre-check
should have caught this). If you skipped the pre-check, go back and do it now.
- If Read genuinely returns file-not-found after trying both AGENTS_DIR paths:
STOP execution for this plan. Do NOT fall back to autonomous mode.
- Error: "Agent file not found for {agent-id}. Checked paths:
{global-path} and {local-path}. This plan cannot execute without its
personality file. Run /legion:update to reinstall agent files."
- In the plan SUMMARY.md, mark status as "blocked" with the missing file details
- Rationale: Autonomous fallback silently degrades execution quality. Personality
injection is the core mechanism — running without it produces generic output
that defeats the purpose of specialist agents. Failing loudly is better than
succeeding silently with degraded quality.
6. NO PLANS FOUND
Symptom: The phase directory exists but contains no {NN}-{PP}-PLAN.md files
Action:
- Error immediately — do not attempt execution
- Message: "No plans found for Phase {N} in .planning/phases/{NN}-{slug}/.
Run /legion:plan {N} first to generate plan files."
- Suggest: check if the phase directory name matches STATE.md's current phase
7. PARTIAL WAVE FAILURE (some plans succeed, some fail)
Symptom: A wave with multiple plans has a mix of successes and failures
Action:
- Write SUMMARY.md files for ALL plans in the wave (both succeeded and failed)
- Collect and report all results before making the post-wave stop decision
- Stop after the wave — do not proceed to the next wave even if most plans succeeded
- Report clearly: "Wave {N}: {X} of {Y} plans succeeded. Stopping before Wave {N+1}.
Failed plans: {list}."
- This prevents later waves from building on a broken foundation
8. PHASE ALREADY PARTIALLY EXECUTED
Symptom: Some SUMMARY.md files already exist for plans in the phase
Detection: During plan discovery
Action:
- Report the already-completed plans: "Found {count} existing summaries.
The following plans have already been executed: {list}"
- Ask user: "Re-run all plans (including completed ones), or skip to
incomplete plans only?"
- If skip: filter the wave map to exclude plans with existing SUMMARY.md files
- If re-run: delete existing SUMMARY.md files and execute all plans fresh
9. AGENT COMPLETES BUT DOESN'T REPORT
Symptom: An agent goes idle without reporting results per adapter.collect_results.
The agent may have completed its work but forgot the Reporting Results step.
Detection: Agent appears idle but no completion report was received per adapter protocol.
Action:
- Follow up per adapter protocol: send a message asking for the structured summary
with Status, Files, Verification, Decisions, Issues, and Errors fields.
- Wait for the agent's response
- If the agent still doesn't respond: infer the result from the filesystem