---
name: map
description: "Massive Action Plan — iterative plan-critique workflow for complex features. Explores the codebase, drafts a plan, gets agent critique until approved, compares against FOSS reference implementations, gets expert-persona critique, then produces phase implementation docs."
argument-hint: "[feature description]"
disable-model-invocation: true
effort: max
---

# MAP — Massive Action Plan

You are executing a rigorous, multi-round plan-critique workflow for a complex
feature. The goal is a battle-tested implementation plan with per-phase docs
ready for execution by subagents.

## Adaptability

The templates, section structures, and goon.yaml schema below are **guidance,
not rigid rules**. Every project is different. When you discover that a project
doesn't fit the templates — different language, no GitHub, no milestones,
monorepo, unusual test setup, whatever — **propose how you'll adapt** rather
than forcing the template or silently skipping sections. For example:

> "This project doesn't use GitHub milestones — I'll track priorities by
> label instead. Sound right?"

> "There's no Cargo workspace here, just a single crate. I'll drop the
> workspace/architecture sections from goon.yaml and simplify."

> "The test suite takes 10 minutes, so I'll split the checklist into `quick`
> (unit tests only) and `verify` (full integration). Make sense?"

The goal is a config and handoff that actually match the project, not one that
matches a template.

## Usage

If `$ARGUMENTS` is empty, "help", or "?", show this and stop:

```
/map [feature description]

Plan a complex feature with multi-round critique and FOSS comparison.
Produces MAP_PLAN.md, per-phase implementation docs, goon.yaml, and
an initial session handoff.

Examples:
  /map hidden classes and inline caches for property access
  /map add WebSocket support to the HTTP server
  /map refactor the document model to support collaborative editing

Part of the /map → /goon → /handoff workflow:
  /map       Plan the work (you are here)
  /goon      Resume a session from the latest handoff
  /handoff   Wrap up a session and generate the next handoff
```

## The feature to plan

$ARGUMENTS

## The workflow (execute ALL steps in order)

### Preliminary — Establish the map directory

Derive a short, kebab-case slug from the feature description (e.g., "hidden
classes and inline caches" → `hidden-classes`, "refactor the document model" →
`document-model-refactor`). Keep it to 2-4 words. If unsure, ask the user.

All artifacts for this MAP live in `.claude/map/{slug}/`:

```
.claude/map/{slug}/
  MAP_PLAN.md
  MAP_PHASE_1.md
  MAP_PHASE_2.md
  ...
  goon.yaml
  SESSION_HANDOFF.md
```

Create this directory before writing any files. Throughout this workflow,
`{map_dir}` refers to `.claude/map/{slug}/`.

### Step 0 — Interview

Before exploring anything, ask the user these questions. Wait for answers
before proceeding. Skip questions the user already answered in their arguments.

1. **Scope**: "Can you describe the end state? What should work when this is
   done that doesn't work today?"
2. **Constraints**: "Any constraints I should know about? Performance targets,
   API compatibility, dependencies to avoid?"
3. **Prior art**: "Have you looked at how other projects handle this? Any
   reference implementations I should study?"
4. **Non-goals**: "Anything that's explicitly out of scope or that I should
   NOT touch?"
5. **Timeline**: "Is this the only thing we're working on, or does it need to
   fit alongside other work?"

If the user's answers are short or vague, that's fine — use them as guardrails
and fill in details during exploration. Don't over-interview. 3-5 answers is
enough to start.

### Step 1 — Explore

Use the Explore agent to deeply understand the relevant parts of the codebase.
Read actual code — don't guess. Identify:

- The current architecture in the area you'll be changing
- Key files, types, and functions involved
- Existing patterns to follow
- Known limitations or bugs in the area

Report your findings before proceeding.

### Step 2 — Draft the plan

Write a plan document to `{map_dir}/MAP_PLAN.md` covering:

- **Current state** — what exists today, what's wrong with it
- **Target state** — what we're building, key design decisions
- **Constraints** — non-negotiable rules (style guide, OPAQUE / domain
  invariants, reviewed feedback memories that bear on this design)
- **Phases** — ordered from critical architecture through correctness through
  improvements, each compilable independently
- **Execution order** — dependency graph between phases
- **Testing strategy** — regression, unit, integration, architecture tests
- **Out of scope** — what explicitly is NOT in this plan and why
- **Files touched** — per phase
- **Critique resolution log** — preserved at the bottom; record each round of
  agent critique and what changed in response. Future sessions read this to
  understand why decisions were made.
- **TODO before dispatch** — checklist the orchestrator works through before
  spawning the first phase agent: re-read style guide, verify file paths
  haven't drifted, confirm referenced symbols exist, etc. Examples:
  - `[ ] Re-read STYLE_GUIDE.md and any feedback memories the design rests on`
  - `[ ] grep for the lines this MAP cites — verify they still resolve`
  - `[ ] Confirm any "X already exists at line Y" claims still hold`
