---
title: Planning Workflow
read_when:
  - "using .impl/ folders"
  - "understanding plan file structure"
  - "implementing plans"
---

# Planning Workflow

This guide explains the `.impl/` folder protocol used in erk for managing implementation plans.

## Overview

Erk uses `.impl/` folders to track implementation progress for plans executed locally by agents.

## .impl/ Folders

**Purpose**: Track implementation progress for plans executed locally.

**Characteristics**:

- NOT tracked in git (in `.gitignore`)
- Created by planning commands
- Contains `plan.md`, `progress.md`, and optional `issue.json`
- Never committed to repository

### Location

The `.impl/` folder lives at the **worktree root**:

```
{worktree_root}/.impl/
```

**Path Resolution**:

```python
impl_dir = repo_root / ".impl"
```

**Structure**:

```
.impl/
├── plan.md         # Immutable implementation plan
├── progress.md     # Mutable progress tracking (checkboxes)
└── issue.json      # Optional GitHub issue reference
```

## Local Implementation Workflow

### 1. Create a Plan

Create a plan using Claude's ExitPlanMode tool. This stores the plan in session logs.

### 2. Choose Your Workflow

When exiting plan mode, you have five options:

#### Option A: Save for Later ("Save the plan")

Save the plan to GitHub without implementing:

```bash
/erk:plan-save
```

This command saves the plan from the current session as a GitHub issue with the `erk-plan` label. The issue becomes the source of truth. Use this when you want to:

- Defer implementation to a remote worker
- Review the plan before committing to implementation
- Hand off to someone else

#### Option B: Save and Implement ("Implement")

Save to GitHub AND immediately implement in the current worktree:

```bash
/erk:plan-implement
```

This command:

1. Saves the plan to GitHub as an issue
2. Creates a feature branch (stacked if on feature branch, otherwise from trunk)
3. Sets up `.impl/` folder with plan content
4. Executes the implementation phases
5. Runs CI and creates a PR

Use this for the typical flow where you plan and implement in one session.

#### Option C: Incremental Changes ("Incremental implementation")

For small PR iterations that don't need issue tracking:

- Skip saving to GitHub
- Implement changes directly in the current worktree
- Best for minor fixes or follow-up changes to existing PRs

#### Option D: View/Edit ("View or edit the plan")

For reviewing or refining the plan:

- Review the plan content in the session
- Make adjustments to the plan if needed
- Loop back to choose another option
- Best when you need to refine before committing to save or implement

#### Option E: Save and Submit for Review ("Save and submit for review")

Save the plan to GitHub and create a PR-based review workflow:

```bash
# Step 1: Save the plan to GitHub
/erk:plan-save

# Step 2: Read the plan-saved-issue marker to get issue number
# (Claude reads marker file automatically)

# Step 3: Create a review PR for the plan
/erk:plan-review <issue-number>

# Step 4: STOP - stay in plan mode
```

This workflow:

1. Saves the plan to GitHub as an issue with `erk-plan` label
2. Creates a GitHub marker (`plan-saved-issue`) with the issue number
3. Creates a review PR with the plan content for feedback
4. Labels the PR with `erk-plan-review` for special handling
5. Stays in plan mode for further refinement

Use this when you want:

- Collaborative review of the plan before implementation
- Feedback from team members on the approach
- Version-controlled plan iteration via PR comments
- Formal approval process before starting work

See [PR-Based Plan Review Workflow](pr-review-workflow.md) for complete details.

### 3. Implement from Existing Issue (Alternative)

If you have an issue number from a previously saved plan:

```bash
erk implement <issue-number>
```

This command:

- Sets up the `.impl/` folder in the current directory with plan content from the issue
- Links to the GitHub issue for progress tracking

## Plan Save Workflow

When a user saves their plan to GitHub (via `/erk:plan-save`), the workflow should end cleanly without additional prompts.

### Flow Diagram

```
┌─────────────────────┐
│  Plan Mode          │
│  (plan created)     │
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│ Exit Plan Mode Hook │
│ "What would you     │
│ like to do?"        │
└─────────┬───────────┘
          │
    ┌─────┼─────┬─────────────┬─────────────┐
    │     │     │             │             │
    ▼     ▼     ▼             ▼             ▼
┌───────┐ ┌─────────┐ ┌──────────────┐ ┌──────────┐ ┌─────────────┐
│ Save  │ │Implement│ │ Incremental  │ │View/Edit │ │Save & Review│
│ (A)   │ │ (B)     │ │ (C)          │ │ (D)      │ │    (E)      │
└───┬───┘ └────┬────┘ └──────┬───────┘ └────┬─────┘ └──────┬──────┘
    │          │             │              │              │
    ▼          ▼             ▼              │              ▼
┌───────┐ ┌─────────────┐ ┌──────────────┐  │      ┌──────────────┐
│GitHub │ │Save + Setup │ │Create marker │  │      │Save to GitHub│
│issue  │ │+ Implement  │ │Exit plan mode│  │      │Create review │
│created│ │+ CI + PR    │ │Impl directly │  │      │PR for plan   │
└───┬───┘ └─────────────┘ └──────────────┘  │      └──────┬───────┘
    │                                       │              │
    ▼                                       │              ▼
┌───────┐                                   │      ┌──────────────┐
│ STOP  │  ← Do NOT call ExitPlanMode       │      │    STOP      │
│(plan  │                          ┌────────┘      │  (plan mode) │
│mode)  │                          │ (loop back)   └──────────────┘
└───────┘                          ▼
```

