---
name: execute-spec
description: Execute an implementation spec generated by ideation. Invokes scout agent for codebase exploration, builds components with feedback loops, then runs a verify-review-fix cycle with the reviewer agent before committing.
---

# Execute Ideation Specification

## Arguments: $ARGUMENTS

Execute a spec file generated by the ideation skill.

**Parse arguments:**

- `--parallel` flag: Enable parallel execution via subagents
- Remaining argument: Spec file path (optional)

Example: `/skill:execute-spec --parallel` or `/skill:execute-spec docs/ideation/foo/spec-phase-1.md`

## Pre-Execution

### 1. Load Specification

**If argument provided:** Read the spec file directly.

**If no argument:** Search for specs:

```
./docs/ideation/*/spec-phase-*.md
```

If multiple found, ask the user to select one.

### 2. Scout Codebase

**Invoke the Scout agent** to explore the codebase and produce a structured context map. The scout runs as a read-only subagent, scores implementation readiness, and persists its findings.

**Determine the project directory** from the spec file path. If the spec is at `docs/ideation/my-project/spec-phase-1.md`, the project directory is `docs/ideation/my-project/`.

**Invoke the Scout** using the `subagent` tool:

- **agent**: `scout`
- **task**: Include the spec file path, project directory, phase number, and whether a prior `context-map.md` exists

The scout's agent definition (`agents/scout.md` in this package) instructs read-only behavior — it uses only `read`, `grep`, `find`, and `ls` tools.

The scout may perform up to 2 internal exploration rounds before reaching a verdict.

**After the scout completes**, parse the scout's text response for the context map and verdict. Write the context map to `{project-directory}/context-map.md`.

**If scout returns GO** (confidence >= 70):

- The context map is ready. Use its sections during implementation:
  - **Key Patterns**: Already-identified patterns to follow (avoid redundant file reads)
  - **Dependencies**: Know what's affected by your changes
  - **Conventions**: Naming, imports, error handling to match
  - **Risks**: Watch for these during build
- Proceed to spec parsing

**If scout returns HOLD** (confidence < 70):

- Present the gap analysis to the user:

```
Scout confidence is {score}/100 (below 70 threshold).
Gaps: {summary of lowest dimensions}. How to proceed?

1. **Proceed anyway** — Build with known gaps. May require more iteration.
2. **Update spec** — The spec may be underspecified. Pause to revise.
3. **Abort** — Stop execution for this phase.
```

**If the user chose "Proceed anyway" after HOLD**: The context map may have gaps. During build, treat missing sections as unavailable and read files directly. Pay extra attention to the Risks section of a partial context map.

**If no scout agent is available** (subagent tool not installed or invocation fails): Fall back to inline exploration:

1. Read all "Pattern to follow" file paths from the spec
2. Read all files in the spec's "Modified Files" section
3. If creating files alongside existing analogues, read the analogues
4. Use `grep` to check what imports or references the modified files (blast radius)
5. Read `AGENTS.md`, `CLAUDE.md`, or project README for conventions

### 3. Parse Spec Structure

Extract from the spec file (and template if applicable):

- **Technical Approach** - Overall implementation strategy
- **File Changes** - New files, modified files, deleted files
- **Implementation Details** - Per-component instructions with code patterns
- **Testing Requirements** - Unit tests, integration tests, manual testing
- **Validation Commands** - Commands to verify implementation
- **Feedback Strategy** - Top-level inner-loop command and playground type (if present)
- **Per-component Feedback Loops** - Playground, experiment, and check command for each component (if present)

**Also extract and retain for the review cycle:**

- **Pattern file list** — scan all components' Implementation Details for "Pattern to follow" entries. Collect every referenced file path into a single list. This list is passed to the reviewer agent during the post-execution review cycle.

### 4. Set Up Feedback Environment

Before implementing any component, establish the spec's feedback environment. This is a one-time setup.

1. **Read the Feedback Strategy** section from the spec. Identify the playground type and inner-loop command.

2. **Auto-detect feedback infrastructure** — even if the spec has no Feedback Strategy section, probe the codebase:
   - Read `package.json` (or equivalent manifest) for scripts: `test`, `dev`, `start`, `storybook`, `typecheck`
   - Check for test runner configs: `jest.config.*`, `vitest.config.*`, `.mocharc.*`, `pytest.ini`, `go.mod`
   - Check for dev server configs: `vite.config.*`, `next.config.*`, `webpack.config.*`
   - Check for storybook: `.storybook/` directory
   - Check for existing script harnesses: `scripts/`, `bin/`, `Makefile`

3. **Set up the playground** if it requires infrastructure:
   - **Test runner**: Verify the test command works
   - **Dev server**: Start it and verify it's running
   - **Storybook/harness**: Start it if the spec calls for one

4. **Verify the inner-loop command runs** (even if it does nothing yet). This catches environment issues before they block implementation.

5. **Fallback**: If no Feedback Strategy in the spec AND no feedback infrastructure detected, fall back to Validation Commands as the post-implementation check.

## Build Phase

### For Each Component

Work through components in dependency order:

1. **Read** the component's implementation details
2. **Read before writing** — If modifying existing files, read them first. If creating files alongside existing analogues, read the analogues to match patterns.
3. **Set up component feedback loop** (if the component has one):
   a. Create the playground artifact first (e.g., create the test file with a describe block, create the script harness)
   b. Run the check command once to verify the loop works