- **Appendix A — Standard agent dispatch preamble** — the verbatim prompt
  body the orchestrator pastes when spawning a phase agent. Includes:
  - Reading order (style guide, OPAQUE, MAP_PLAN, MAP_PHASE_N, CLAUDE.md, MEMORY.md)
  - Verification commands the agent IS allowed to run
  - Verification commands the agent must NOT run (with rationale citing feedback memories)
  - Self-review checklist (composite names, wildcard arms, unwrap, stale comments, etc.)
  - Forbidden patterns (trait abstractions over closed sets, transition shims,
    placeholder macros, AI-attribution lines in commits)
  - Commit and reporting conventions
  - "If you hit a real design decision NOT covered, STOP and report" guard
- **Appendix B — Resume guidance** — what a fresh session does on
  `/goon {slug}`: which files to read in what order, how to identify the
  next phase, how to dispatch it using Appendix A.

**Checkpoint**: Present the plan summary to the user before proceeding to
critique. Ask: "Does this look right directionally? Anything I'm missing or
got wrong before I send this to critique?" Wait for confirmation. If the user
has corrections, incorporate them and re-present.

### Step 3 — Agent critique (iterate until approved)

Spawn a Plan agent with this prompt pattern:

> "Ultrathink. Evaluate this plan at [path] intelligently and rigorously.
> Look for ordering dependencies that don't hold, edge cases the plan
> hasn't accounted for, API design choices that conflict with the project's
> style guide and feedback memories, and assumptions that don't survive
> grep-the-actual-code verification. Read the actual files; don't pattern-match
> from memory. If the plan looks great, say 'the plan looks great.' If there
> are issues, list them with severity and a concrete proposed fix."

Adversarial framing ("harsh," "find everything wrong") tends to inflate
perceived severity and generate noise. Rigorous-and-constructive framing
keeps the bar high without poisoning context — the goal is a real review,
not a stress test.

After each critique round:
1. Address every issue raised — either by fixing the plan or by explicitly
   noting why the issue doesn't apply
2. Update the plan document
3. Re-submit for critique

**Do NOT proceed until an agent says "the plan looks great."**

Expect 2-3 rounds. Common issues caught:
- Phase ordering dependencies missed
- Borrow checker conflicts in Rust
- Performance traps (cloning, allocation in hot loops)
- API design problems (enum bloat, leaky abstractions)
- Missing cleanup/invariant enforcement
- Style-guide violations (composite names, mod.rs, etc.)
- Trait machinery where concrete duplication is the prescribed shape

### Step 4 — FOSS comparison (if applicable)

Search for open-source implementations solving the same problem. Good sources:
- `~/projects/` for local checkouts the user may have
- GitHub via `gh search repos` or `WebSearch`

Spawn an Explore agent to deeply read the FOSS implementation and compare:

> "Thoroughly explore [FOSS project] and compare against our plan at [path].
> Report: what do they do better? What do we do better? What did we miss?
> Give specific file paths and line numbers."

Update the plan with findings. Common discoveries:
- Simpler architectural patterns we over-engineered
- Edge cases they handle that we missed
- Error types or variants we forgot
- Functions/features we should add or deprioritize

### Step 5 — Expert critique

Spawn a Plan agent with a domain-expert persona:

> "You are [domain]'s leading expert. You invented [foundational thing] and
> have spent 30 years building [relevant system]. Ultrathink. Critique this
> plan from DSA, performance, and API perspectives. Find everything."

The expert pass is allowed to be harsh — domain-expert framing earns its
keep when the persona pushes harder than a generic agent would. (Step 3's
regular agent critique uses softer framing because adversarial pressure
without the persona just generates noise.)

Address all issues. Repeat once if needed.

### Step 6 — Write phase documents

For each phase in the plan, write a dedicated implementation doc at
`{map_dir}/MAP_PHASE_N.md` (or a more descriptive name). Each phase doc must be
**self-contained enough for a subagent to implement without reading other phases**.

Each phase doc includes:
- Prerequisites (what must be done first)
- Goal + exit criteria ("when this phase is done, X Y Z work")
- Step-by-step changes with code snippets showing before/after
- Every file that needs changing and what changes
- Verification commands
- Spot-check table (formula/input → expected output)
- What NOT to change (prevent scope creep)

### Step 7 — Cross-reference audit

Read all phase docs and the master plan. Verify:
- Every item in the master plan's checklist has a corresponding phase doc step
- Phase ordering is consistent across all docs
- No phase doc references types/functions that don't exist until a later phase
- Prerequisites in each phase doc match the actual dependency graph

