Skip to content
playbookplanningdevelopment

Gap-Driven Iterative Planning ​

Build implementation plans through repeated cycles of writing, gap identification, and refinement until the remaining ambiguity is near zero.

Audience: Engineers, tech leads, product managers scoping work.


When to Use ​

Use iterative planning when:

  • The feature is non-trivial (more than 1 day of implementation work)
  • Requirements are partially defined — you know the "what" but not all the "how"
  • The change spans multiple systems (database, backend, frontend, external APIs)
  • You are working in an unfamiliar codebase where assumptions are dangerous
  • The feature involves state machines, rule engines, or complex domain logic

Do NOT use for:

  • Trivial bug fixes or single-file changes
  • Well-understood tasks you have done before
  • Cosmetic/styling changes
  • Tasks where the implementation path is immediately obvious

Decision Rule

If you can describe the full implementation in your head without writing anything down, you probably do not need this playbook. If you cannot, you do.

Starting from Scratch?

If requirements are still rough or incomplete, start with the Requirements Elicitation Playbook first, then return here to plan the implementation.


The Planning Loop ​

┌─────────────────────────────────────────────────────────┐
│                                                         │
│   Write initial plan                                    │
│        │                                                │
│        ▼                                                │
│   Identify gaps & ambiguities  ◄──────────────────┐     │
│        │                                          │     │
│        ▼                                          │     │
│   Clarify with stakeholders                       │     │
│   (specific questions, not "looks good?")         │     │
│        │                                          │     │
│        ▼                                          │     │
│   Update plan with answers                        │     │
│        │                                          │     │
│        ▼                                          │     │
│   Re-examine for new gaps ────────────────────────┘     │
│   (answers often create new questions)                  │
│        │                                                │
│        ▼                                                │
│   Done: no gaps, all edge cases covered, verifiable     │
│                                                         │
└─────────────────────────────────────────────────────────┘

A plan is ready when every enum value is accounted for, every relationship is defined, every status transition has a trigger, every edge case has a resolution, and every file path and namespace reference has been verified against the actual codebase.


Phase 1: Context Gathering ​

Before writing the plan, understand what already exists. This phase prevents the most common planning failure: building on incorrect assumptions about the codebase.

What to Read ​

CategoryExamples
Existing modelsThe model you are replacing or extending, its relationships, its traits
Existing controllersAPI shape, authorization patterns, response formats
Existing policiesAuthorization patterns, gate helpers, role checks
Existing migrationsColumn naming conventions, FK patterns, index strategies
Existing testsWhat is tested, what test infrastructure exists
DocumentationSpecs, audits, research reports, prototype code
Recent commitsWhat has changed recently that might affect your work

Launch Explore Agents ​

For large codebases, dispatch 2-3 explore agents with focused objectives:

Agent 1: "Read all models in app/Models/ related to [domain].
          Map their relationships, traits, and key methods.
          Report: model name, table, key relationships, notable patterns."

Agent 2: "Read all controllers in app/Http/Controllers/Api/ related to [domain].
          Map routes, authorization, request validation, response format.
          Report: endpoint, method, auth pattern, request shape, response shape."

Agent 3: "Read all migrations related to [domain].
          Map column names, types, indexes, FKs, conventions.
          Report: table, columns, notable patterns."

Real Example ​

An entitlement system plan started by reading:

  • The existing model being replaced (to understand current behavior)
  • The authorization policy (to match access control patterns)
  • The broadcast event (to understand real-time update patterns)
  • The API controller (to follow endpoint conventions)
  • A competitive analysis audit document (from earlier research)
  • An HTML prototype of the new rule engine UI

This context gathering revealed critical namespace conventions. The codebase used non-standard model paths, and getting them wrong in the plan would have cascaded into incorrect polymorphic type values.


Phase 2: First Draft ​

Write a structured plan that covers every layer of the implementation. The goal is not perfection. The goal is to get enough on paper that gaps become visible.

Plan Structure ​

Follow this order (adjusted for your stack):

  1. Context — what exists, what is changing, key decisions already made
  2. Enums — all enumerated values with descriptions
  3. Database Migrations — full column definitions with types, defaults, constraints
  4. Models — relationships, casts, computed properties, scopes
  5. Services — business logic, rule engines, state transitions
  6. Controllers — endpoints, request validation, authorization, responses
  7. Events & Observers — side effects, broadcasts, cascading changes
  8. Tests — scenario coverage, edge cases, integration points

Level of Detail ​

The plan must be specific enough that someone, human or agent, could implement from it without asking clarifying questions. This means:

Do this:

markdown
### `create_entitlements_table`

