---
name: ao-implementation
description: "Implement only after a validated/approved plan. Use for coding: small diffs, frequent tests, no refactors, stop on ambiguity."
category: core
invokes: [ao-state, ao-validation, ao-testing, ao-git, ao-task, ao-debugging, ao-usage]
invoked_by: []
state_files:
  read: [constitution.md, baseline.md, focus.json, issues/active.jsonl, issues/references/*]
  write: [issues/events.jsonl, focus.json]
references: [.ao/references/confidence.md, .ao/references/completion-gate.md]
---

# Implementation workflow

> **Confidence Reference**: This skill uses canonical confidence definitions from [.ao/references/confidence.md](.ao/references/confidence.md). Low-confidence work requires mandatory baseline and stricter validation.
> **Completion Gate**: See [.ao/references/completion-gate.md](.ao/references/completion-gate.md) for all gate requirements.

### Review Triggers

**After Each Task** (during implementation):
- Run ao-review on current changes
- Present results
- Fix Critical/Important items before continuing
- Update focus with review results

**After Major Feature** (comprehensive):
- Run ao-review on full feature
- Check plan compliance
- Assess code quality
- Present comprehensive results
- Fix Critical/Important items before continuing

**Before Completion** (final gate):
- Run final ao-review
- All changes must pass review
- Critical findings must be resolved
- Update issue notes with review history

**Manual** (on demand):
- `/ao-review {ISSUE-ID}` - Review specific issue
- `/ao-review --review-since {date}` - Review changes since date

**Uses `ao` CLI for all issue operations.** Most commands need no global flags. Use `--yes` only for interactive commands. See `ao-usage` skill for full command reference.

## Build/Test Commands (from constitution)

Implementation uses project-specific commands from **constitution.md**:

```bash
# Read actual commands from .agent/ops/constitution.md
build: uv run python -m build     # or: npm run build
lint: uv run ruff check .         # or: npm run lint  
test: uv run pytest               # or: npm run test
format: uv run ruff format .      # or: npm run format
```

## Issue Tracking via ao CLI

| Operation | Command |
|-----------|--------|
| Start work | `printf '%s' '{"set":{"status":"in_progress"},"append":{"log":[{"ts":"YYYY-MM-DD","text":"Started"}]}}' \| ao issue patch ISSUE_ID --in -` |
| Add log entry | `ao log add ISSUE_ID "progress note"` |
| Check AC item done | `ao ac check ISSUE_ID INDEX` |
| Create follow-up | pipe IssueCreateInput JSON to `ao issue add --in -` |
| Complete issue | `ao issue close ISSUE_ID --log "Done: summary" --status done` |

### Time Tracking

Time tracking is handled via `ao log add`. When beginning work, patch the issue to `in_progress`. On completion, `ao issue close` records `completed_at` automatically.

### Example Implementation Flow

1. `ao issue patch ISSUE_ID --in - <<<'{"set":{"status":"in_progress"}}'` — claim issue
2. Update `.agent/ops/focus.json` — "Implementing {ISSUE-ID}"
3. Run tests after each change (from constitution)
4. `ao log add ISSUE_ID "Completed step N"` — progress log
5. When done: `ao issue close ISSUE_ID --log "Done: {summary}" --status done`

## Preconditions
- Constitution is confirmed.
- Baseline exists.
- Final plan exists and is approved (or stop and ask for approval).
- Work is tracked as an issue (or create one before starting).
- **Implementation details file exists** (from planning phase) — check `.agent/ops/issues/references/{ISSUE-ID}-impl-plan.md`

## <HARD-GATE> No Code Without Approved Plan and Failing Test

**Do NOT write production code without:**
1. An approved plan (from ao-planning)
2. For FEAT issues: a failing test that defines the expected behavior

This gate is enforced at ALL confidence levels:
- If no approved plan exists → STOP and invoke ao-planning
- If FEAT issue has no failing test → STOP and write the test first (Red step)
- BUG/CHORE/REFAC issues: approved plan required, test-first recommended but not mandatory

Violation of this gate is a **protocol failure**.

## TDD Iron Law (MANDATORY for FEAT issues)

> **Credit**: Test-Driven Development "Iron Law" adapted from obra/superpowers by Jesse Vincent (MIT License). See `.agent/ops/references/superpowers-analysis.md` Section 2 and obra/superpowers `skills/test-driven-development/SKILL.md`.

**NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST.**

### Red-Green-Refactor Cycle

1. **RED** - Write minimal failing test (one behavior, clear name)
   - Test should be clear about what it's testing
   - Use descriptive test names (e.g., `test_user_creation_requires_valid_email`)
   - Test exactly ONE behavior or edge case

2. **Verify RED** - Run test, confirm it fails for expected reason (MANDATORY)
   - Run the test and see it fail
   - This proves the test actually tests something
   - If it passes immediately, you're not testing the right thing

3. **GREEN** - Write minimal code to pass the test
   - Write the simplest code that makes the test pass
   - Don't implement more than the test requires
   - Focus on making THIS test pass only

4. **Verify GREEN** - Run test, confirm it passes (MANDATORY)
   - Verify the test now passes
   - Only then move to the next test

5. **REFACTOR** - Clean up while keeping tests green
   - Improve code structure without changing behavior
   - Run tests after each refactor
   - Keep all tests green

6. **Repeat** - Next failing test for next feature
   - Don't batch tests - one at a time
   - Follow the cycle for each test

### TDD Anti-Patterns to Prevent

| Anti-Pattern | Problem | Correct Approach |
|--------------|---------|-----------------|
| Writing code before tests | Tests written after code pass immediately | Write test FIRST, see it fail, then write code |
| Keeping "reference code" | Temptation to copy-paste | Delete reference code, write from test requirements |
| Tests that pass immediately | Proves nothing about implementation | Verify test fails BEFORE writing production code |
| Vague test names | Unclear what's being tested | Use descriptive names: `test_` + `expected_behavior` |
| Implementing multiple features | Violates single-responsibility | One test → minimal code → one feature |

### When No Test Framework Exists

If no test framework is detected:
1. Suggest creating a test setup (pytest, jest, etc.)
2. Create CHORE issue for test framework setup if needed
3. Don't proceed without testing capability

## Low-Confidence Baseline Check (MANDATORY)

**For `confidence: low` issues, baseline is MANDATORY before ANY implementation.**

### Pre-Implementation Baseline Gate

```
IF issue.confidence == 'low':
    IF NOT file_exists('.agent/ops/baseline.md'):
        ⛔ STOP — Cannot implement low-confidence issue without baseline
        ACTION: invoke ao-baseline to capture baseline FIRST
        DO NOT proceed until baseline exists
    
    IF baseline_age > 24_hours:
        ⚠️ WARN — Baseline may be stale for low-confidence work
        RECOMMEND: Refresh baseline before implementation
```

### Enforcement

This check runs BEFORE Step 1 of implementation:

1. Read active issue from focus.json
2. Check issue's `confidence:` field (default: check constitution if not set)
3. If `low`:
   - Check `.agent/ops/baseline.md` exists
   - If missing: STOP, invoke `ao-baseline`, then continue
   - If stale: WARN, offer to refresh

**Skipping this check for low-confidence work is FORBIDDEN.**

## Using Implementation Details

**Before starting implementation, check for implementation details:**

1. Look for `.agent/ops/issues/references/{ISSUE-ID}-impl-plan.md`
2. If exists, use it as the primary implementation guide:
   - Follow the detailed code snippets (extensive level)
   - Reference function signatures (normal level)
   - Use file list and approach (low level)
3. If not exists, proceed with plan only (but consider generating details first)

**During implementation, reference the details file for:**
- Exact function signatures to implement
- Edge cases to handle
- Error scenarios to cover
- Test cases to write

## Issue Tracking During Implementation

0) **Read existing lessons on this issue** (BEFORE starting):
   - Run `ao lesson ls ISSUE_ID` to load prior context
   - Prior lessons may contain critical insights from failed attempts, blocked work, or prior review findings
   - If lessons exist, factor them into your implementation approach

1) **Reference the issue** being worked on:
   - Update issue status to `in_progress`
   - Note in focus.json: "Implementing {ISSUE-ID}"

2) **Track deferred work**:
   - If you notice something that needs fixing but is out of scope:
   - Create a new issue, don't fix it now
   - Add to current issue's notes: "Related: {NEW-ISSUE-ID}"

3) **Capture lessons in the moment** (MANDATORY):
   - When you discover a pitfall, gotcha, or non-obvious behavior during implementation, **immediately** record it:
     ```bash
     ao lesson add ISSUE_ID "description of what was learned"
     ```
   - Don't wait for retrospective — capture while context is fresh
   - Examples of what to capture:
     - API quirks: `ao lesson add FEAT-0042@abc123 "msgspec.to_builtins() strips None fields by default"`
     - Build gotchas: `ao lesson add FEAT-0042@abc123 "Golden fixture needs updating when adding fields to Issue"`
     - Workarounds: `ao lesson add FEAT-0042@abc123 "Need type: ignore[union-attr] when calling .get() on Issue | dict"`
   - Don't overthink it — one-liner observations are fine, no duplicate detection needed

## Procedure

0) **TDD Pre-Check** (for FEAT issues):

    ```
    IF issue.type == 'FEAT':
        ⚠️ TDD IRON LAW ACTIVE
        NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
        ```

    **TDD Checklist** (must complete before any implementation):
    - [ ] Write failing test for first behavior
    - [ ] Run test - confirm it FAILS for expected reason (MANDATORY)
    - [ ] Write minimal code to make test pass
    - [ ] Run test - confirm it PASSES (MANDATORY)
    - [ ] Refactor if needed (keep tests green)
    - [ ] Repeat for next behavior

    **If test framework doesn't exist:**
    - Stop and suggest test framework setup
    - Create CHORE issue for test infrastructure

0) **Check for Preferences**:
    Check for `preferences.md` in this skill's directory.

    **Path**: `.ao/skills/ao-implementation/preferences.md`
   
   ```
   IF file_exists(PREFERENCES_PATH):
       Parse frontmatter:
       - test_frequency (per-step/per-file/batch) — when to run tests
       - commit_style (per-step/per-file/batch) — when to commit
       - validation_level (full/quick/skip-precommit) — validation depth
       - code_review_trigger (always/major-changes/never) — when to request review
       Log: "✓ Loaded implementation preferences"
   ELSE:
       Log: "No preferences found, using defaults"
       Proceed to Step 1
   ```

0.5) **Check for Linked Preview (MANDATORY)**:

   Before starting implementation, check if a plan-preview exists:
   
   ```
   preview_path = .agent/ops/issues/references/{ISSUE-ID}-preview.md
   
   IF file_exists(preview_path):
       Load validation snapshot from preview file
       Extract:
       - expected_files (list of files to change)
       - expected_components (list of components to add/modify)
       - security_sensitive_files (list requiring human review)
       - scope_estimates (line counts per file)
       
       Log: "✅ Preview found — validation will be enforced"
       Store preview_context for step-level validation
   ELSE:
       Log: "⚠️ No preview found — proceeding without preview validation"
       preview_context = None
   ```
   
   **If preview has linked VAL issue:**
   - Note the VAL issue ID for completion tracking
   - VAL issue must be marked done when implementation completes

1) Implement in small steps (reviewable diffs).
2) After each step:
   - run the smallest reliable test subset
   - update focus
   - **If preview exists: run incremental preview validation** (Step 2.5)
3) **Log file creations** (see File Audit Trail below)
4) If ambiguity appears:
   - stop and ask; do not guess
5) Avoid refactors:
   - if a refactor seems necessary, create an issue + ask permission before doing it.
6) End-of-implementation:
   - run full test suite (or constitution-defined test command)
   - **If preview exists: run full preview validation** (see Preview Validation Gate below)
   - prepare for critical review skill.

### Step 2.5: Incremental Preview Validation (after each implementation step)

**If preview_context is loaded, validate after EACH implementation step:**

```
function validate_step_against_preview(changed_files, preview_context):
    IF preview_context is None:
        RETURN  // No preview to validate against
    
    // Check for unexpected file changes
    for file in changed_files:
        IF file NOT IN preview_context.expected_files:
            ⚠️ FLAG: "File '{file}' changed but not in preview"
            ADD to discrepancy_log
    
    // Check for security-sensitive files
    for file in changed_files:
        IF file IN preview_context.security_sensitive_files:
            🚨 FLAG: "Security-sensitive file '{file}' modified — REQUIRES human review"
            ADD to security_review_required
    
    // Report incrementally
    IF discrepancy_log NOT EMPTY:
        WARN: "Incremental validation found {N} discrepancies:"
        - {list discrepancies}
        "These must be resolved before completion."
```

**Incremental validation output:**
```
🔍 Step {N} Preview Check:
- Files changed: {list}
- In preview: ✅ {count}
- Not in preview: ⚠️ {count} {list}
- Security-sensitive: {count} {list if any}
```

7) **Offer Preferences Creation** (if `preferences.md` doesn't exist):
   
   > "Would you like me to save your implementation preferences?"
   
   **If user says yes**, use `ao-interview` to ask:
   
   1. **Test Frequency**: "When should tests run during implementation?"
      Options: per-step | per-file | batch
      Default: per-step
   
   2. **Commit Style**: "How often do you prefer to commit?"
      Options: per-step | per-file | batch
      Default: per-file
   
   3. **Validation Level**: "How thorough should pre-commit validation be?"
      Options: full | quick | skip-precommit
      Default: full
   
   4. **Code Review Trigger**: "When should code review be requested?"
      Options: always | major-changes | never
      Default: major-changes
   
   **Save to** `.ao/skills/ao-implementation/preferences.md`

## Completion Gate (MANDATORY)

> **Canonical Reference**: See `.ao/references/completion-gate.md` for authoritative completion gate documentation.
> This section summarizes the key checks; the reference document is the source of truth.

**An issue CANNOT be marked `done` until ALL of these are verified:**

| Gate | Check | Action if Fails |
|------|-------|-----------------|
| Tests pass | Full test suite from constitution | Fix failures before proceeding |
| TDD verification (FEAT only) | Test failed THEN passed for each feature | Re-run TDD cycle for failed features |
| Lint passes | Lint command from constitution | Fix lint errors |
| Baseline comparison | No NEW regressions vs baseline | Fix regressions or create follow-up issues |
| Issue closed | Issue closed via ao (auto-archives to terminal status) | `ao issue close ISSUE_ID --log "Done"` |

### TDD Verification (for FEAT issues)

**For each feature implemented:**
- [ ] Test written FIRST and confirmed to FAIL
- [ ] Code written to make test pass
- [ ] Test confirmed to PASS
- [ ] Refactored if needed (tests stayed green)

**Commit Requirements (for FEAT issues):**
- Tests committed separately with `test:` prefix
- Example commit message: `test: add user authentication test`
- Feature code committed after tests pass

**Anti-Pattern Check:**
- [ ] No code written before tests
- [ ] No "reference code" kept during implementation
- [ ] No tests that passed immediately on first run
- [ ] No vague test names (test1, works, etc.)

### Low-Confidence Completion Gate (ADDITIONAL)

**For `confidence: low` issues, these ADDITIONAL checks are MANDATORY:**

| Gate | Check | Action if Fails |
|------|-------|-----------------|
| Baseline exists | `.agent/ops/baseline.md` exists | ⛔ CANNOT mark done without baseline |
| Baseline compared | Validation ran with baseline comparison | ⛔ Run Tier 2+ validation with comparison |
| Tier 2+ validation | Tier 1 (quick) not used alone | ⛔ Re-run with Tier 2+ validation |
| Human review | Hard stop checkpoint was presented | ⛔ Stop and wait for human approval |

**Attempting to mark a low-confidence issue as `done` without baseline comparison is EXPLICITLY FORBIDDEN.**

```
IF issue.confidence == 'low' AND status_change_to == 'done':
    IF NOT baseline_exists:
        ⛔ ERROR: Cannot close low-confidence issue without baseline
        ACTION: Run baseline capture, then Tier 2+ validation
    IF NOT baseline_comparison_ran:
        ⛔ ERROR: Low-confidence completion requires baseline comparison
        ACTION: Run ao-validation Tier 2+ with comparison
    IF NOT human_review_presented:
        ⛔ ERROR: Low-confidence requires human review hard stop
        ACTION: Present hard stop checkpoint, wait for approval
```

### Preview Validation Gate (if preview exists)

**If implementation has a linked preview, validate before marking complete:**

```
IF preview_context is NOT None:
    
    // 1. Get actual changes
    actual_files = get_git_diff_files_vs_baseline()
    actual_lines = count_lines_changed_per_file()
    
    // 2. Compare files
    extra_files = actual_files - preview_context.expected_files
    missing_files = preview_context.expected_files - actual_files
    
    // 3. Compare scope
    for file in actual_files:
        expected_lines = preview_context.scope_estimates[file]
        actual_lines = count_lines_changed(file)
        deviation = abs(actual_lines - expected_lines) / expected_lines
        
        IF deviation > 0.10:  // 10% strict threshold
            scope_violations.add((file, expected_lines, actual_lines))
    
    // 4. Check security-sensitive files
    security_files_touched = actual_files ∩ preview_context.security_sensitive_files
    
    // 5. Generate validation report
```

**Preview Validation Report:**

```markdown
📋 PREVIEW VALIDATION REPORT — {ISSUE-ID}

Preview: .agent/ops/issues/references/{issue_id}-preview.md
Validation Issue: VAL-{N}@{hash}

## File Comparison

| Category | Count | Files |
|----------|-------|-------|
| Expected & Changed | {N} | {list} |
| Extra (not in preview) | {N} | {list} |
| Missing (in preview, not changed) | {N} | {list} |

## Scope Comparison

| File | Expected | Actual | Deviation | Status |
|------|----------|--------|-----------|--------|
| {file} | {N} lines | {N} lines | {%} | {✅ OK / ⛔ EXCEEDS 10%} |

## Security Review

| File | Reason | Human Review |
|------|--------|-------------|
| {file} | {pattern/keyword} | {⬜ REQUIRED / ✅ APPROVED} |

## Resolution Required

{IF extra_files NOT EMPTY:}
⚠️ EXTRA FILES: The following files were changed but not in the approved preview:
{list files}

Options:
1. [A]pprove — these changes are acceptable
2. [R]evert — undo changes to these files
3. [U]pdate preview — add to preview (requires re-approval)

{IF missing_files NOT EMPTY:}
⚠️ MISSING CHANGES: The following planned changes were not implemented:
{list files}

Options:
1. [I]mplement — complete the missing changes
2. [R]emove from plan — update preview to exclude (requires re-approval)

{IF scope_violations NOT EMPTY:}
⛔ SCOPE EXCEEDED: The following files exceed the 10% deviation threshold:
{list files with expected/actual}

This BLOCKS completion. ALL discrepancies must be resolved.

{IF security_files_touched NOT EMPTY AND NOT all_approved:}
🚨 SECURITY REVIEW REQUIRED: Human must approve security-sensitive file changes.

---

⛔ VALIDATION STATUS: {PASS / BLOCKED}

{IF BLOCKED:}
Cannot mark issue as done until all discrepancies are resolved.
```

**Resolution Flow:**

1. Present validation report
2. For each discrepancy category:
   - Require explicit user action (approve/revert/update/implement)
   - Log each resolution decision
3. Only when ALL discrepancies resolved:
   - Mark VAL issue as done
   - Allow original issue to be marked done

### Gate Check Procedure

Before setting `status: done`:

1. **Run verification:**
    ```
    invoke ao-complete
    ```
    This executes the Gate Function: IDENTIFY → RUN → READ → VERIFY → ONLY THEN

2. **If verification FAILS:**
    - STOP — do not mark done
    - Fix issues, re-run verification

3. **If verification PASSES:**
    - Close issue: `ao issue close ISSUE_ID --log "Verified" --status done`
    - Update focus.json

### Archival on Completion

When closing an issue, `ao issue close` records `completed_at` and moves it to terminal status automatically. No manual archival to `history.md` is required.

If the issue size is large, add a final log note summarising the work done.

## File Audit Trail (MANDATORY)

**When creating or modifying files OUTSIDE `.agent/ops/`, log them for audit purposes.**

This enables `ao-selective-branch` to identify ao-created files when preparing clean PR branches.

### Enforcement (NON-OPTIONAL)

**The file audit trail is MANDATORY, not optional.**

1. **At session/iteration start**: Ensure `.agent/ops/log/` directory exists
2. **After EACH file create/modify/delete**: Append to log immediately
3. **Before marking issue done**: Verify log contains all changed files
4. **If log missing**: Create it before proceeding with implementation

**Failure to maintain the log breaks the selective-branch workflow and should be treated as a protocol violation.**

### Log Directory Setup

**At the start of implementation, ensure log directory exists:**

**PowerShell:**
```powershell
if (-not (Test-Path ".agent/ops/log")) { 
    New-Item -ItemType Directory -Path ".agent/ops/log" -Force 
}
```

**Bash:**
```bash
mkdir -p .agent/ops/log
```

### What to Log

- Files created in `src/`, `tests/`, `docs/`, etc.
- Configuration files added to project root
- Any file the user didn't explicitly create themselves
- **ALL modifications to existing files** (not just creates)

### What NOT to Log

- Files inside `.agent/ops/` (already excluded by convention)
- Files inside `.ao/skills/`, `.github/prompts/`, `.github/agents/` (already excluded)
- Temporary files that will be deleted

### Log Format

Append to `.agent/ops/log/created-files.log`:
```
{ISO-timestamp}|{action}|{relative-path}
```

Actions: `CREATE`, `MODIFY`, `DELETE`

**Use pipe `|` as delimiter** for easier parsing.

### Logging Commands

**PowerShell:**
```powershell
# Ensure log directory exists
if (-not (Test-Path ".agent/ops/log")) { New-Item -ItemType Directory -Path ".agent/ops/log" -Force }

# Log a file operation
$timestamp = (Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ")
Add-Content -Path ".agent/ops/log/created-files.log" -Value "$timestamp|CREATE|src/new-file.py"
```

**Bash:**
```bash
# Ensure log directory exists
mkdir -p .agent/ops/log

# Log a file operation
echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)|CREATE|src/new-file.py" >> .agent/ops/log/created-files.log
```

### When to Log

| Event | Action | Example |
|-------|--------|---------|
| `create_file` tool used | `CREATE` | `2026-01-27T10:15:32Z\|CREATE\|src/utils/helper.py` |
| `replace_string_in_file` on new code | `MODIFY` | `2026-01-27T10:16:45Z\|MODIFY\|src/existing.py` |
| File deleted via terminal | `DELETE` | `2026-01-27T10:17:00Z\|DELETE\|src/obsolete.py` |

### Example Flow

When implementing a feature that creates `src/utils/helper.py`:

1. Ensure `.agent/ops/log/` exists
2. Create the file
3. Log it: `2026-01-27T10:15:32Z|CREATE|src/utils/helper.py`
4. Continue with tests
5. If tests require modifying `src/utils/helper.py`, log: `...|MODIFY|src/utils/helper.py`

### Fallback: Generate from Git History

**If log is missing or incomplete, generate from git history before selective-branch:**

```bash
# Find branch point
base=$(git merge-base HEAD develop 2>/dev/null || git merge-base HEAD main)

# List files changed since branch point
git diff --name-status $base..HEAD | while read status file; do
    timestamp=$(git log -1 --format=%aI -- "$file")
    case "$status" in
        A) action="CREATE" ;;
        M) action="MODIFY" ;;
        D) action="DELETE" ;;
        *) action="MODIFY" ;;
    esac
    echo "$timestamp|$action|$file"
done > .agent/ops/log/created-files.log
```

This fallback is less accurate (uses commit time, not actual operation time) but enables selective-branch to work.

## Handling Unexpected Failures

**If tests fail unexpectedly during implementation, invoke `ao-debugging`:**

1. **Don't guess** — use systematic debugging process
2. **Isolate** — is this from your changes or pre-existing?
3. **Diagnose** — form hypothesis, test it
4. **Decide**:
   - If your change caused it → fix before continuing
   - If pre-existing → document, create issue, continue
   - If unclear → escalate to user

```
⚠️ Test failure during implementation step {N}.

Debugging analysis:
- Hypothesis: {what you think caused it}
- Evidence: {what you found}

Options:
1. Fix and continue (my change caused this)
2. Create issue and continue (pre-existing)
3. Need help investigating
```

## Issue Discovery After Implementation

**After implementation complete, invoke `ao-task` discovery procedure:**

1) **Collect follow-up items discovered during implementation:**
   - TODOs left in code → `CHORE` issues
   - Edge cases to handle later → `BUG` or `ENH` issues
   - Tests to add → `TEST` issues
   - Documentation needed → `DOCS` issues
   - Related improvements noticed → `ENH` or `REFAC` issues

2) **Present to user:**
   ```
   📋 Implementation complete for {ISSUE-ID}. Found {N} follow-up items:
   
   - [TEST] Add edge case tests for empty input
   - [DOCS] Document new API endpoint
   - [ENH] Consider caching for performance
   
   Create issues for these? [A]ll / [S]elect / [N]one
   ```

3) **Update original issue:**
   - Status: `done` (or `blocked` if follow-ups are required)
   - Log: "YYYY-MM-DD: Implementation complete, {N} follow-up issues created"

4) **After creating issues:**
   ```
   Created {N} follow-up issues. What's next?
   
   1. Run critical review on changes
   2. Start next priority issue
   3. Work on follow-up item ({ISSUE-ID})
   4. Mark original issue done and commit
   ```

## Low Confidence Hard Stop (MANDATORY)

**When confidence is LOW, implementation MUST stop after EACH issue for human review.**

This is non-negotiable. Low confidence means high uncertainty — human oversight is critical.

### Hard Stop Trigger

After completing implementation of a LOW confidence issue:

1. **DO NOT** proceed to next issue automatically
2. **DO NOT** batch multiple issues
3. **MUST** present hard stop checkpoint

### Hard Stop Checkpoint Template

```
🛑 LOW CONFIDENCE HARD STOP — Human Review Required

## Implementation Complete: {ISSUE-ID}

### Changes Made
- {file1}: {description of change}
- {file2}: {description of change}

### Tests Executed
- Test command: {command from constitution}
- Result: {PASS/FAIL} ({N} tests, {coverage}% coverage)
- New tests added: {count}

### Coverage Analysis
- Lines changed: {N}
- Lines covered by tests: {N} ({percentage}%)
- Branches covered: {N} ({percentage}%)

### Implementation Details Reference
- Spec file: {path to impl-plan.md}
- Adherence: {followed spec / deviated because...}

### Questions for Reviewer
1. {Any uncertainties encountered}
2. {Any assumptions made}

---

⏸️ WAITING FOR HUMAN APPROVAL

Please review the changes and respond:
- [A]pprove — continue to next issue or critical review
- [R]equest changes — specify what needs modification
- [D]iscuss — need clarification before deciding
```

### After Human Approval

Only after explicit human approval:

1. Update issue status to `done` (or `needs-changes` if requested)
2. Log the approval in issue notes
3. Proceed to critical review OR next issue (human's choice)

### Batch Size Enforcement

| Confidence | Issues per Iteration | Hard Stop |
|------------|---------------------|------------|
| LOW | 1 (hard limit) | After each issue |
| NORMAL | Up to 3 | Soft stop (ask, continue) |
| HIGH | Up to 5 | Minimal (report only) |

**For LOW confidence, batch size is ALWAYS 1.** The agent must not group issues.

## Multi-Issue Iteration Loop (with Hard Stops)

**When working on multiple issues in one session, use this iteration loop.**

### Pre-Iteration Validation

Before starting any iteration:

```
1. Read active issues from focus.json
2. Group by confidence level
3. Validate batch constraints:
   - LOW: max 1, HARD STOP required
   - NORMAL: max 3, soft stop recommended
   - HIGH: max 5, report only

4. Check for OVERRIDE-LOW:
   - If LOW issue selected AND autonomous mode requested:
   - Look for "OVERRIDE-LOW" in recent user messages
   - If present: proceed with single LOW issue, log override
   - If absent: SOFT BLOCK until user confirms
```

### Iteration Loop

```
FOR EACH issue IN selected_batch:
    
    // Pre-issue check
    IF issue.confidence == "low" AND NOT override_active:
        SOFT_BLOCK("Confirm LOW confidence issue")
        WAIT for user confirmation or OVERRIDE-LOW
    
    // Implementation phase
    EXECUTE implementation_steps(issue)
    
    // Post-implementation validation
    RUN validation_tier_by_confidence(issue.confidence)
    
    // Hard stop decision
    IF issue.confidence == "low":
        HARD_STOP:
            Present hard stop checkpoint (see template above)
            WAIT for human approval: [A]pprove / [R]equest changes / [D]iscuss
            
            IF approval == "R":
                DO NOT proceed to next issue
                User must specify changes needed
            ELIF approval == "D":
                PAUSE iteration for discussion
            ELIF approval == "A":
                Log approval in issue
                IF OVERRIDE-LOW was active:
                    RESET override (does not carry to next issue)
                CONTINUE to next issue
    
    ELIF issue.confidence == "normal":
        SOFT_STOP:
            Present completion summary
            ASK: "Continue to next issue? [Y]es / [N]o / [R]eview first"
            IF "N" or "R": PAUSE iteration
    
    ELIF issue.confidence == "high":
        REPORT only:
            Log completion
            CONTINUE to next issue automatically

END FOR
```

### Hard Stop Enforcement (MANDATORY)

**Hard stops are ACTUAL BLOCKS, not advisory messages.**

When a hard stop is triggered:

1. **Agent MUST stop all automated work**
2. **Agent MUST NOT proceed to next issue**
3. **Agent MUST present the hard stop checkpoint**
4. **Agent MUST wait for explicit human response**

**Violation handling:**

If agent detects it bypassed a hard stop:
```
⚠️ PROTOCOL VIOLATION DETECTED

A hard stop was required but not executed.

Issue: {ISSUE-ID}
Confidence: LOW
Required: Human review hard stop
Actual: {what happened}

REVERTING to last checkpoint.

Please review and approve before continuing.
```

### Override Expiration

**OVERRIDE-LOW expires after the issue it was applied to:**

| Event | Override Status |
|-------|-----------------|
| User provides "OVERRIDE-LOW" | Active for next LOW issue only |
| LOW issue marked done | Override EXPIRES |
| LOW issue marked blocked | Override EXPIRES |
| Session ends | Override EXPIRES |
| Next LOW issue starts | Must re-confirm |

**The override is SCOPED, not GLOBAL.**

## Preferences Update Trigger

**When user mentions "preferences" for this skill:**

| Trigger Phrases | Action |
|-----------------|--------|
| "Update my implementation preferences" | Open interview to update all preference fields |
| "What are my implementation preferences?" | Display current preferences |
| "Reset implementation preferences" | Delete `preferences.md` (with confirmation) |
| "preferences" (during implementation) | Show current preferences being used |

**Display Format:**
```
📋 Current Implementation Preferences:

- Test Frequency: {value}
- Commit Style: {value}
- Validation Level: {value}
- Code Review Trigger: {value}

Would you like to update any of these? [Y]es / [N]o
```