### Key Principle: Don't Call ExitPlanMode After Saving

After saving to GitHub:

1. The marker file `exit-plan-mode-hook.plan-saved.marker` is created
2. Success message is displayed with next steps
3. **Session stays in plan mode** - no ExitPlanMode call

Why? ExitPlanMode shows a plan approval dialog. After saving, this dialog:

- Serves no purpose (plan is already saved)
- Requires unnecessary user interaction
- Confuses the workflow

### Safety Net: Hook Blocks ExitPlanMode

If ExitPlanMode is called anyway (e.g., by mistake), the `exit-plan-mode-hook` detects the plan-saved marker and blocks with exit 2:

```python
if plan_saved_marker.exists():
    plan_saved_marker.unlink()
    click.echo("✅ Plan saved to GitHub. Session complete.")
    sys.exit(2)  # Block to prevent plan approval dialog
```

This ensures the plan dialog never appears after a successful save.

## Progress Tracking

The `.impl/progress.md` file tracks completion status:

```markdown
---
completed_steps: 3
total_steps: 5
---

# Progress Tracking

- [x] 1. First step (completed)
- [x] 2. Second step (completed)
- [x] 3. Third step (completed)
- [ ] 4. Fourth step
- [ ] 5. Fifth step
```

The front matter enables progress indicators in `erk status` output.

## 🔴 Line Number References Are DISALLOWED in Implementation Plans

Line numbers drift as code changes, causing implementation failures. Use durable alternatives instead.

### The Rule

- 🔴 **DISALLOWED**: Line number references in implementation steps
- ✅ **REQUIRED**: Use function names, behavioral descriptions, or structural anchors
- **Why**: Line numbers become stale as code evolves, leading to confusion and incorrect implementations

### Allowed Alternatives

Use these durable reference patterns instead of line numbers:

- ✅ **Function/class names**: `Update validate_user() in src/auth.py`
- ✅ **Behavioral descriptions**: `Add null check before processing payment`
- ✅ **File paths + context**: `In the payment loop in src/billing.py, add retry logic`
- ✅ **Contextual anchors**: `At the start of process_order(), add validation`
- ✅ **Structural references**: `In the User class constructor, initialize permissions`

### Exception: Historical Context Only

Line numbers ARE allowed in "Context & Understanding" or "Planning Artifacts" sections when documenting historical research:

- Must include commit hash: `Examined auth.py lines 45-67 (commit: abc123)`
- These are historical records, not implementation instructions
- Provides breadcrumb trail for understanding research process

### Examples

**❌ WRONG - Fragile line number references:**

```markdown
1. Modify lines 120-135 in billing.py to add retry logic
2. Update line 89 in auth.py with new validation
3. Change lines 200-215 in api.py to handle errors
```

**✅ RIGHT - Durable behavioral references:**

```markdown
1. Update calculate_total() in src/billing.py to include retry logic
2. Add null check to validate_user() in src/auth.py before database query
3. Modify process_request() in src/api.py to handle timeout errors gracefully
```

**✅ ALLOWED - Historical context with commit hash:**

```markdown
## Context & Understanding

### Planning Artifacts

During planning, examined the authentication flow:

- Reviewed auth.py lines 45-67 (commit: a1b2c3d) - shows current EAFP pattern
- Checked validation.py lines 12-25 (commit: a1b2c3d) - demonstrates LBYL approach
```

## Important Notes

- **Never commit `.impl/` folders** - They're in `.gitignore` for a reason
- **Safe to delete after implementation** - Once the work is committed, `.impl/` can be removed
- **One plan per worktree** - Each worktree has its own `.impl/` folder

## Remote Implementation via GitHub Actions

### How Changes Are Detected

The workflow uses a **dual-check** approach to detect implementation changes:

1. **Pre-implementation**: Captures `git rev-parse HEAD` before the agent runs
2. **Post-implementation**: Checks both uncommitted changes AND new commits
3. **Result**: Changes exist if either channel has changes

This dual-check prevents false negatives when agents commit their work without leaving uncommitted changes. See [erk-impl Change Detection](../ci/erk-impl-change-detection.md) for details.

### Submitting for Remote Implementation

For automated implementation via GitHub Actions, use `erk plan submit`:

```bash
erk plan submit <issue-number>
```

This command:

- Validates the issue has the `erk-plan` label
- Verifies the issue is OPEN (not closed)
- Triggers the `dispatch-erk-queue.yml` GitHub Actions workflow via direct workflow dispatch
- Displays the workflow run URL

The GitHub Actions workflow will:

1. Create a dedicated branch from trunk
2. Set up the `.worker-impl/` folder with the plan from the issue
3. Create a draft PR
4. Execute the implementation automatically
5. Mark the PR as ready for review

**Monitor workflow progress:**

```bash
# List workflow runs
gh run list --workflow=dispatch-erk-queue.yml

# Watch latest run
gh run watch
```

## Commands Reference

### Plan Creation and Saving

- `/erk:plan-save` - Save the current session's plan to GitHub as an issue (no implementation)

### Implementation

- `/erk:plan-implement` - Save plan to GitHub AND implement (full workflow: save → setup → implement → CI → PR)
- `erk implement <issue>` - Implement plan from existing GitHub issue in current directory