| Column                  | Type                                    | Notes                    |
| ----------------------- | --------------------------------------- | ------------------------ |
| `id`                    | bigint PK                               |                          |
| `uuid`                  | uuid, unique                            | Stable public identifier |
| `participant_id`        | bigint FK → participants                | CASCADE on delete        |
| `entitlement_item_id`   | bigint FK → entitlement_items           |                          |
| `entitlement_rule_id`   | bigint FK → entitlement_rules, nullable | null = manual            |
| `quantity`              | int, nullable                           |                          |
| `status`                | string(50), default `active`            | EntitlementStatus enum   |
| `valid_from`            | datetime, nullable                      |                          |
| `valid_to`              | datetime, nullable                      |                          |
| timestamps, softDeletes |                                         |                          |

Not this:

markdown
### Entitlements table

- Has the usual columns
- References participants and items
- Tracks status

Include Rationale for Design Decisions ​

When a decision is non-obvious, explain why. Future readers, including you, will need that context.

Real example from the entitlements plan:

Why not store expired/depleted/overdue as status values? These are time-dependent — they become true/false based on the current moment. Storing them would require cron jobs to flip statuses, and for per_day entitlements, depleted resets every midnight. Keeping them computed avoids stale state and eliminates an entire class of sync bugs.

Reference Existing Patterns ​

Explicitly call out conventions from the codebase:

  • "Use return new class extends Migration syntax — matches codebase convention"
  • "String-backed enums, validated in app not DB — matches existing enums"
  • "Use GateHelper authorization pattern — see AccreditationListPolicy"
  • "Broadcast events follow BroadcastAccreditationChanged pattern"

Phase 3: Explicit Gap Identification ​

This is the step most people skip, and it is usually the most valuable one.

After writing the first draft, explicitly ask for gap identification:

Prompt: "This plan likely has gaps, missing details, and ambiguities.
         Identify them. Check:
         - Is every enum value used somewhere? Are any missing?
         - Is every relationship fully defined (type, FK, cascade)?
         - Are all edge cases handled?
         - Are status transitions complete? What triggers each?
         - Are namespace/path references accurate?
         - Are column names verified against the actual schema?
         - Are there implicit assumptions that should be explicit?"

What Gap Identification Typically Finds ​

CategoryExample from Entitlements Plan
Wrong assumptions about existing codeFestival has no users() method — must use festivalInvites() (HasMany) instead
Incorrect column namesFestivalSectionPublicFormResponsePivot uses section_id and response_id, not festival_section_id and public_form_response_id
Missing triggersPlan documented 12 observer triggers; audit found 16 additional missing triggers across 5 priority tiers
Under-specified mappingsAffiliation mapping was documented for 3 of 5 sources but ambiguous for guests and contacts
Missing edge cases"What happens when a participant matches a rule but the rule requires approval, and then the participant stops matching before approval is granted?"
Namespace errorsUsing App\Models\PartnerContact instead of App\PartnerContact

Gap Identification Checklist ​

Run through each of these explicitly:

  • [ ] Every enum: are all values defined? Is each value used in at least one status transition or condition?
  • [ ] Every migration column: does the type match the intended usage? Are nullable columns explicitly marked?
  • [ ] Every relationship: is it HasMany, BelongsTo, MorphTo, etc.? Is the FK correct?
  • [ ] Every status transition: what triggers it? Is it reversible? What happens to related records?
  • [ ] Every polymorphic type: is the *_type value the correct fully-qualified class name?
  • [ ] Every file path and namespace: verified against ls or find in the actual codebase?
  • [ ] Every computed value: is the computation defined? Are edge cases handled (null, zero, negative)?
  • [ ] Every observer/event: is the trigger condition precise? What about bulk operations?
  • [ ] Concurrency: can two processes modify the same record simultaneously? Is locking needed?
  • [ ] Deletion cascades: what happens when a parent record is soft-deleted? Hard-deleted?

Phase 4: Clarification Rounds ​

When gaps are identified, ask the stakeholder specific, answerable questions, not open-ended "does this look good?"

Good Questions ​

1. Rules engine: should this ship in v1 or be deferred to v2?
   Option A: v1 (the prototype already designs the full UX)
   Option B: v2 (reduces scope, but frontend team has to wait)

2. Data migration: clean cutover per festival, or migrate existing data?
   Option A: Clean cutover — new festivals use entitlements, old ones stay on accreditations
   Option B: Migration — write a script to convert accreditations to entitlements
   Trade-off: A is simpler but means two systems coexist temporarily