Report any gaps to the user.

### Step 8 — Bootstrap /goon workflow

Now that you have a battle-tested plan, set up the project for `/goon` and
`/handoff` so future sessions can pick up seamlessly.

**Generate `{map_dir}/goon.yaml`** (or update it if it exists). Discover:
- **repo**: `gh repo view --json nameWithOwner -q .nameWithOwner` (if in a git repo with a remote)
- **milestone**: match against open GitHub milestones, or "none"
- **project_board**: `gh project list` to find relevant project boards
- **default_branch**: check `git remote show origin` or `.git/HEAD`
- **workspace members**: read `Cargo.toml` for `[workspace] members`
- **checklist commands**: look in CLAUDE.md, Makefile/justfile, Cargo.toml, CI
  workflows. Categorize into `quick` (< 30s), `verify` (full suite), `lint`
- **key_files**: the files you explored in Step 1 that matter most — CLAUDE.md,
  style guides, workflow docs, core types, entry points (8-12 files)
- **style/workflow docs**: check for `.claude/RUST_STYLE.md`, `.claude/WORKFLOW.md`,
  `rustfmt.toml`, clippy lints in `Cargo.toml`
- Run the `quick` commands to verify they work; fix if they don't

**Interview for things you can't discover from code** — ask the user:
- "Any workflow patterns I should capture? Things that work well or things to avoid?"
- "Want me to set up GitHub project tracking? I can create a project board,
  milestones, labels, and issues from the MAP plan. Or do you manage that
  differently?"

Use this as the reference template. Include every section that applies, omit
what doesn't. Comments show optional fields — uncomment and fill in what you
discover. The typical Rust project uses most of these:

```yaml
# Project configuration for /goon and /handoff commands
# Generated by /map, updated by /handoff as the project evolves.

project: {name}
description: {one-line description}

# GitHub
repo: {owner/repo}
milestone: {current milestone, e.g. "v0.3.0", or "none"}
# project_board: "{board name}"
default_branch: {main or master}

# Handoff file location and naming
handoff:
  dir: .claude/map/{slug}
  prefix: SESSION_HANDOFF

# Workspace structure (from Cargo.toml [workspace] members)
# List crate names and their role so /goon can orient quickly
workspace:
  - name: {crate_name}
    path: "."
    role: "{library|binary} — {what it does}"
  # - name: {other_crate}
  #   path: "other/"
  #   role: "library — {what it does}"
  # - name: {example_app}
  #   path: "examples/app"
  #   role: "example — {what it demonstrates}"

# Crate dependency graph (how workspace members relate to each other)
# architecture:
#   - "{crate_a} → {crate_b} → {crate_c}"

# Verification checklist
# Commands are run in order within each group.
checklist:
  # Quick — run on /goon to verify project compiles and tests pass
  quick:
    - cargo test --workspace
  # Full — run on /handoff before generating the handoff document
  verify:
    - cargo test --workspace
    # - cargo test -p {specific_crate}               # if a crate has slow tests worth calling out
  lint:
    - cargo clippy --all-targets -- -D warnings
    # - cargo fmt --all -- --check                   # if rustfmt is enforced (check rustfmt.toml)

# Key files to internalize at session start (in priority order)
# Include: CLAUDE.md, style guides, workflow docs, core types, entry points
key_files:
  - CLAUDE.md
  # - .claude/RUST_STYLE.md                          # if it exists
  # - .claude/WORKFLOW.md                            # if it exists
  # - src/lib.rs                                     # library root / public API
  # - src/{core_module}.rs                           # core types and logic
  # - {crate}/src/lib.rs                             # other workspace crate entry points

# Example apps (GUI demos, CLI tools — things you cargo run to verify visually)
# These are NOT self-checking test scripts — they're for manual verification.
# examples:
#   - command: "cargo run -p {example_name}"
#     description: "{what it demonstrates}"
#   - command: "cargo run --example {name}"
#     description: "{what it demonstrates}"

# Benchmarks (not run automatically, documented for reference)
# benchmarks:
#   - name: {benchmark name}
#     command: "cargo bench" or "time ./target/release/{bin} {args}"
#     baseline: "{current timing}"
#     target: "{goal timing}"

# Style notes (supplement to CLAUDE.md / RUST_STYLE.md)
# Only include rules NOT already covered in those docs.
style:
  - "No AI attribution in commits or public content"
  # - "Edition 2024, min rust version {version}"
  # - "No mod.rs — use foo.rs + foo/ style"
  # - "No unwrap() in production — use expect('reason')"
  # - "Conventional commits: type(scope): description"

# Workflow notes — learned patterns for working effectively on this project
# These accumulate over sessions as you discover what works and what doesn't.
# workflow:
#   - "Fix bugs before adding features"
#   - "{project-specific lesson}"
```

