---
name: ao-planning
description: "Produce a thorough plan before implementation. Use for planning tasks: clarify unknowns, create plan iterations based on confidence level, validate each, then finalize."
category: core
invokes: [ao-state, ao-interview, ao-task, ao-impl-details, ao-usage]
invoked_by: []
state_files:
  read: [constitution.md, baseline.md, memory.md, focus.json, issues/active.jsonl]
  write: [focus.json, issues/events.jsonl, issues/references/*]
references: [.ao/references/confidence.md]
---

# Planning workflow

> **Confidence Reference**: This skill uses canonical confidence definitions from [.ao/references/confidence.md](.ao/references/confidence.md). Iteration counts, validation depth, and implementation detail levels are determined by confidence level.

**Uses `ao` CLI for all issue operations.** See `ao-usage` skill for full command reference.

## Issue Tracking via ao CLI

| Operation | Command |
|-----------|--------|
| Create planning issue | pipe `{"type":"PLAN","title":"...","priority":"backlog"}` to `ao issue add --in -` |
| Update status | `ao issue patch ISSUE_ID --in - <<<'{"set":{"status":"in_progress"}}'` |
| Add log entry | `ao log add ISSUE_ID "Plan iteration 2 complete"` |
| Show issue | `ao issue show ISSUE_ID` |

### Build Commands (from constitution)

```bash
# Read actual commands from .agent/ops/constitution.md to understand project structure, examples:
build: uv run python -m build
test: uv run pytest
```

### Reference Documents

Implementation details are stored as markdown:
```
.agent/ops/issues/references/{ISSUE-ID}-impl-plan.md
```


## Preconditions
- Work should be tracked as an issue before planning begins
- Constitution exists and is baseline-ready (or stop and run constitution workflow)
- Baseline exists if any code change is expected (or stop and run baseline workflow first)

## <HARD-GATE> No Implementation Before Plan Approval

**Do NOT invoke ao-implementation or write ANY code until the plan is approved by the user.**

This gate cannot be skipped regardless of confidence level:
- HIGH confidence: plan may be abbreviated but MUST be presented and approved
- NORMAL confidence: plan must have ≥2 iterations and be approved
- LOW confidence: plan must be explicit, validated section-by-section, and approved

Violation of this gate is a **protocol failure**. If you find yourself writing production code during planning, STOP immediately and return to the planning process.

## Issue-First Principle

## Brainstorming Process (NEW - Enhanced Workflow)

### 1) Check Project State First (MANDATORY)

**Before planning begins, examine current project state:**

```
Check:
  - Current project files and structure
  - Existing documentation (README, docs/)
  - Recent commits and changes
  - Related issues or previous plans
  - Codebase architecture and patterns
  - Lessons from this issue and related issues (see step 1.5)

Purpose:
  - Understand existing solutions
  - Identify patterns used in codebase
  - Avoid proposing solutions that already exist
  - Leverage existing architecture
  - Learn from prior attempts and pitfalls
```

### 1.5) Read Lessons from Prior Work (MANDATORY)

**Before planning, check for existing lessons on this issue and related issues:**

```bash
# Check lessons on the current issue (may have lessons from prior attempts)
ao lesson ls ISSUE_ID

# Check lessons on issues in the same epic (shared context)
ao ls --epic EPIC_NAME --format json  # find related issues
ao lesson ls RELATED_ISSUE_ID         # read their lessons
```

**Why this matters:**
- Issues that were previously blocked or had failed attempts carry lessons
- Same-epic issues often share pitfalls (e.g., "msgspec field ordering matters")
- Reading lessons prevents re-discovering the same gotchas

**What to do with lessons found:**
- Factor them into the plan as known constraints or risks
- Note them in the plan: "Prior lesson from ISSUE_ID: ..."
- If a lesson contradicts the planned approach, reconsider

### 2) Intake and Refine

```
Restate goal (1-3 lines):
  - What are we trying to solve?
  - Why does this matter?

List unknowns as explicit questions:
  - Don't assume answers
  - List what needs clarification
  - Stop and ask until clear

Scope boundaries:
  - What's explicitly OUT OF SCOPE for this issue?
  - What must NOT be changed?

  (List anything I should NOT touch or change)
```

### 3) Present Plan in Sections (NEW - Enhanced Structure)

```
Break plan into 200-300 word sections:
  Section 1: {Architecture / Data Flow / Components}
    [200-300 words]
    Ask: Does this look right? (yes/no/revise)

  Section 2: {Next area}
    [200-300 words]
    Ask: Does this look right? (yes/no/revise)

  ... (continue sections as needed)

Validation after each section:
  - "Does this section look correct so far?"
  - Be ready to go back and revise
  - Don't proceed until current section is validated
```

### 4) Explore 2-3 Approaches (NEW - Alternatives Analysis)

```
Don't just create 2 iterations of the same approach.
Instead, present 2-3 genuinely different architectural approaches:

  Approach 1: {Description}
    Pros: {list advantages}
    Cons: {list disadvantages}

  Approach 2: {Different approach}
    Pros: {list advantages}
    Cons: {list disadvantages}

  Approach 3: {Another approach - optional}
    Pros: {list advantages}
    Cons: {list disadvantages}

Lead with recommendation and explain why:
  - "I recommend Approach {N} because..."
  - Include specific trade-offs considered
  - Let user choose before detailed plan
```

### 5) YAGNI Enforcement (MANDATORY - Ruthless Feature Pruning)

**YAGNI = "You Aren't Gonna Need It"**

Before finalizing ANY plan, you MUST apply the YAGNI checklist:

#### YAGNI Checklist (MANDATORY)

For EVERY proposed feature, requirement, or design element:

- [ ] Immediate need: Is this needed for the current requirement?
- [ ] Real problem: Does this solve a real problem or a hypothetical one?
- [ ] Addable later: Can this be added later without major refactoring?
- [ ] Simplest solution: What's the simplest thing that could work?

**If ANY checkbox cannot be verified, REMOVE the feature.**

#### YAGNI Questions to Ask

For every feature being considered:

1. "Do we need this for the current requirement?"
   - If NO → Remove it

2. "Is this solving a real problem or a hypothetical one?"
   - If hypothetical → Remove it

3. "Can this be added later without refactoring?"
   - If YES → Defer it

4. "What's the simplest thing that could work?"
   - Implement that instead

#### YAGNI Anti-Patterns (DO NOT DO)

**Don't:**
- Add plugin system when you have one use case
- Create abstraction layers for single implementation
- Add configuration options that aren't needed
- Build for scale you don't have
- Add "flexibility" for uncertain future needs
- Implement "hooks" or "extensions" for no current use

**Do:**
- Hardcode until you have 3+ variations
- Duplicate code until pattern emerges
- Add complexity only when pain is felt
- Design for current requirements, not hypothetical ones

#### YAGNI in Practice

**Example 1: Configuration**
```
Don't: "Let's make this configurable so we can change it later"
Do: Hardcode the value. When you need to change it 3+ times, THEN make it configurable.
```

**Example 2: Abstraction**
```
Don't: "Let's create an interface in case we need another implementation"
Do: Implement the concrete class. When you need a second implementation, THEN extract the interface.
```

**Example 3: Features**
```
Don't: "Users might want to export to CSV, PDF, and Excel someday"
Do: Implement CSV export. When users ask for PDF, THEN add it.
```

#### Integration into Planning Workflow

**During Plan Iteration 1:**
- Present initial plan with all proposed features

**During Validation:**
- Run YAGNI checklist on each feature
- Remove features that fail any check
- Revise plan without those features

**During Plan Iteration 2:**
- Present revised plan with YAGNI-applied scope
- Explicitly list what was removed and why

**Final Approval:**
- Confirm user accepts YAGNI-reduced scope
- Document deferred features for future issues if needed

### 6) Incremental Validation (NEW - Validate After Each Section)

```
After presenting each section:
  - Ask: "Does this section look right so far?"
  - Be ready to revise previous sections if needed
  - Don't proceed until current section is validated

Benefits:
  - Early course correction
  - Reduced rework
  - Continuous feedback loop
  - Flexibility to pivot
```

### 7) Document Flexibility (NEW - Revision Capability)

```
Document in plan:
  - "You can ask me to revise any previous section"
  - "No section is final until full plan is reviewed"
  - "I can modify any section if you discover issues later"

This encourages:
  - Don't get locked into a path
  - Iterate based on feedback
  - Change approach if better solution emerges
```

---

Before starting detailed planning:

1. **Check for existing issue**: Is there already an issue for this work?
   - Yes → proceed with planning, reference the issue ID
   - No → suggest creating one first

2. **Create issue if needed**:
   ```
   This work isn't tracked yet. Create an issue first?
   
   Suggested: FEAT-{next}@{hash} — "{title from request}"
   Priority: {inferred priority}
   
   [Y]es, create and continue / [N]o, plan without issue
   ```

3. **Reference issue throughout**:
   - Plan title: "Plan for {ISSUE-ID}: {title}"
   - Update issue status to `in_progress` when planning starts
   - Link plan to issue in notes section

## Iterations based on confidence

| Confidence | Minimum iterations | Validation depth | Implementation Details Level |
|------------|-------------------|------------------|------------------------------|
| low | 3+ | exhaustive — question everything | **extensive** — full code snippets, edge cases, test scenarios |
| normal | 2 | standard — validate key assumptions | **normal** — pseudo-code, signatures, data flow |
| high | 1 (or skip) | quick — trust established patterns | **low** — bullet points, files, approach |

Read confidence from:
1. Task's `confidence` field (if set)
2. Otherwise, constitution's default confidence

## Low Confidence Mandatory Interview (invoke `ao-interview`)

**When confidence is LOW, an interview is MANDATORY before planning begins.**

This ensures assumptions are surfaced and clarified with the human before any design work.

### Interview Trigger

```
🎯 LOW CONFIDENCE DETECTED — Mandatory Interview Required

Before planning {ISSUE-ID}, I need to clarify key aspects with you.
This is required for low confidence work to reduce implementation risk.

Starting structured interview (one question at a time)...
```

### Interview Questions Template

Ask these questions ONE AT A TIME, waiting for response before proceeding:

1. **Scope Boundaries**
   ```
   Q1: What is explicitly OUT OF SCOPE for this issue?
   (List anything I should NOT touch or change)
   ```

2. **Expected Behavior**
   ```
   Q2: Can you describe the expected behavior in specific terms?
   (What should happen when X? What output for input Y?)
   ```

3. **Edge Cases**
   ```
   Q3: What edge cases should I consider?
   (Empty inputs, errors, concurrent access, etc.)
   ```

4. **Testing Expectations**
   ```
   Q4: What testing approach do you expect?
   (Unit tests? Integration? Manual verification? Specific scenarios?)
   ```

5. **Success Criteria**
   ```
   Q5: How will you know this is done correctly?
   (What will you check during code review?)
   ```

6. **Known Constraints**
   ```
   Q6: Are there any constraints I should know about?
   (Performance requirements, compatibility, dependencies, etc.)
   ```

### Interview Notes Capture

After interview completes:

1. Summarize answers in issue notes section
2. Create `.agent/ops/issues/references/{ISSUE-ID}-interview.md` if answers are extensive
3. Link interview notes from issue's `spec_file` or `notes` field

```markdown
### Interview Summary (YYYY-MM-DD)
- **Out of scope**: {answer}
- **Expected behavior**: {answer}
- **Edge cases**: {answer}
- **Testing**: {answer}
- **Success criteria**: {answer}
- **Constraints**: {answer}
```

### Interview Bypass (NOT RECOMMENDED)

User may skip interview, but must acknowledge the risk:

```
⚠️ Skipping interview for low confidence issue is NOT recommended.
This increases risk of incorrect implementation.

Skip anyway? [Y]es, I accept the risk / [N]o, let's do the interview
```

If skipped, log in issue: "Interview skipped by user — higher risk accepted"

## Preconditions
- Constitution exists and is baseline-ready (or stop and run constitution workflow).
- Baseline exists if any code change is expected (or stop and run baseline workflow first).

## Procedure

0) **Check for Preferences**:
   Check for `preferences.md` in this skill's directory.
   
   **Path**: `.ao/skills/ao-planning/preferences.md`
   
   ```
   IF file_exists(PREFERENCES_PATH):
       Parse frontmatter:
       - confidence_level (low/normal/high) — default confidence setting
       - min_iterations (1-5) — minimum plan iterations
       - include_risks (yes/no) — whether to analyze risks
       - include_alternatives (yes/no) — whether to explore alternatives
       - require_issue (yes/no) — enforce issue-first principle
       Log: "✓ Loaded planning preferences"
   ELSE:
       Log: "No preferences found, using defaults"
       Proceed to Step 1
   ```

1) Intake:
   - restate the goal (1–3 lines)
   - list unknowns as explicit questions
   - stop and ask until clarified; no guessing

2) Plan iteration 1:
   - steps
   - files expected to change
   - files that must not change
   - test strategy
   - risks/unknowns
   - why it is minimal change

3) Validate iteration 1:
   - check every requirement
   - check constitution constraints
   - check baseline constraints
   - identify assumptions; convert assumptions into questions

4) Plan iteration 2+ (if confidence requires):
   - revise based on validation
   - tighten diffs and test plan

5) **Generate Implementation Details** (invoke `ao-impl-details`):
   - Determine detail level from confidence (see table above)
   - Generate detailed implementation specification
   - Save to `.agent/ops/issues/references/{ISSUE-ID}-impl-plan.md`
   - Link from issue's `spec_file` field

6) Final implementation plan:
   - numbered steps
   - acceptance criteria mapping
   - test plan mapping
   - **reference to implementation details file**

7) Approval gate (based on confidence):
   - low: HARD gate — wait for explicit approval, plan for single issue only
   - normal: SOFT gate — ask "Ready to implement?", continue if no objection
   - high: MINIMAL — proceed unless user objects

   **LOW confidence additional requirements:**
   - Plan must cover exactly 1 issue (no batching)
   - Reference document in `.agent/ops/issues/references/` is MANDATORY
   - Implementation will have HARD STOP after completion for human review
   - Test coverage threshold: ≥90% line, ≥85% branch on changed code

8) Update `.agent/ops/focus.json` and issue status via `ao-state`.

9) **Offer Preferences Creation** (if `preferences.md` doesn't exist):
   
   > "Would you like me to save your planning preferences? This will remember your choices for future plans."
   
   **If user says yes**, use `ao-interview` to ask:
   
   1. **Confidence Level**: "What default confidence level do you prefer?"
      Options: low | normal | high
      Default: normal
   
   2. **Minimum Iterations**: "How many plan iterations do you want at minimum?"
      Options: 1 | 2 | 3 | 4 | 5
      Default: 2
   
   3. **Risk Analysis**: "Should plans always include risk analysis?"
      Options: yes | no
      Default: yes
   
   4. **Alternative Approaches**: "Should plans explore alternative approaches?"
      Options: yes | no
      Default: yes
   
   5. **Issue Requirement**: "Should planning require an existing issue?"
      Options: yes | no
      Default: yes
   
   **Save to** `.ao/skills/ao-planning/preferences.md`:
   ```markdown
   ---
   confidence_level: {answer}
   min_iterations: {answer}
   include_risks: {answer}
   include_alternatives: {answer}
   require_issue: {answer}
   ---
   
   # Planning Preferences
   
   ## Summary
   These preferences customize how the planning skill operates.
   
   ## Settings
   - **Confidence Level**: {explanation}
   - **Minimum Iterations**: {explanation}
   - **Risk Analysis**: {explanation}
   - **Alternative Approaches**: {explanation}
   - **Issue Requirement**: {explanation}
   
   ---
   *Update these preferences anytime by asking "Update my preferences for planning"*
   ```

## Implementation Details Integration

**MANDATORY: After plan iterations are complete, you MUST generate implementation details.**

This is not optional. Every plan must have an implementation details file.

### Low Confidence → Extensive Details

For risky, complex, or uncertain changes:

```
Invoking ao-impl-details with level: extensive

Output MUST include:
- ACTUAL EXECUTABLE CODE for each change (not pseudo-code)
- Complete function implementations with types
- Edge case handling with specific code
- Error scenarios with specific exception handling
- Full test cases with assertions
- Import statements
- Docstrings
```

**Example extensive output:**
```python
# File: src/services/user.py
# Change: Add process_user function

from datetime import datetime
from typing import Optional
from .models import User, UserResult
from .exceptions import NotFoundError

def process_user(user_id: str, db: Database) -> UserResult:
    """Process user with validation.
    
    Args:
        user_id: The user's unique identifier
        db: Database connection
        
    Returns:
        UserResult with processed user data
        
    Raises:
        ValueError: If user_id is invalid
        NotFoundError: If user doesn't exist
    """
    if not user_id:
        raise ValueError("user_id is required")
    
    user = db.get_user(user_id)
    if user is None:
        raise NotFoundError(f"User {user_id} not found")
    
    return UserResult(
        id=user.id,
        name=user.name,
        processed_at=datetime.utcnow(),
    )
```

### Normal Confidence → Normal Details

For standard features and typical changes:

```
Invoking ao-impl-details with level: normal

Output includes:
- Function signatures with parameter types
- Pseudo-code for logic flow
- Data structure definitions
- API contracts (request/response)
- Key test scenarios (not full code)
```

### High Confidence → Low Details

For simple, well-understood changes:

```
Invoking ao-impl-details with level: low

Output includes:
- Files to change with brief description
- High-level approach (1-2 sentences per file)
- Dependencies and risks
- Basic test coverage outline
```

### Detail Level Override

User can override the default level:

```
Plan with extensive details regardless of confidence? [y/n]
```

Or specify in the planning request: "Plan with extensive implementation details"

## Issue Discovery During Planning

**During planning, invoke `ao-task` discovery procedure for:**

1) **Sub-tasks discovered**:
   - Large feature breaks into multiple issues
   - Prerequisites that need addressing first
   - "Before we can do X, we need to Y"

2) **Risks identified**:
   - Technical risks → `CHORE` or `TEST` issues
   - Security concerns → `SEC` issues
   - Performance concerns → `PERF` issues

3) **Dependencies found**:
   - External blockers → blocked issues
   - Missing APIs/features → `FEAT` issues

**Present after plan iteration:**
```
📋 Planning revealed {N} additional work items:

- [FEAT] API endpoint for user preferences (prerequisite)
- [TEST] Integration tests needed for payment flow
- [DOCS] Update API documentation for new fields

Create issues for these? [A]ll / [S]elect / [N]one

These will be linked as dependencies/related to {ORIGINAL-ISSUE-ID}.
```

**After creating sub-issues:**
```
Created {N} related issues. What's next?

1. Continue planning {ORIGINAL-ISSUE-ID} (with dependencies noted)
2. Plan the prerequisite first ({NEW-ISSUE-ID})
3. Review all related issues
```

## Preferences Update Trigger

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

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

**Update Workflow:**

1. Read current `preferences.md` (if exists)
2. Show current values with option to change each
3. For each field user wants to change, ask new value
4. Save updated `preferences.md`
5. Confirm changes saved

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

- Confidence Level: {value}
- Minimum Iterations: {value}
- Risk Analysis: {value}
- Alternative Approaches: {value}
- Issue Requirement: {value}

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