3. When a rule-created entitlement is pending approval and the participant
   stops matching the rule, should the entitlement be:
   Option A: Hard-deleted (disappears entirely)
   Option B: Soft-deleted (preserved for audit trail)
   Option C: Revoked (status change, remains visible)

Bad Questions ​

- "Does this plan look good?" (too vague to get useful feedback)
- "What should the status values be?" (you should propose them)
- "How should this work?" (you should propose how, then ask for corrections)

Group Questions by Category ​

Group questions so the stakeholder can think about related decisions together:

## Data Model Questions
1. ...
2. ...

## UX/Workflow Questions
3. ...
4. ...

## Edge Cases
5. ...
6. ...

## Migration & Rollout
7. ...

Phase 5: Plan Hardening ​

After clarification rounds, harden the plan by cross-referencing it against every available source of truth.

Cross-Reference Against Prototypes ​

If a prototype or mockup exists, verify that every UI element has a corresponding data field in the plan, and that every planned data field appears somewhere in the UI.

Cross-Reference Against Research ​

If a research or audit document exists, verify that the plan addresses every finding. Create a checklist:

markdown
## Audit Findings Coverage

- [x] Finding 1: Binary status needs multi-state → EntitlementStatus enum
- [x] Finding 2: No rule engine → EntitlementRule model + criteria JSON
- [ ] Finding 3: No credential tracking → TODO: add CredentialStatus

Run Through Code-Reviewer Agent ​

Ask a code-reviewer agent to review the plan for logic gaps:

Prompt: "Review this implementation plan as if it were a PR.
         Focus on:
         - Logical inconsistencies between sections
         - Missing error handling
         - Undefined behavior for edge cases
         - Performance concerns (N+1 queries, missing indexes)
         - Security gaps (authorization, validation)"

Verify All References ​

Before finalizing, verify every reference in the plan:

bash
# Verify model namespaces
grep -r "class Festival " app/ --include="*.php" -l

# Verify column names
grep -r "section_id\|festival_section_id" database/migrations/ --include="*.php"

# Verify method existence
grep -r "function users\|function festivalInvites" app/Festival.php

Next Step

Once the plan is hardened, move to Stage 3: Execute in the Development Lifecycle.


Anti-Patterns ​

1. Writing Code Before the Plan Is Solid ​

Symptom: "I will figure it out as I go."

Why it fails: You discover architectural issues after writing 500 lines of code. Refactoring costs 3x more than getting the plan right.

Fix: Do not write implementation code until the plan has survived at least one gap identification round with zero critical findings.

2. Assuming Instead of Asking ​

Symptom: "Festival probably has a users() method." (It does not.)

Why it fails: Wrong assumptions cascade. If Festival->users() does not exist, every query and relationship that depends on it fails.

Fix: Verify every assumption against the actual codebase. Use explore agents to read the code.

3. Stopping After the First Draft ​

Symptom: "The plan looks complete to me."

Why it fails: The entitlements plan found 16 missing observer triggers, incorrect column names, and ambiguous affiliation mappings — none visible in the first draft.

Fix: Run explicit gap identification (Phase 3). If zero gaps are found, look harder.

4. Planning in Your Head Instead of on Paper ​

Symptom: "I know what I need to do, I do not need to write it down."

Why it fails: Unwritten plans cannot be reviewed, cannot be gap-checked, and cannot be handed to another developer or agent. They also tend to be far less complete than the author believes.

Fix: Write it down. Even a rough plan on paper is better than a polished plan in your head.

5. Open-Ended Stakeholder Questions ​

Symptom: "What do you think about the status values?"

Why it fails: Stakeholders cannot design your system for you. They can choose between options you present.

Fix: Always propose options with trade-offs. "Should status be A (simpler, 4 values) or B (more granular, 6 values)? Here is why I lean toward B..."


Plan Document Template ​

Use this template as a starting point, adjusting sections for your stack and domain.

Full template (click to expand)
markdown
# [Feature Name] — Implementation Plan

## Context

[1-2 paragraphs: what exists today, what is changing, why.]

**Key decisions:**

- [Decision 1 with rationale]
- [Decision 2 with rationale]

**Reference files:**

- [File 1]: [what it contains]
- [File 2]: [what it contains]

**Codebase notes** (non-obvious conventions):

- [Namespace note 1]
- [Column naming note 1]
- [Pattern note 1]

---

## 1. Enums

All in `[path]`. [Backing type, validation approach — match existing convention].

| Enum       | Values                          |
| ---------- | ------------------------------- |
| `EnumName` | `value_1`, `value_2`, `value_3` |

**Design notes:**
[Why these values? Why not others? Computed vs stored state rationale.]

---

## 2. Database Migrations