**Set up GitHub project tracking** (if user approved). This turns the MAP plan
into a living project board.

Key concepts:
- **Milestones are version numbers** (e.g., `v0.1.0`, `v0.2.0`). They
  represent releases, not topics or phases. A milestone answers "what ships
  in this version?"
- **Labels are topics/categories** (e.g., `performance`, `language`, `jit`,
  `parser`, `builtins`, `node polyfill`). They categorize what an issue is
  about, orthogonal to which version it ships in.
- An issue gets **one milestone** (which release) and **one or more labels**
  (what topics it touches).

Steps:

1. **Create a project board** (if none exists):
   ```
   gh project create --owner {owner} --title "{Project Name} Roadmap"
   ```

2. **Create milestones** as version numbers. Ask the user how MAP phases group
   into releases:
   > "The plan has 4 phases. How should these map to versions? For example:
   > - v0.1.0 = Phases 1-2 (core architecture)
   > - v0.2.0 = Phases 3-4 (polish + performance)
   > Or all in one version?"
   ```
   gh api repos/{owner}/{repo}/milestones -f title="v0.1.0" \
     -f description="Core architecture: shapes, inline slots" -f state="open"
   ```

3. **Create labels** for topics derived from the plan's areas of work. These
   are categories, not milestones — an issue labeled `performance` might ship
   in v0.1.0 or v0.3.0:
   ```
   gh label create "performance" --repo {owner}/{repo} --color "0E8A16"
   gh label create "language" --repo {owner}/{repo} --color "1D76DB"
   gh label create "done" --repo {owner}/{repo} --color "5319E7"
   ```

4. **Create issues** from the MAP plan. Each discrete piece of work gets an
   issue with a **version milestone** and **topic labels**:
   ```
   gh issue create --repo {owner}/{repo} \
     --title "Implement shape transition tree" \
     --milestone "v0.1.0" --label "performance" \
     --body "From MAP Phase 2: ..."
   ```
   Don't create one issue per phase — break phases into individual work items.
   Present the list to the user before creating:
   > "I'll create these issues:
   > - Implement PropertyMap wrapper (v0.1.0, `language`)
   > - Add Shape type with transition tree (v0.1.0, `performance`)
   > - Monomorphic inline caches (v0.2.0, `jit`, `performance`)
   > - ...
   > Look right?"

5. **Link issues to the project board** if one was created:
   ```
   gh project item-add {project-number} --owner {owner} --url {issue-url}
   ```

Update `goon.yaml` with the project board name and current milestone after
creation. The `/handoff` and `/goon` skills will use these to check and sync
issue status across sessions.

If the user declined GitHub tracking, skip all of this — the workflow works
fine with just local handoff files and no issue tracking.

**Generate `{map_dir}/SESSION_HANDOFF.md`** — the initial handoff doc. Structure:

1. **Project description** — what is this, one paragraph
2. **Where things stand** — stats (LOC, tests), current state
3. **Project management** — GitHub workflow (milestones, labels, issue lifecycle)
4. **The plan** — reference `MAP_PLAN.md` and list the phases with
   status (all "pending" at this point)
5. **What to build next** — Phase 1 from the MAP, with enough context to start
6. **Known bugs and tech debt** — anything found during exploration
7. **Key files to read first** — numbered list with one-line descriptions
8. **Running commands** — build, test, run, lint
9. **End-of-session checklist** — verify, lint, push, write next handoff
10. **Style guide** — key conventions

The handoff must be self-contained — a fresh session with only this file and
`goon.yaml` should be able to start working immediately.

**Checkpoint**: Show the user the generated `goon.yaml` and handoff. Ask:
"Anything to add or change before we lock this in?" Incorporate feedback.

## Output

When complete, you should have:
- `{map_dir}/MAP_PLAN.md` — the master plan (battle-tested through critique)
- `{map_dir}/MAP_PHASE_N.md` — one doc per phase (self-contained for subagents)
- `{map_dir}/goon.yaml` — project config for `/goon` and `/handoff`
- `{map_dir}/SESSION_HANDOFF.md` — initial handoff document
- A summary message to the user listing all docs and key design decisions,
  and telling them they can now use `/goon` to start sessions and `/handoff`
  to end them

## Rules

- Each phase must compile independently (`cargo clippy --all-targets` or equivalent)
- Follow the project's existing style guide and conventions (check CLAUDE.md, RUST_STYLE.md, etc.)
- Prefer editing existing files over creating new ones
- No premature abstractions — build what the plan requires, nothing more
- Write code snippets showing the actual types and signatures, not pseudocode
- When a playground test can verify a tricky Rust borrow pattern, run it