4. **Build incrementally**:
   a. Follow the pattern specified (if "Pattern to follow" is listed)
   b. Implement a meaningful chunk (one function, one handler, one subcomponent)
   c. Run the component's **check command** (or the spec's inner-loop command)
   d. If the check fails: read the output, fix, re-run. Iterate until passing.
   e. Move to the next chunk. Repeat.
5. **Run the component's experiment** (if specified) — the parameterized check with specific inputs.

### Component Completion

After implementing a component:

1. Run the component's **experiment** if defined (edge cases, parameterized inputs)
2. Run the spec's **inner-loop command** (top-level quick check) to verify nothing regressed
3. Report any issues before proceeding to the next component

### Handling Issues

If validation fails:

1. Report the error clearly
2. Attempt to fix based on error message
3. Re-run validation
4. If still failing, pause and ask user

### Parallel Execution (with `--parallel` flag)

**Default (no flag):** Sequential execution — work through components one at a time.

**With `--parallel` flag:** Use pi-subagents for independent components:

1. Identify components with no dependency on each other
2. If only one unblocked component, execute directly
3. If multiple unblocked components:
   - Use `/parallel worker "implement component A per spec" -> worker "implement component B per spec"`
   - Each subagent implements its component following the same build flow above
4. **File conflicts**: If two components modify the same file, do NOT parallelize them — execute sequentially to avoid conflicts.

**Review cycle in parallel mode**: Subagents only build — they do not run their own review cycles. After all components are complete, run a single verify-review-fix loop on the combined diff.

## Post-Execution: Verify-Review-Fix Loop

After all components are completed, enter the review cycle. Code is **not committed** until the review passes or the user explicitly accepts remaining issues.

**Do not stage files until after the review passes.** The reviewer uses `git diff HEAD` to see all changes.

### Verify

Run all commands from the spec's "Validation Commands" section:

- Type check
- Lint
- Tests
- Build

If any validation command fails, fix the issue before proceeding to review. Validation failures do not consume a review cycle.

### Review (Cycle 1 of max 3)

**If git diff is empty** (no changes to review): Skip the review cycle entirely. Report that all components were no-ops and proceed to the completion report.

**Invoke the Reviewer agent** using the `subagent` tool:

- **agent**: `reviewer`
- **task**: Include the spec file path, the pattern file list (collected during spec parsing), the cycle number (1, 2, or 3), and if cycle > 1, the prior cycle's findings

The reviewer's agent definition (`agents/reviewer.md` in this package) instructs it to only use `bash` for `git diff HEAD` commands and to never edit files.

**Parse the reviewer's output:**

1. Look for the verdict line: `**Verdict**: PASS` or `**Verdict**: FAIL`
2. Count findings by severity: lines starting with `critical/`, `high/`, `medium/`, `low/`
3. If zero `critical` AND zero `high` → **PASS**
4. If any `critical` or `high` → **FAIL**

**If the reviewer fails or returns no verdict**: Fall back to validation-only mode — treat validation command results as sufficient. Log a warning. Continue to commit.

### On PASS

Review passed. Proceed to commit and completion report.

Report medium and low findings to the user for awareness, but they do not block the commit.

### On FAIL (Cycle < 3)

1. Read each `critical` and `high` finding
2. Apply the suggested fix (the `→ action` part)
3. Re-run **Verify** (all validation commands)
4. If verify passes, invoke **Review** again (increment cycle number)

### On FAIL (Cycle = 3, final)

Escalation. Present remaining findings to the user:

```
Review cycle 3 still has {N} critical/high findings. How to proceed?

1. **Fix manually** — You fix the remaining issues yourself. Re-run /skill:execute-spec after fixing.
2. **Accept with issues** — Commit with known issues. Findings included in completion report.
3. **Abort** — Do not commit. Leave changes unstaged for manual review.
```

### Commit

Only reached after PASS or user acceptance:

1. Stage all changed files relevant to this phase (use specific file names, not `git add -A`)
2. Commit with a descriptive message following the project's commit conventions
3. If review took multiple cycles, include the cycle count in the commit body

### Completion Report

```markdown
## Phase {N} Implementation Complete

### Implemented
- {List of components implemented}

### Files Changed
- {List of files created/modified}

### Review Summary
- Cycles: {N} of 3 max
- Findings addressed: {count} ({critical} critical, {high} high auto-fixed)
- Remaining (non-blocking): {count} ({medium} medium, {low} low)
- Acknowledged issues: {count, if user accepted with issues}

### Validation Results
- Type check: PASS/FAIL
- Lint: PASS/FAIL
- Tests: PASS/FAIL

### Acceptance Criteria
- [x] {Met criteria}
- [ ] {Unmet criteria with notes}

### Next Steps
- Review changes: `git log -1 --stat`
- For next phase: `/skill:execute-spec spec-phase-{N+1}.md`
```

## Key Principles

1. **Read before writing** - Understand existing code and patterns before creating or modifying files
2. **Feedback loops over post-hoc validation** - Set up the check cycle before building, not after
3. **Fast inner loop** - The check command should run in seconds
4. **Follow spec literally** - Don't improvise beyond what's specified
5. **Match existing patterns** - New code should look like it belongs
6. **Human in loop** - Pause when uncertain, don't guess
7. **One phase at a time** - Complete this phase fully before moving on
8. **Review before commit** - Code is not committed until the reviewer passes or the user explicitly accepts
9. **Fix, don't argue** - When the reviewer flags an issue, fix it. Don't rationalize.
10. **Escalate, don't loop forever** - 3 cycles max. If the same findings persist, the spec or approach needs human input.