[Migration syntax convention note.]

### 2.1 `create_[table]_table`

| Column | Type      | Notes |
| ------ | --------- | ----- |
| `id`   | bigint PK |       |
| ...    | ...       | ...   |

Unique: `(col_1, col_2)`

---

## 3. Models

### 3.1 `ModelName`

**Relationships:**

- `belongsTo(OtherModel::class)` via `other_model_id`
- `hasMany(RelatedModel::class)`

**Casts:**

- `status` → `StatusEnum::class`
- `metadata` → `array`

**Computed properties:**

- `isExpired(): bool` — `valid_to !== null && valid_to < now()`

**Scopes:**

- `scopeActive($query)` — `where('status', 'active')`

---

## 4. Services

### 4.1 `ServiceName`

**Methods:**

- `evaluate(Rule $rule): void` — [description]
- `sync(Participant $participant): void` — [description]

**State transitions:**
| From | To | Trigger | Side effects |
|------|----|---------|-------------|
| `pending_approval` | `active` | `approve()` | Broadcast event |
| `active` | `revoked` | Rule re-evaluation | Soft-delete if pending |

---

## 5. Controllers

### 5.1 `ControllerName`

| Method  | Route           | Auth              | Request        | Response             |
| ------- | --------------- | ----------------- | -------------- | -------------------- |
| `index` | `GET /api/...`  | `Policy::viewAny` | —              | Paginated collection |
| `store` | `POST /api/...` | `Policy::create`  | `StoreRequest` | Resource             |

---

## 6. Events & Observers

### 6.1 Observer Triggers

| Trigger   | Model       | Condition        | Action            |
| --------- | ----------- | ---------------- | ----------------- |
| `created` | `ModelName` | `field !== null` | Re-evaluate rules |

---

## 7. Tests

### 7.1 Scenario Coverage

| #   | Scenario                 | Type    | Priority |
| --- | ------------------------ | ------- | -------- |
| 1   | [Happy path description] | Feature | P1       |
| 2   | [Edge case description]  | Unit    | P1       |

---

## Open Questions

- [ ] [Question that needs stakeholder input]
- [ ] [Question that needs codebase verification]

## Gaps (to be resolved)

- [ ] [Known gap 1]
- [ ] [Known gap 2]

Example Prompt Sequence ​

Here is a realistic sequence of prompts that drives the full planning loop:

Prompt 1 — Context gathering:

Read the existing accreditation system: the Accreditation model, its policy,
the broadcast event, the controller, and the audit document. Also read the
HTML prototype at modified/05-rules.html. Summarize: data model, API shape,
authorization pattern, and what the prototype adds beyond what exists today.

Prompt 2 — First draft:

Write an implementation plan for the entitlement system. Structure it as:
Context, Enums, Migrations (with full column definitions), Models
(with relationships and computed properties), Services, Controllers, Tests.
Reference the existing accreditation patterns where applicable.

Prompt 3 — Gap identification:

This plan likely has gaps and missing details. Identify them. Check:
enum completeness, relationship definitions, status transition triggers,
edge cases for the rule engine, namespace accuracy against the codebase,
and column name accuracy against existing migrations.

Prompt 4 — Clarification with options:

Based on the gaps found:
1. Should the rule engine ship in v1 or v2?
2. Clean cutover per festival or data migration?
3. When a pending entitlement's participant stops matching: hard-delete,
   soft-delete, or status change to revoked?

Prompt 5 — Plan hardening:

Update the plan with these decisions. Then cross-reference against the
prototype UI: verify every UI element has a data field, and every data
field appears in the UI. Flag any mismatches.

Prompt 6 — Final review:

Review this implementation plan as if it were a code review. Focus on
logical inconsistencies, missing error handling, undefined edge cases,
and performance concerns.

Verification Checklist ​

Before declaring the plan ready for implementation:

  • [ ] All plan sections present (context, enums, migrations, models, services, controllers, events, tests)
  • [ ] Gap identification completed at least once with findings addressed
  • [ ] Every enum value accounted for in at least one status transition or condition
  • [ ] Every relationship fully defined (type, FK, cascade behavior)
  • [ ] Every file path and namespace verified against the actual codebase
  • [ ] All stakeholder questions answered and incorporated
  • [ ] Sign-off obtained from stakeholder before any code is written

Superpowers Skill Mapping ​

SkillRole in This Playbook
brainstormingPhase 1 context gathering, exploring alternatives
writing-plansPhase 2 first draft, Phase 4-5 plan updates
agentic-researchWhen research findings feed into planning (see Knowledge Synthesis)
executing-plansNot used here — this playbook feeds INTO execution