story-cycle
Delivering story: $ARGUMENTS
Skill metrics: Emit a start event to the activity log:
echo "{\"type\":\"skill\",\"event\":\"start\",\"skill\":\"story-cycle\",\"story\":\"$ARGUMENTS\",\"ts\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" >> docs/sessions/.activity-log.jsonl
Progress tracking: At the start, create a task list for phase tracking:
- "Phase 0+1: Decompose intent, research, plan" — activeForm: "Planning..."
- "Phase 2: Context transition + readiness gate" — activeForm: "Preparing..." — blockedBy: [1]
- "Phase 3: Implement by story type" — activeForm: "Implementing..." — blockedBy: [2]
- "Phase 4: Verify, quality gates, commit" — activeForm: "Verifying..." — blockedBy: [3]
At each phase boundary, mark the current task completed and the next task in_progress.
Process Flow (authoritative — prose below is supporting detail)
START → Phase 0: Intent Decomposition (identify ALL deliverables, mark uncertainties)
→ Size Classification:
→ [TRIVIAL: single-file, <10 lines, no behavioral change]
→ Phase 3-lite: Make change → Run tests → Abbreviated self-review → Commit → DONE
→ [SMALL: single-file, <50 lines, clear AC]
→ Lightweight Phase 1 (skip 1f-1g) → Phase 2 → Phase 3 → Phase 4 → DONE
→ [STANDARD: everything else]
→ Phase 1: Plan Mode (research, identify type, write plan with WHAT/HOW separation)
→ Phase 1c.5: Online Verification → `*** HARD GATE: must print Research Decision block ***`
→ 1c.5+: Dependency Freshness Check (always, if story touches external deps)
→ Phase 1d.7: Story Refinement & Forward Context (gap analysis, cross-story notes)
→ Phase 1f: Clarification Check (ambiguity_scan across 7 categories)
→ Phase 1g: Plan Completeness (verify spec/implementation sections)
→ [User approved?] → NO: Revise → YES: Continue
→ Phase 2: Context Transition + Confidence Gate
→ (prune context, score 5 dimensions, ≥85 proceed, 70-84 clarify, <70 return to Phase 1)
→ Phase 3: Execute by Story Type
→ `*** HARD GATE: TDD ordering — tests BEFORE implementation (Feature/Bug Fix/Refactoring) ***`
→ Web-Assisted Error Recovery (on build/test failure involving external libraries)
→ Bug Fix Web Research (always for bug fix stories — search error patterns first)
→ Phase 4: Verify + Wrap Up
→ Self-review + disaster prevention + ground rules re-check
→ Quality agents dispatched per risk level
→ Security web verification (security-scoped stories — CWE + CVE check)
→ Quality gates `*** HARD GATE: all configured gates must pass ***`
→ UAT generation + sense check (optional — Feature/Bug Fix only)
→ Completion verification (evidence for every AC)
→ Docs + commit
→ [All criteria met?] → NO: Fix + re-verify (max 2 passes) → YES: Report → DONE
Profile-Adaptive Behavior
Read the **Profile:** line from CLAUDE.md to determine the active project profile.
Skip these phases/steps entirely:
- Phase 0a.5 (sprint context loading)
- Phase 1f (clarification check) and Phase 1g (plan completeness check)
- Phase 2 confidence gate scoring — only run objective pre-checks: are planned files read? do existing tests pass?
- Phase 4a quality agent dispatch — use
/quality-checkwith no flags (lean defaults = code only) - Phase 4c (UAT generation)
- Phase 4e capture-outcome and capture-learnings micro-components
Keep these (non-negotiable):
- Phase 0 (intent decomposition and size classification)
- Phase 1 core (1a-1e for STANDARD stories; skip Phase 1 entirely for SMALL — go directly to Build)
- Phase 3 (implementation with TDD for Feature/Bug Fix/Refactoring story types)
- Phase 4b quality-gate-sequence (lint + test from CLAUDE.md Commands)
- Phase 4d (completion verification — all AC met with evidence)
- Phase 4e commit and completion report
Plan is optional for SMALL stories — if the task is clear, go directly to Phase 3 (Build). Safety is unchanged in Lean mode: TDD enforcement, test-before-ship, all hooks active. Lean is less ceremony, not less safe.
Additions beyond standard behavior:
- All 8 phases are mandatory for ALL stories including TRIVIAL — no fast-tracking, no Phase 3-lite
- Phase 4a: dispatch
/quality-check --allfor EVERY story regardless of risk level (all 5 agents + integration-tester) - Coverage delta must be >= 0 (test coverage cannot decrease). Compare before/after in Phase 4b.
- Security audit runs full CWE checklist (all 15 entries) for ALL stories, not just security-scoped ones
- On story completion (Phase 4e), write structured audit entry to
docs/sessions/.audit-log.jsonl:{"type":"audit","story":"<id>","story_type":"<type>","profile":"strict","files_changed":["<paths>"],"agents_run":["<names>"],"gates_passed":true,"coverage_delta":"+N%","ts":"<ISO-8601>"}
Plan Mode for Phases 0-2 (Optional)
For STANDARD stories, consider entering Plan Mode at the start of Phase 0 and remaining in it through Phase 2 (Context Transition). This prevents accidental implementation during the planning phases and provides a natural approval checkpoint.
When to use: Complex stories, high-risk changes, or when the user requests careful planning.
How: Enter Plan Mode before Phase 0. The existing Phase 1 already operates in Plan Mode. Exit Plan Mode after plan approval — just before Phase 2 (Context Transition + Confidence Gate) and Phase 3 (Execution).
CRITICAL — After ExitPlanMode: Plan Mode exit wipes the story-cycle skill from context. After ExitPlanMode, you MUST immediately:
- Read the plan file's
remaining_stepslist — it is your execution checklist - The first step (BOOTSTRAP) tells you to re-read this skill file from Phase 2 onwards
- Continue executing all remaining phases (2 → 3 → 4) — do NOT stop
Phase 0: Intent Decomposition
Run the context-prime micro-component from .claude/prompts/context-prime.md to load project context (intent-aware ordering based on the story description).
0a. Backlog Story Lookup
If $ARGUMENTS matches a story ID pattern (e.g., PROJ-001, S01, E01-S03), search docs/reference/backlog/E*.md for the story:
- Find the story in the epic checklist:
- [ ] ID — Title (Priority, Status) - Find the detailed story section:
### ID: Titlewith inline metadata - Extract metadata: Type, Size, Priority, Status, Dependencies, Affected files, Acceptance criteria, Verification commands
- Use extracted type/size/priority as starting classification (validated in the Size & Risk Classification step)
Definition of Ready check: If the story has status: draft or is missing verification commands, affected files, or out-of-scope section, warn the user:
"This story doesn't meet the Definition of Ready. Missing: [list]. Consider running
/ideateto refine it, or proceed with caution."
Dependency check: If the story has dependencies listed, verify each dependency story has status done in its epic file. If any dependency is not done, warn:
"Dependency [ID] is not complete (status: [status]). This story may be blocked."
Status update: Set the story's status to in-progress in the epic file (both checklist and detail section). Emit a story lifecycle event:
echo "{\"type\":\"story\",\"event\":\"status-change\",\"id\":\"<story-id>\",\"from\":\"<previous>\",\"to\":\"in-progress\",\"story_type\":\"<type>\",\"size\":\"<size>\",\"ts\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" >> docs/sessions/.activity-log.jsonl
0a.5. Sprint Context Load
If on a sprint branch (branch name matches sprint-*), load the sprint spec for decision context:
- Find
docs/sprints/sprint-<number>.md(derive number from branch name) - Extract and hold in context:
- Sprint goal — the primary decision-making context for this story. When implementation choices are ambiguous, the sprint goal breaks the tie.
- Boundaries — out-of-scope items. If this story drifts toward an out-of-scope area, flag it.
- Remaining capacity — count stories by status and size (S=1, M=2, L=4 sessions). Compare against total available sessions to determine sprint health.
- Decisions log — prior decisions in this sprint that may constrain this story's approach.
Sprint-aware risk modifier: If the sprint goal explicitly relates to this story's domain (e.g., sprint goal is "auth integration" and story is about auth), note "sprint-aligned" — this story is goal-critical and deserves full depth. If the story is peripheral to the sprint goal (e.g., sprint goal is "auth integration" but story is "update error messages"), note "sprint-peripheral" — keep scope minimal.
Capacity check: If remaining stories (🔲 + 🔄) require more sessions than remain in sprint capacity:
"⚠️ Sprint capacity at risk — [N] stories remaining ([M] sessions needed), [K] sessions available. Consider carrying over the lowest-priority ⏭️ story."
M/L story session guidance: If this story is sized M or L, suggest the three-session pattern:
"This is a [M/L] story (~[2-3/3-5] sessions). Consider: Session 1 = Phase 0-1 (plan + approve), Session 2 = Phase 3 (implement), Session 3 = Phase 4 (verify + commit). Use
/handoffat natural break points to preserve context."
This is guidance, not enforcement — the developer may complete it in fewer sessions.
0b. PRD Scope Guard
If docs/reference/PRD_SUMMARY.md exists, load Section 7 (scope boundaries) and Section 3 (success criteria). Use scope boundaries as guard rails throughout implementation — if the story drifts toward a stated non-goal or violates an implementation boundary, flag it. Use success criteria to verify the story contributes to measurable product outcomes.
0b.5. Discovery Context Loading
0c. Scope Analysis
Before any exploration, decompose the user's request. Apply the scope_analysis reasoning tool from references/reasoning-tools.md:
- List ALL distinct outcomes the user expects (implementation, tests, docs, PR, etc.)
- For each: identify type, files likely affected, complexity (1-5), and dependencies
- Flag any deliverable rated complexity ≥4 as candidate for splitting
- If the request contains multiple independent stories, suggest splitting and confirm scope
- Confirm the full scope with the user before proceeding to planning
This prevents missing later parts of compound requests (e.g., "refactor auth AND add rate limiting AND create a PR").
Size & Risk Classification (Fast-Track Gate)
After Phase 0 decomposition, classify by size then risk:
Size classification — use the story's frontmatter size field as starting point (if the story came from the backlog via /ideate). Validate against actual scope after decomposition — reclassify if the scope doesn't match:
| Size | Criteria | Default Workflow |
|---|---|---|
| TRIVIAL | Single file, <10 lines changed, no behavioral change (typo, config, comment) | Phase 3-lite (below) |
| SMALL | One clear change following an existing pattern | Lightweight Phase 1 (skip 1f, 1g) → Phase 2 → Phase 3 → Phase 4 |
| STANDARD | One coherent feature, requires a plan | Full workflow (unchanged) |
| LARGE | One coherent mechanism whose parts interlock and cannot be meaningfully tested in isolation | Full workflow + integration test pass before Phase 4 |
| XL | A complete subsystem with a single conceptual center | Full workflow, staged implementation — build and verify one part of the mechanism at a time, then a full-suite pass before Phase 4 |
Sizing is by conceptual cohesion, not file count — see ../ideate/references/story-template.md.
Do not reclassify a LARGE or XL story downward, or split it, merely because it touches many files.
Split only when it spans genuinely unrelated topics.
Adaptive calibration: If docs/sessions/.activity-log.jsonl contains 10+ skill execution records, check historical data for this story type/scope:
- If stories matching this type consistently required full workflow despite SMALL classification → escalate to STANDARD
- If STANDARD stories in this area consistently completed without issues → note as candidate for lightweight treatment
- Log calibration adjustment in plan for transparency:
Depth calibration: [escalated/standard/downgraded] based on [N] prior executions
Sprint context modifier (from Phase 0a.5): If sprint context was loaded, apply:
- Sprint-aligned stories: maintain or escalate depth — these are goal-critical, quality matters most
- Sprint-peripheral stories: consider downgrading depth if sprint capacity is tight — keep scope minimal, defer stretch goals to next sprint
- Log:
Sprint alignment: [aligned/peripheral] — sprint goal: "[goal]"
Risk classification (apply risk_classification reasoning tool from references/reasoning-tools.md):
Score domain risk, integration surface, and reversibility (1-3 each). Sum determines risk level:
| Low risk (3-4) | Medium risk (5-6) | High risk (7-9) | |
|---|---|---|---|
| TRIVIAL | Phase 3-lite | Phase 3-lite + full test suite | Reclassify as SMALL |
| SMALL | Lightweight Phase 1 | Standard workflow | Standard + mandatory security-audit |
| STANDARD | Standard workflow | Standard + all quality agents | Standard + all agents + architecture-check |
| LARGE | Standard + integration tests | Standard + all quality agents + integration tests | Standard + all agents + architecture-check + security-audit |
| XL | Staged build + all quality agents | Staged build + all agents + architecture-check | Staged build + all agents + architecture-check + security-audit + integration-tester |
SMALL Story Checklist
SMALL stories skip Phase 1f (clarification check) and 1g (plan completeness) only. All other phases are REQUIRED — do NOT skip them because the story feels simple:
- Phase 0: Intent decomposition
- Phase 1: Lightweight analysis + plan (includes 1c.5 Research Decision — MANDATORY output) →
*** HARD GATE: user approval *** - Phase 2: Context transition + readiness gate (5 objective checks) →
*** HARD GATE *** - Phase 3: Implementation (TDD by story type)
- Phase 4: Self-review + quality gates + completion verification with evidence →
*** HARD GATE ***
Why this matters: Testing proved that SMALL stories get their quality gates skipped when the agent optimizes for speed. The code may be fine, but the process guarantees are missing. Every gate exists for a reason.
Phase 3-lite (TRIVIAL only)
- Make the change
- Run tests (if test command configured)
- Abbreviated self-review: Does the diff match intent? Any unintended side effects?
- Commit with conventional format
- Print completion report
Phase 1: Story Analysis (Plan Mode)
Enter plan mode to research and design the approach.
Pre-flight: Run the discover-commands micro-component from .claude/prompts/discover-commands.md to extract configured commands (test, lint, format, build, typecheck) from CLAUDE.md. Run the verify-clean-git-state micro-component from .claude/prompts/verify-clean-git-state.md to confirm no uncommitted changes and correct branch.
1a. Identify Story Type
Determine the story type from the description, backlog entry, or user input:
| Type | Indicators | Approach |
|---|---|---|
| Feature | New user-facing capability, "As a user..." | TDD: RED-GREEN-REFACTOR |
| Bug Fix | Defect, "fix", error report, reproduction steps | Reproduce → Test → Fix → Verify |
| Refactoring | "Refactor", "restructure", no behavior change | Characterization tests → Refactor → Verify |
| Spike/Research | "Investigate", "evaluate", "prototype", time-boxed | Explore → Document → Decide |
| Infrastructure | CI/CD, tooling, build, config, environment | Plan → Implement → Smoke Test |
| Testing | "Add tests", "coverage", "E2E tests" | Design strategy → Generate → Validate |
| Documentation | "Document", "write docs", "update README" | Gather → Generate → Review |
| Security | "Harden", "audit", "vulnerability", "encrypt" | Threat model → Implement → Audit |
| Performance | "Optimize", "benchmark", "speed up", "latency" | Baseline → Optimize → Benchmark |
| Skill/Tooling | "Create skill", "add tool", "developer experience" | Design → Build → Document |
| Review | Phase transition, walkthrough, assumption validation, direction decision | Interactive walkthrough → Document findings → Decide direction |
If the story type is ambiguous after checking indicators, ask the user using AskUserQuestion with description fields explaining workflow implications:
- Feature — description: "Full TDD (RED-GREEN-REFACTOR). AC in Given/When/Then. Heaviest testing."
- Bug Fix — description: "Reproduce first, then fix. Creates regression test. Lighter planning."
- Refactoring — description: "No behavior change. Characterization tests first, then restructure."
- Spike/Research — description: "Time-boxed exploration. Output is a decision doc, not code. No TDD."
- Infrastructure — description: "CI/CD, tooling, config. Smoke test verification. Lighter AC."
- Testing — description: "Pure test code. Design strategy, generate tests, validate coverage."
- Documentation — description: "Non-code deliverable. Gather, generate, review cycle."
- Security — description: "Threat model first. Mandatory security-audit agent. CWE checklist."
- Performance — description: "Baseline measurement required. Optimize, then benchmark."
- Skill/Tooling — description: "Developer experience. Design, build, document pattern."
1b. Codebase Exploration (Grep-First)
Use the grep-first-explore micro-component from .claude/prompts/grep-first-explore.md to efficiently identify relevant files before reading them. The number of exploration streams scales with story size:
| Size | Exploration Strategy |
|---|---|
| TRIVIAL | Skip Phase 1b entirely (already fast-tracked) |
| SMALL | Single grep-first pass: extract terms from the story, run parallel Grep calls, read top 5-7 files |
| STANDARD | Grep-first pass + 1-2 codebase-explorer agents for broader context (architecture focus, test focus) |
| STANDARD + High-risk | Grep-first pass + 2 agents + security-focused grep (search for auth patterns, input validation, trust boundaries in affected modules) |
Grep-first process:
- Extract key terms from the story description (function names, module names, API endpoints, error messages)
- Run parallel Grep calls: imports/usage, definitions, and test references
- Rank files by match density, select top 5-10
- If fewer than 3 files match (greenfield or entirely new feature): fall back to codebase-explorer agents
If sub-agents are available (STANDARD stories): Use the wave-execution micro-component from .claude/prompts/wave-execution.md to dispatch codebase-explorer agents in parallel with focused prompts:
- Implementation focus: "Find source files that implement or relate to: [story description]."
- Test focus: "Find test files, test utilities, and fixtures related to: [story description]."
Prior learnings check: Search docs/solutions/ for prior learnings on affected modules. Grep frontmatter fields (tags, module, component) for terms from the story. Read matching solution documents to avoid rediscovering known patterns or gotchas.
Collect all results. Deduplicate and synthesize into a focused file list (10-15 files max). Read ONLY the files identified. If during implementation you need additional files, read them then — don't front-load.
If sub-agents are NOT available: Use grep-first only — it's efficient enough for most stories without agent support.
Architecture rules check: If docs/architecture/ARCHITECTURE.md exists and is non-template, read ONLY the Module Map (Dependency Rules subsection) and Known Landmines sections. For each module this story touches, note any applicable rules or landmines in the exploration summary. This avoids wrong-direction implementations and repeat mistakes.
Debt register cross-reference (skip for TRIVIAL stories): If docs/technical-debt.md has active items, grep its Location fields for files identified in exploration. If any explored files appear in active debt items:
- Low severity + Hours effort in files being modified → suggest addressing as a "boy scout" improvement alongside the story (leave code better than you found it). Note: do not expand story scope — only fix if genuinely trivial.
- Higher severity or effort → note in exploration summary for awareness ("TD-NNN affects this file"), but do not expand scope. The debt register tracks these for future sprints.
1c. Research Codebase
- Deep-read the files identified in step 1b
- Understand patterns, conventions, and existing tests in the area
- If
docs/context/system-patterns.mdexists and is populated (not template-only), check it against the files being touched:- Which implementation patterns apply to this story's scope? (Note reference files to follow.)
- Does the area's error handling match the documented strategy? (Flag divergence.)
- What testing conventions apply? (Test naming, fixture approach, mock strategy.)
- Is there an implementation recipe for the type of entity this story adds? (Follow it.) Note applicable patterns in the plan's "patterns to follow" section. If the story will introduce a NEW pattern not yet documented, note that for post-implementation update.
- Identify files to modify and files to create
- Check for
CLAUDE.mdfiles in the target directory and parent directories — these contain module-specific patterns and conventions that supplement global CLAUDE.md
1c.5. Online Verification
Step 1 — Classify research requirement:
| Story type | Research requirement | Depth |
|---|---|---|
| Spike/Research | MANDATORY | DEEP |
| Security | MANDATORY | STANDARD |
| Bug Fix | MANDATORY (error pattern search) | QUICK |
| All other types | Conditional (evaluate 3 signals below) | Auto-select |
Step 2 — For conditional stories, evaluate these three signals:
| Signal | Research needed | Skip research |
|---|---|---|
| Risk level | High-risk topics: security, payments, auth, external APIs, new dependencies | Low-risk internal changes |
| Local context strength | Weak: unfamiliar library, no existing patterns, no prior solutions in docs/solutions/ |
Strong: established patterns, existing tests, prior solution docs cover this area |
| Uncertainty level | Approach is unclear, multiple valid strategies exist | Approach is obvious from codebase conventions |
Decision: If ANY signal points to "research needed" → proceed. Otherwise → skip with justification.
Step 3 — Execute research (when proceeding):
Compose the deep-research methodology (.claude/prompts/deep-research.md) at the depth from Step 1:
| Story context | Research depth |
|---|---|
| Spike/Research | DEEP |
| Security, new external dependencies | STANDARD |
| Bug fix, standard story with research signals | QUICK |
The research engine handles: query decomposition, parallel subagent dispatch, source evaluation, reflection-based compression. See .claude/prompts/deep-research.md.
For Spike/Research stories specifically: Generate sub-questions from the spike's questions. Research current state of reference technologies, recent publications, competitor approaches, and relevant patterns. All claims MUST cite sources with URLs. Training data alone is NEVER sufficient for spikes.
Step 4 — Print the Research Decision block (MANDATORY):
## Research Decision
**Story type:** [type from 1a]
**Research requirement:** [MANDATORY / Conditional]
**Decision:** [PERFORMED at [depth] / SKIPPED]
**Justification:** [why — for skips: which signals were evaluated and why all pointed to skip]
### Findings (if research was performed)
- [Key finding 1 with source URL]
- [Key finding 2 with source URL]
- [Finding N...]
**Research confidence:** [high/medium/low]
**Impact on plan:** [how findings affect the approach — or "No findings that change approach"]
This block is included in the plan and feeds into Phase 2b readiness checks.
Record findings:
- If official docs reveal a deprecation or API change: note it in the plan as a "Doc Finding" and update relevant reference docs after implementation
- If a better approach is found: incorporate it into the plan
- If everything checks out: note "Online verification: APIs confirmed current" and move on
1c.5+. Dependency Freshness Check (Always-On for External Deps)
Trigger: The story creates, modifies, or directly calls any external dependency (not internal modules). This runs even when the main 1c.5 research gate was skipped.
Quick check (~30 seconds):
- Identify the external libraries the story will use (from plan or codebase grep)
- For each,
WebSearchfor:"<library> <pinned-version> deprecation OR breaking change OR CVE"(batch into 1-2 searches) - If a result looks relevant,
WebFetchthe specific page to confirm
Outcomes:
| Finding | Action |
|---|---|
| No issues | Note "Dep freshness: all clear" in plan, move on |
| Deprecation notice | Note in plan, use recommended replacement API |
| Known CVE | Flag to user immediately — may change story scope |
| Breaking change in newer version | Note in plan for awareness; no action if pinned version is stable |
Skip when: Story only touches internal code with no external library calls.
1d. Define Required Skills
Determine which skills benefit this story. If the story metadata already defines skills, use those. Otherwise select from:
| Skill | Load When |
|---|---|
/code-quality |
Feature, refactoring, infrastructure stories |
/test-validator |
Feature, bug fix, refactoring, testing stories |
/security-audit |
Security stories, code touching auth/credentials/data |
Intent-based security activation: If the story touches user input, API endpoints, database queries, file uploads, sessions, or network calls, treat the security rule as active for ALL files in this story — not just files matching security path patterns. Note this in the plan: Security scope: story-wide (intent-based).
1d.5. Discovery Gate (Facilitator Check)
Before writing the plan, check: do you have enough information to write a plan without assumptions?
- If YES: proceed to 1d.7
- If NO: present the 3 most critical unknowns to the user as focused questions with 2-4 answer options each. Integrate answers, then proceed to 1d.7.
Red flag: If you're about to write "Assuming X..." in the plan, STOP — ask the user about X instead. Facilitate discovery; don't generate assumptions.
1d.7. Story Refinement & Forward Context
With codebase understanding from 1b-1c, pressure-test the story before planning:
- Map to application: For each acceptance criterion, identify the concrete components, endpoints, services, and modules involved. If a criterion is vague, make it specific to the project's architecture.
- Gap analysis: What's needed for this to work that the story doesn't mention? Check if gaps are covered by other TODO stories in the epic.
- Small uncovered gap → propose expanding this story's AC (confirm with user)
- Large uncovered gap → flag it, don't silently absorb scope
- Forward context: Check TODO stories in the same epic that depend on or relate to this one. If research clarifies anything for them (API shape they'll consume, patterns to follow, components to reuse), add a brief
> Context from [this story]: ...note to those stories in the epic file.
Summarize: what was refined, what gaps were found, what forward context was added.
1e. Write the Plan
Keep the plan concise — under 50 lines. Save complex plans to docs/plans/ for persistence across compaction. Reference files by path rather than inlining content.
Follow the plan template structure in references/plan-template.md. The plan MUST have two distinct sections:
- Specification (WHAT/WHY) — User-visible behavior changes, acceptance criteria in Given/When/Then format. NO file paths, NO function names, NO framework references.
- Implementation Approach (HOW) — Files to modify/create, patterns to follow, technical strategy with rationale.
For any requirement where the user's intent is ambiguous or multiple valid interpretations exist, insert [NEEDS CLARIFICATION: specific question] in the plan. Maximum 3 markers before triggering a hard gate for user input.
Apply the test_strategy_selection reasoning tool for the testing section.
1f. Clarification Check
Apply the ambiguity_scan reasoning tool from references/reasoning-tools.md. Scan the plan for assumptions across 7 categories (scope, data model, UX, non-functional, integration, edge cases, constraints).
1g. Plan Completeness
Apply the plan_completeness reasoning tool from references/reasoning-tools.md to verify:
- All deliverables from Phase 0 have implementation steps
- All acceptance criteria have verification approaches
- Specification section contains zero implementation details
- Implementation section traces to every acceptance criterion
- Research Decision block is present (from Phase 1c.5) — if missing, HALT and go back to 1c.5
CRITICAL — Story-Cycle Context Preservation:
After plan approval, context resets and only the plan survives. The plan MUST start with a "Story-Cycle Context" section so Claude Code knows what workflow it's in and what steps remain. Update the phase and stepsCompleted fields at each phase transition — this enables true mid-workflow resume if the session is interrupted or context compacts.
Use this exact format at the TOP of the plan:
## Story-Cycle Context
workflow: story-cycle
storyType: "[from Phase 1a]"
sprint_number: [N]
sprint_goal: "[from Phase 0a.5 — one sentence]"
sprint_alignment: "[aligned/peripheral — from Size & Risk Classification]"
phase: "plan-approved — proceed to Phase 2 Context Transition + Confidence Gate"
stepsCompleted: [0-intent, 0a5-sprint-context, 1a-type, 1b-discovery, 1c-research, 1c5-online-verify, 1d-skills, 1d5-discovery-gate, 1d7-refinement, 1e-plan, 1f-clarification, 1g-completeness, 1h-depth-check]
remaining_steps:
- "BOOTSTRAP (do this FIRST): Read .claude/skills/story-cycle/SKILL.md starting from '## Phase 2: Context Transition + Confidence Gate' to reload the full story-cycle workflow. You are mid-workflow — planning is done, implementation phases remain. Do NOT stop after reading the plan."
- "Phase 2 — CONTEXT + READINESS GATE (HARD-GATE): Prune context (keep plan + paths + gotchas, discard bulk). Read .claude/prompts/confidence-gate.md. Verify 5 objective checks (files read, tests baseline, pattern match, scope bounded, no conflicts). All pass → proceed. Any fail → address gap. Output the check results."
- "Phase 3 — IMPLEMENT (TDD HARD-GATE for Feature/Bug Fix/Refactoring): Read .claude/skills/story-cycle/references/story-types.md for [storyType] execution steps. Load relevant sections of docs/reference/CODING_STANDARDS.md and docs/reference/TESTING_STRATEGY.md. Re-read all target files from plan before editing. CRITICAL: For Feature/Bug Fix/Refactoring stories, write and run a failing test BEFORE writing implementation code. Show test failure output. Only then write implementation. Follow story-type methodology (TDD: RED → GREEN → REFACTOR)."
- "Phase 4a — SELF-REVIEW (HARD-GATE): Read .claude/skills/story-cycle/references/self-review.md — complete ALL checklist items including ground rules re-check. Read .claude/skills/story-cycle/references/disaster-prevention.md — check for wheel reinvention, spec drift, integration wiring, file structure, regression surface, architecture doc staleness. Dispatch quality skills per risk level (Low: code-quality+test-validator+security-audit-lightweight, Medium: +security-audit-full, High: +architecture-check). At Medium+ risk, also dispatch integration-tester native agent (.claude/agents/integration-tester.md) with test commands + acceptance criteria for independent dynamic verification. If ANY item fails → fix in Phase 3 before proceeding."
- "Phase 4b — QUALITY GATES (HARD-GATE): Run the project's quality command (from CLAUDE.md Commands section: lint → typecheck → test). Stop on first failure, fix, re-run. Show passing output in the current turn — do NOT claim tests pass without evidence. Do NOT proceed until all gates pass."
- "Phase 4b.5 — LAUNCH & VERIFY (optional, Feature/Bug Fix only): Check CLAUDE.md Commands for a dev command. If one exists AND the story type is Feature or Bug Fix: offer to run it so the user can visually verify. Run in background, show whatever output it produces (URLs, status, CLI output — do NOT assume localhost). Ask: 'Want to verify it visually?' If user declines or no dev command exists, skip. Also skip for Spike, Infrastructure, Documentation, Testing, Refactoring, Performance, Skill/Tooling, Review stories."
- "Phase 4c — UAT (optional, Feature/Bug Fix only): If project has UAT directory, generate UAT test case + sense check per Phase 4c/4c.1 in SKILL.md. Skip for Spike/Research, Infrastructure, Documentation, Testing, Refactoring, Performance, Skill/Tooling stories. Also skip if no UAT directory exists."
- "Phase 4d — COMPLETION VERIFICATION (HARD-GATE): Re-read original AC from plan. For EACH criterion, provide concrete evidence (test output, file:line, command output). Max 2 extra loop passes if gaps found. Do NOT print completion report until every AC has evidence."
- "Phase 4e — DOCS + COMMIT: (1) Update epic file (mark story DONE in heading, check all AC boxes). (2) Update BACKLOG_INDEX.md (increment Done, decrement TODO for epic row, update Total row). (3) Update docs/progress.md (story status ✅). (4) Update sprint spec (docs/sprints/sprint-N.md): set story Status to ✅, Session column to today's date. (5) Update CLAUDE.md if it contains backlog counts or epic progress that changed. (6) Emit skill metrics event to docs/sessions/.activity-log.jsonl. (7) Invoke /commit skill. Do NOT merge or create PR — that is sprint-end."
- "COMPLETION REPORT: Print story, type, approach, files modified, test counts, commit hash, verification evidence. Include Next Steps section with concrete commands. Determine the next story from the sprint spec (docs/sprints/sprint-N.md) or epic file — find the first story with status TODO/ready. Format: '**Next steps:**\n1. Clear your context window: `/clear`\n2. Start the next story: `/story-cycle [next-story-id]`' — always use the actual story ID. If no stories remain, suggest `/sprint-end` instead."
error_recovery: ".claude/skills/story-cycle/references/error-recovery.md"
skill_file: ".claude/skills/story-cycle/SKILL.md"
File Context (accumulates across compactions)
<files-read>
[List all files read during planning — one path per line]
</files-read>
<files-modified>
[Update as files are modified during execution — one path per line]
</files-modified>
When context compacts, MERGE new file paths into these lists — never discard previous entries.
When you exit Plan Mode (ExitPlanMode) during a story-cycle, you are NOT done. Planning is only Phase 1 of 4. After Plan Mode exits, you MUST:
- Read
.claude/skills/story-cycle/SKILL.mdstarting from## Phase 2: Context Transition + Confidence Gate - Execute the
remaining_stepsfrom the plan's Story-Cycle Context block IN ORDER - Do NOT report completion until Phase 4d passes with evidence for every acceptance criterion
The plan approval is a checkpoint, not the finish line. If you stop after Plan Mode, the story is incomplete — no code was written, no tests were run, nothing was committed.
For complex stories, use ultrathink to reason through architectural decisions before writing the plan.
1h. Depth Check (Optional)
Before presenting for approval, offer the user a depth option if the plan contains areas with complexity ≥4 or unresolved uncertainties:
- [D] Deep dive — Explore design alternatives for uncertain areas using the
depth_explorationreasoning tool and elicitation techniques fromreferences/elicitation-techniques.md - [C] Continue — Plan is ready for approval as-is
If [D]: apply the most relevant elicitation technique, integrate findings into the plan, then present for approval. If [C] or no uncertainties exist: proceed directly to approval.
Present the plan for user approval.
Phase 2: Context Transition + Confidence G
…(truncated)