# Flow Plan Steps

**IMPORTANT**: Steps 1-3 (research, gap analysis, depth) ALWAYS run regardless of input type.

**CRITICAL**: If you are about to create:
- a markdown TODO list,
- a task list outside `.flow/`,
- or any plan files outside `.flow/`,

**STOP** and instead:
- create/update tasks in `.flow/` using `flowctl`,
- record details in the spec/task markdown.

## Success criteria

- Plan references existing files/patterns with line refs
- Reuse points are explicit (centralized code called out)
- Acceptance checks are testable
- Tasks are small enough for one `/flow-next:work` iteration (split if not)
- **No implementation code** — specs describe WHAT, not HOW (see SKILL.md Golden Rule)
- Open questions are listed

## Task Sizing Rule

Use **T-shirt sizes** based on observable metrics — not token estimates (models can't reliably estimate tokens).

| Size | Files | Acceptance Criteria | Pattern | Action |
|------|-------|---------------------|---------|--------|
| **S** | 1-2 | 1-3 | Follows existing | Combine with related work |
| **M** | 3-5 | 3-5 | Adapts existing | ✅ **Sweet spot** |
| **L** | 5+ | 5+ | New/novel | ⚠️ Split into M tasks |

**M is the target size** — fits one context window (~80-100k tokens), makes meaningful progress.

**Anchor examples** (calibrate against these):
- **S**: Fix a bug, add config, simple UI tweak → combine if sequential
- **M**: New API endpoint with tests, new component with state → ideal
- **L**: New subsystem, architectural change → split into M tasks

**Combine rule**: Sequential S tasks touching related code → combine into one M task.

**If too large, split it:**
- ❌ Bad: "Implement Google OAuth" (L — new subsystem)
- ✅ Good:
 - "Google OAuth backend (config + passport + routes)" (M)
 - "Add Google sign-in button" (S)

**If too granular (7+ tasks), combine:**
- ❌ Over-split: 4 sequential S tasks for backend setup
- ✅ Better: 1 M task covering the sequential work

**Minimize file overlap for parallel work:**

When splitting tasks, design for minimal file overlap. Tasks touching disjoint files can be worked in parallel without merge conflicts.

- ❌ Bad: Task A and B both modify `src/auth.ts`
- ✅ Good: Task A modifies `src/auth.ts`, Task B modifies `src/routes.ts`

List expected files in each task's `**Files:**` field. If multiple tasks must touch the same file, mark dependencies explicitly with `flowctl dep add`.

## Step 0: Initialize .flow

**CRITICAL: flowctl is BUNDLED — NOT installed globally.** `which flowctl` will fail (expected). Always use:

```bash
# Get flowctl path
FLOWCTL="${DROID_PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$HOME/.codex}}/scripts/flowctl"
[ -x "$FLOWCTL" ] || FLOWCTL=".flow/bin/flowctl"

# Ensure .flow exists
$FLOWCTL init --json
```

## Step 1: Fast research (parallel)

**If input is a Flow ID** (fn-N-slug or fn-N-slug.M, including legacy fn-N/fn-N-xxx): First fetch it with `$FLOWCTL show <id> --json` and `$FLOWCTL cat <id>` to get the request context.

**Check if memory and github-scout are enabled:**
```bash
$FLOWCTL config get memory.enabled --json
$FLOWCTL config get scouts.github --json
```

**Check for STRATEGY.md (husk-vs-presence — uses `sections_filled >= 1`, NOT `[[ -f STRATEGY.md ]]`):**
```bash
STRATEGY_STATUS_JSON=$($FLOWCTL strategy status --json 2>/dev/null || echo '{"exists":false,"sections_filled":0}')
STRATEGY_FILLED=$(jq -r '.sections_filled // 0' <<< "$STRATEGY_STATUS_JSON" 2>/dev/null || echo 0)

if [[ "$STRATEGY_FILLED" -ge 1 ]]; then
 STRATEGY_JSON=$($FLOWCTL strategy read --json 2>/dev/null || echo '{}')
 # Pass the parsed STRATEGY.md content into plan-prompt context alongside research findings.
 # `tracks` is a raw markdown string (### <track-name> H3 sub-blocks); empty section bodies
 # are "" not null. The plan prompt sees `name`, `target_problem`, `approach`, `tracks`,
 # `last_updated` verbatim — no paraphrasing. Active tracks shape the Strategy Alignment
 # section in Step 5; conflicts with active tracks surface as drift in Step 5.
 STRATEGY_PRESENT=true
else
 STRATEGY_PRESENT=false
fi
```

When `STRATEGY_PRESENT=true`, the scouts and the plan-prompt see the strategy content. When `STRATEGY_PRESENT=false` (no STRATEGY.md or husk), the plan skips the `## Strategy Alignment` section and any drift-surfacing entirely (Step 5) — absence is fine, no signal to align to.

**Based on user's choice in SKILL.md setup:**

---

**CRITICAL: You MUST run ALL listed scouts. Run them in parallel for efficiency. Do NOT skip any scout — each provides unique signal that improves plan quality.**

---

**If user chose context-scout (RepoPrompt)**:

Run ALL of these scouts in parallel:
| Scout | Purpose | Required |
|-------|---------|----------|
| the `context_scout` agent | RepoPrompt AI file discovery | YES |
| the `practice_scout` agent | Best practices + pitfalls | YES |
| the `docs_scout` agent | External documentation | YES |
| the `github_scout` agent | Cross-repo patterns via gh CLI | IF scouts.github |
| the `memory_scout` agent | Project memory entries | IF memory.enabled |
| the `spec_scout` agent | Dependencies on open specs | YES |
| the `docs_gap_scout` agent | Docs needing updates | YES |

**If user chose repo-scout (default/faster)** OR rp-cli unavailable:

Run ALL of these scouts in parallel:
| Scout | Purpose | Required |
|-------|---------|----------|
| the `repo_scout` agent | Grep/Glob/Read patterns | YES |
| the `practice_scout` agent | Best practices + pitfalls | YES |
| the `docs_scout` agent | External documentation | YES |
| the `github_scout` agent | Cross-repo patterns via gh CLI | IF scouts.github |
| the `memory_scout` agent | Project memory entries | IF memory.enabled |
| the `spec_scout` agent | Dependencies on open specs | YES |
| the `docs_gap_scout` agent | Docs needing updates | YES |

**Anti-pattern**: Running only 2-3 scouts "because they seem most relevant" — this causes incomplete plans.

Must capture:
- File paths + line refs
- Existing centralized code to reuse
- Similar patterns / prior work
- External docs links
- Project conventions (CLAUDE.md, CONTRIBUTING, etc)
- Architecture patterns and data flow (especially with context-scout)
- Spec dependencies (from spec-scout)
- Doc updates needed (from docs-gap-scout) - add to task acceptance criteria
- DESIGN.md design system tokens (if repo-scout found one)

## Step 2: Stakeholder & scope check

Before diving into gaps, identify who's affected:
- **End users** — What changes for them? New UI, changed behavior?
- **Developers** — New APIs, changed interfaces, migration needed?
- **Operations** — New config, monitoring, deployment changes?

This shapes what the plan needs to cover. A pure backend refactor needs different detail than a user-facing feature.

## Step 3: Flow gap check

Run the gap analyst subagent:
- Use the flow_gap_analyst agent(<request>, research_findings)

Fold gaps + questions into the plan.

## Step 4: Pick depth

Default to standard unless complexity demands more or less.

**SHORT** (bugs, small changes)
- Problem or goal
- Acceptance checks
- Key context

**STANDARD** (most features)
- Overview + scope
- Approach
- Risks / dependencies
- Acceptance checks
- Test notes
- References
- Mermaid diagram if data model changes

**DEEP** (large/critical)
- Detailed phases
- Alternatives considered
- Non-functional targets
- Architecture/data flow diagram (mermaid)
- Rollout/rollback
- Docs + metrics
- Risks + mitigations

## Step 5: Write to .flow

**Efficiency note**: Use stdin (`--file -`) with heredocs to avoid temp files. Use `task set-spec` to set description + acceptance in one call.

**Route A - Input was an existing Flow ID**:

1. If spec ID (fn-N-slug or legacy fn-N/fn-N-xxx):
 ```bash
 # Use stdin heredoc (no temp file needed)
 $FLOWCTL spec set-plan <id> --file - --json <<'EOF'
 <plan content here>
 EOF
 ```
 - Create/update child tasks as needed

2. If task ID (fn-N-slug.M or legacy fn-N.M/fn-N-xxx.M):
 ```bash
 # Combined set-spec: description + acceptance in one call
 # Write to temp files only if content has single quotes
 $FLOWCTL task set-spec <id> --description /tmp/desc.md --acceptance /tmp/acc.md --json
 ```

**Route B - Input was text (new idea)**:

1. Create spec:
 ```bash
 $FLOWCTL spec create --title "<Short title>" --json
 ```
 This returns the spec ID (e.g., fn-1-add-oauth).

2. Set spec branch_name (deterministic):
 - Default: use spec ID (e.g., fn-1-add-oauth)
 ```bash
 $FLOWCTL spec set-branch <spec-id> --branch "<spec-id>" --json
 ```
 - If user specified a branch, use that instead.

3. Write spec (use stdin heredoc):

 The canonical scaffold lives in [`plugins/flow-next/templates/spec.md`](../../templates/spec.md) — section list, scope-owner annotations, and the `## Decision Context` flat-vs-H3 conditional. At runtime the template is resolved via the 4-tier discovery cascade (first match wins): `<repo_root>/SPEC.md` → `<repo_root>/spec.md` → `.flow/templates/spec.md` → bundled `${PLUGIN_ROOT}/templates/spec.md`. The bundled file is the canonical source of truth; earlier tiers are user-customized overrides. Read the resolved template before authoring; never duplicate its section list inline. The plan skill extends that scaffold with the plan-specific sections shown below (Overview, Quick commands, Strategy Alignment, Strategy drift, Early proof point, Requirement coverage).

 ```bash
 # Include: Overview, Scope, Approach, Quick commands (REQUIRED),
 # Acceptance Criteria, Early proof point, Requirement coverage, References
 # Conditional sections: ## Strategy Alignment (when STRATEGY_PRESENT=true from Step 1),
 # ## Strategy drift flagged for review (when plan scope conflicts with an active track)
 # Add mermaid diagram if data model or architecture changes
 $FLOWCTL spec set-plan <spec-id> --file - --json <<'EOF'
 # Spec Title

 ## Overview
 ...

 ## Quick commands
 ```bash
 # At least one smoke test command
 ```

 ## Boundaries / non-goals
 - <what this spec explicitly does NOT cover>

 ## Strategy Alignment
 <!-- Include this section ONLY when STRATEGY_PRESENT=true from Step 1.
 When STRATEGY_PRESENT=false (no STRATEGY.md or husk: sections_filled == 0),
 skip this section entirely. -->

 Active tracks served by this plan:
 - **<track-name>** — <one line on how this plan advances the track>
 - **<track-name>** — <one line>

 <!-- If the plan serves no active strategy track, replace the bulleted list with: -->
 _No active strategy track served — review for drift._

 ## Strategy drift flagged for review
 <!-- Include this block ONLY when the plan scope conflicts with an active track.
 Mirrors plan-sync's "Decision overrides flagged for review" convention
 (agents/plan-sync.md). Read-only — the plan skill never auto-supersedes
 STRATEGY.md; the user (or `/flow-next:strategy`) decides whether to revise. -->

 - **<track-name>**: <one line on how this plan diverges from the track's stated direction>. Review for revision via `/flow-next:strategy`.

 ## Decision context
 - <why this approach over alternatives>

 ## Acceptance Criteria
 - **R1:** <testable criterion>
 - **R2:** <testable criterion>
 - **R3:** <testable criterion>

 ## Early proof point
 Task fn-N-slug.1 validates the core approach (<what it proves>).
 If it fails, re-evaluate <strategy> before continuing with fn-N-slug.2+.

 ## Requirement coverage

 | Req | Description | Task(s) | Gap justification |
 |-----|-------------|---------|-------------------|
 | R1 | <criterion from Acceptance Criteria> | fn-N-slug.1, fn-N-slug.2 | — |
 | R2 | <another criterion> | fn-N-slug.3 | — |
 | R3 | <deferred item> | — | Deferred to fn-M-slug |
 EOF
 ```

 **`## Strategy Alignment` rules (active iff STRATEGY_PRESENT=true from Step 1):**
 - Section sits between `## Boundaries / non-goals` and `## Decision context` in the template above.
 - List active tracks (`### <track-name>` blocks parsed from the strategy snapshot's `tracks` raw markdown string) that this plan advances.
 - When the plan serves NO active track, render the placeholder `_No active strategy track served — review for drift._` literally — do not omit the section.
 - Skip the entire section when STRATEGY_PRESENT=false. Husk-vs-presence: gated on `sections_filled >= 1`, NOT `[[ -f STRATEGY.md ]]`.

 **`## Strategy drift flagged for review` rules (conditional on conflict detection):**
 - Mirrors plan-sync's "Decision overrides flagged for review" surface (`agents/plan-sync.md` Phase 6 summary).
 - Bulleted list with track name + plan-decision divergence + `Review for revision via /flow-next:strategy.` line per item.
 - Read-only — the plan skill never edits STRATEGY.md, never marks a track superseded, never auto-supersedes anything. Surface for human review only.
 - Omit the heading entirely when no drift detected. Empty drift block is silent, not `_(none)_`.

 **Early proof point rules:**
 - Identify which task proves the fundamental approach works
 - One sentence: which task + what it proves
 - One sentence: what to reconsider if it fails
 - Usually the first task in dependency order, but not always

 **Requirement coverage rules:**
 - One row per acceptance criterion or distinct requirement from the spec
 - Every requirement must map to at least one task OR have a gap justification
 - Table goes at the bottom of the spec (after Acceptance Criteria + Early proof point)
 - Keep Req IDs simple (R1, R2...) — they're local to this spec

 **R-ID rule (MANDATORY for new specs):**
 - Number acceptance criteria as `R1`, `R2`, `R3`, ... in creation order using the `- **Rn:** ...` prose prefix format shown in the template above.
 - Once a review cycle has run against an R-ID, **never renumber**. Reordering is fine (R1, R3, R5 after R2/R4 deletion is correct).
 - New criteria take the next unused number. Gaps are fine — do not compact.
 - R-IDs in `## Acceptance Criteria` and `## Requirement coverage` must match (same IDs, same meanings).
 - R-IDs are plain markdown prose, not YAML — the reviewer matches them via LLM reasoning, not strict parsing.

4. Set spec dependencies (from spec-scout findings):

 If spec-scout found dependencies, set them automatically:
 ```bash
 # For each dependency found by spec-scout:
 $FLOWCTL spec add-dep <new-spec-id> <dependency-spec-id> --json
 ```

 Report findings at end of planning (no user prompt needed):
 ```
 Spec dependencies set:
 - fn-N-slug → fn-2-add-auth (Auth): Uses authService from fn-2-add-auth.1
 - fn-N-slug → fn-5-user-model (DB): Extends User model
 ```

5. Create child tasks:
 ```bash
 # Task with no dependencies:
 $FLOWCTL task create --spec <spec-id> --title "<Task title>" --json

 # Task with dependencies (use --deps for inline dependency declaration):
 $FLOWCTL task create --spec <spec-id> --title "<Task title>" --deps <dep1>,<dep2> --json
 ```

 **TIP**: Use `--deps` to declare dependencies inline when creating tasks. Tasks must exist before being referenced, so create in dependency order.

6. Write task specs (use combined set-spec):
 ```bash
 # For each task - single call sets both sections
 # Write description and acceptance to temp files, then:
 $FLOWCTL task set-spec <task-id> --description /tmp/desc.md --acceptance /tmp/acc.md --json
 ```

 **When the task needs `satisfies:` frontmatter**, use `--file` mode instead (frontmatter lives above the sections, not inside them):
 ```bash
 $FLOWCTL task set-spec <task-id> --file - --json <<'EOF'
 ---
 satisfies: [R1, R3]
 ---

 ## Description
 ...

 ## Acceptance
 - [ ] ...
 EOF
 ```

 **Task spec content** (remember: NO implementation code):
 ```markdown
 ---
 satisfies: [R1, R3]
 ---

 ## Description
 [What to build, not how to build it]

 **Size:** S/M (L tasks should be split)
 **Files:** list expected files

 ## Approach
 - Follow pattern at `src/example.ts:42`
 - Reuse `existingHelper()` from `lib/utils.ts`

 ## Investigation targets
 **Required** (read before coding):
 - `src/auth/oauth.ts` — existing OAuth flow to extend
 - `src/middleware/session.ts:23-45` — session validation pattern

 **Optional** (reference as needed):
 - `src/auth/*.test.ts` — existing test patterns

 ## Design context
 *Only include for frontend tasks when DESIGN.md exists in project.*

 Relevant DESIGN.md sections for this task:
 - **Colors:** Primary (#2665fd) for CTAs, Neutral (#757681) for backgrounds
 - **Components:** Buttons are rounded (8px), primary uses brand blue fill
 - **Do's/Don'ts:** Primary color only for single most important action per screen

 Full design system: `DESIGN.md` (read before implementing UI changes)

 ## Key context
 [Only for recent API changes, surprising patterns, or non-obvious gotchas]

 ## Acceptance
 - [ ] Criterion 1
 - [ ] Criterion 2
 ```

 **Design context rule:** Only add `## Design context` to tasks where Files/Description reference frontend patterns:
 - Extensions: `.jsx`, `.tsx`, `.vue`, `.svelte`, `.css`, `.scss`
 - Directories: `components/`, `pages/`, `views/`, `layouts/`, `styles/`, `app/`
 - Keywords: button, modal, form, layout, responsive, color, font, card, navigation, theme, UI, component

 Backend-only tasks (`api/`, `server/`, `controllers/`, `.py`, `.go`): skip design context.
 When ambiguous: include it (false positive is low-cost, false negative causes inconsistency).

 **Investigation targets rules:**
 - Max 5-7 targets per task (focus, don't flood)
 - Use exact file paths with optional line ranges — not descriptions alone
 - Validate paths exist at plan time (repo-scout/context-scout already found them)
 - "Required" = must read before implementing. "Optional" = helpful reference
 - Targets come from repo-scout/context-scout findings in Step 1

 **`satisfies` frontmatter rules (optional, additive):**
 - Populate `satisfies: [R1, R3]` only when the task obviously advances specific R-IDs from the spec's `## Acceptance Criteria` section.
 - Tasks that do infrastructure, refactoring, shared plumbing, or docs-only work may legitimately have **no** `satisfies` entry — omit the frontmatter entirely.
 - Use bare R-ID tokens (`[R1, R3]`), not quoted strings.
 - Frontmatter is additive — tasks created without it parse unchanged.

7. Add task dependencies (if not already set via `--deps`):

 **Preferred**: Use `--deps` flag during task creation (step 5). This saves prompt turns.

 **Alternative**: Use `dep add` to add dependencies after task creation:
 ```bash
 # Syntax: dep add <dependent-task> <dependency-task>
 # "task B depends on task A" → dep add B A
 $FLOWCTL dep add fn-N.2 fn-N.1 --json
 ```

 Use `dep add` when you need to add dependencies to existing tasks or fix missed dependencies.

8. Output current state:
 ```bash
 $FLOWCTL show <spec-id> --json
 $FLOWCTL cat <spec-id>
 ```

## Step 6: Validate

```bash
$FLOWCTL validate --spec <spec-id> --json
```

Fix any errors before proceeding.

## Step 7: Review (if chosen at start)

If user chose "Yes" to review in SKILL.md setup question:
1. Invoke `/flow-next:plan-review` with the spec ID
2. If review returns "Needs Work" or "Major Rethink":
 - **Re-anchor EVERY iteration** (do not skip):
 ```bash
 $FLOWCTL show <spec-id> --json
 $FLOWCTL cat <spec-id>
 ```
 - **Immediately fix the issues** (do NOT ask for confirmation — user already consented)
 - Re-run `/flow-next:plan-review`
3. Repeat until review returns "Ship"

**No human gates here** — the review-fix-review loop is fully automated.

**Why re-anchor every iteration?** Per Anthropic's long-running agent guidance: context compresses, you forget details. Re-read before each fix pass.

## Step 8: Offer next steps

Show spec summary with size breakdown and offer options:

```
Spec fn-N-slug created: "<title>"
Tasks: M total | Sizes: Ns S, Nm M

Next steps:
1) Start work: `/flow-next:work fn-N-slug`
2) Refine via interview: `/flow-next:interview fn-N-slug`
3) Review the plan: `/flow-next:plan-review fn-N-slug`
4) Go deeper on specific tasks (tell me which)
5) Simplify (reduce detail level)
```

If user selects 4 or 5:
- **Go deeper**: Ask which task(s), then add more context/research to those specific tasks
- **Simplify**: Remove non-essential sections, tighten acceptance criteria, merge small tasks

Loop back to options after changes until user selects 1, 2, or 3.
