| name | prp-plan |
| description | Create a comprehensive implementation plan by analyzing the codebase, discovering patterns, and producing a step-by-step actionable plan document. |
| metadata | {"short-description":"Create implementation plan"} |
Agent Mode Detection
If your input context contains [WORKSPACE CONTEXT] (injected by a multi-agents framework),
you are running as a sub-agent. Apply these optimizations:
- Skip Phase 0.5 (toolchain detection) — if the context includes a
toolchain JSON
block with runner/commands, use those directly instead of re-detecting.
- Skip CLAUDE.md reading — the parent session already loaded project conventions
into context. Do not re-read them.
- Skip Directory Discovery — the parent agent already explored
the codebase. Focus on targeted file reads for pattern extraction instead.
- Proceed directly to Phase 1 with the feature description from context.
All other phases (codebase pattern extraction, research, plan generation) run unchanged —
these are where quality comes from.
PRP Plan — Create Implementation Plan
Input
Feature description or path to PRD file: $ARGUMENTS
Format: <feature description | path/to/prd.md> [--fast] [--no-interact]
Objective
Transform the input into a battle-tested implementation plan through systematic codebase exploration, pattern extraction, and strategic research.
- PLAN ONLY — no code written
- CODEBASE FIRST, RESEARCH SECOND — solutions must fit existing patterns
- Thorough Exploration — deep codebase search before any external research
- Read project conventions file (CLAUDE.md, AGENTS.md, .cursorrules, etc.)
Context: Directory Discovery
Run these to understand project structure:
ls -la
ls -la */ 2>/dev/null | head -50
- Identify project type from config files (package.json, pyproject.toml, Cargo.toml, go.mod, etc.)
- Do NOT assume
src/ — alternatives: app/, lib/, packages/, cmd/, internal/, pkg/
Phase 0: DETECT — Input Type Resolution
Parse flags first (remove from input before type detection):
| Flag | Effect |
|---|
--fast | Fast-track mode (lighter analysis) |
--no-interact | Never ask questions — use best judgment |
--package <name> | Scope to a specific monorepo package (e.g., --package api). Sets MONOREPO_PACKAGE. |
| Input Pattern | Type | Action |
|---|
Ends with .prd.md | PRD file | Parse PRD, select next phase |
Ends with .md + "Implementation Phases" | PRD file | Parse PRD, select next phase |
| File path that exists | Document | Read and extract feature description |
| Free-form text | Description | Use directly as feature input |
| Empty/blank | Conversation | Use conversation context as input |
If PRD File Detected:
- Read the PRD file — if file does not exist, STOP: "PRD file not found at
{path}. Verify the path and try again."
- Parse the Implementation Phases table — find rows with
Status: pending. If the PRD has no "Implementation Phases" table (no table with Status/Phase columns), STOP: "PRD file has no Implementation Phases table. Add a phases table with Status column, or use free-form text input instead."
- Check dependencies — only select phases whose dependencies are
complete
- Select the next actionable phase:
- First pending phase with all dependencies complete
- If multiple candidates with same dependencies, note parallelism opportunity
- If NO phases are actionable (all pending phases have incomplete dependencies): STOP — "No actionable phases found. All pending phases have unmet dependencies. Check the PRD phases table for circular or unresolvable dependencies."
- Extract phase context:
PHASE: {phase number and name}
GOAL: {from phase details}
SCOPE: {from phase details}
SUCCESS SIGNAL: {from phase details}
PRD CONTEXT: {problem statement, user, hypothesis from PRD}
- Report selection to user:
PRD: {prd file path}
Selected Phase: #{number} - {name}
{If parallel phases available:}
Note: Phase {X} can also run in parallel (in separate worktree).
Proceeding with Phase #{number}...
If Free-form or Conversation Context:
Proceed directly to Phase 1 with the input as feature description.
GATE: If requirements are AMBIGUOUS:
- Default: STOP and ASK for clarification.
- If
--no-interact: Do NOT ask. Use best judgment, state assumptions in "## Assumptions" section.
PHASE_0_CHECKPOINT:
Phase 0.5: DETECT — Project Toolchain
0.5.1 Identify Package Manager
| File Found | Package Manager | Runner |
|---|
bun.lockb | bun | bun / bun run |
pnpm-lock.yaml | pnpm | pnpm / pnpm run |
yarn.lock | yarn | yarn / yarn run |
package-lock.json | npm | npm run |
pyproject.toml | uv/pip | uv run / python |
Cargo.toml | cargo | cargo |
go.mod | go | go |
Priority: bun > pnpm > yarn > npm.
Fallback: If no lock file → placeholder with WARNING.
0.5.2 Identify Validation Scripts
Read package.json (or equivalent) for exact script names:
| Category | Common Names | Example Command |
|---|
| Type checking | type-check, typecheck, tsc | bun run type-check |
| Linting | lint, lint:fix | bun run lint |
| Testing | test, test:unit, test:integration | bun test |
| Building | build, compile | bun run build |
0.5.3 Store as Plan Metadata
Runner: {detected runner}
Type Check: {runner} run {script-name}
Lint: {runner} run {script-name}
Test: {runner} {test-command}
Build: {runner} run {script-name}
0.5.4 Detect Monorepo
Check for monorepo configuration files at project root:
| File Found | Monorepo Type |
|---|
pnpm-workspace.yaml | pnpm workspaces |
turbo.json | Turborepo |
nx.json | Nx |
lerna.json | Lerna |
root package.json with "workspaces" field | yarn/npm workspaces |
If --package flag provided but NO monorepo config detected:
WARNING: --package {name} specified but no monorepo configuration found (no pnpm-workspace.yaml, turbo.json, nx.json, lerna.json, or workspaces field in package.json). Ignoring --package flag — proceeding as single-package project.
If monorepo detected:
-
Discover workspace directories — read the actual workspace config:
cat pnpm-workspace.yaml
cat package.json | jq '.workspaces'
ls -d packages/*/ apps/*/ libs/*/ services/*/ modules/*/ 2>/dev/null
-
List available packages from discovered workspace directories:
find {workspace-dirs} -maxdepth 2 -name "package.json" -exec dirname {} \;
-
Determine target package:
| Condition | Action |
|---|
--package <name> flag provided | Use that package. Set MONOREPO_PACKAGE = <name> |
| Feature description mentions a specific package | Auto-detect. Confirm with user (unless --no-interact) |
| Neither | Ask user to specify (unless --no-interact → scope to root/all) |
-
Resolve package path from discovered workspaces:
PACKAGE_DIR=$(find {workspace-dirs} -maxdepth 2 -name "package.json" \
-exec grep -l "\"name\".*\"$MONOREPO_PACKAGE\"" {} \; | head -1 | xargs dirname)
Verify the directory exists. If not → STOP with error listing available packages.
-
Scope toolchain commands (override 0.5.3) — syntax varies by monorepo tool:
| Monorepo Type | Scoped Command Pattern | Example (package: api, script: lint) |
|---|
| pnpm workspaces | pnpm --filter {pkg} run {script} | pnpm --filter api run lint |
| Turborepo | turbo run {script} --filter={pkg} | turbo run lint --filter=api |
| Nx | nx run {pkg}:{script} | nx run api:lint |
| Lerna | lerna run {script} --scope={pkg} | lerna run lint --scope=api |
| yarn workspaces | yarn workspace {pkg} run {script} | yarn workspace api run lint |
| npm workspaces | npm run {script} -w {pkg} | npm run lint -w api |
Generate scoped commands for plan metadata:
Type Check: {scoped command for type-check}
Lint: {scoped command for lint}
Test: {scoped command for test}
Build: {scoped command for build}
-
Store monorepo metadata:
Monorepo: {type}
Package: {MONOREPO_PACKAGE}
Package Dir: {PACKAGE_DIR}
Monorepo Tool: {pnpm|turbo|nx|lerna|yarn|npm}
If no monorepo detected and no --package flag: Skip this section entirely. No impact on workflow.
PHASE_0_5_CHECKPOINT:
Phase 1: PARSE — Feature Understanding
Extract from input:
- Core problem being solved
- User value and business impact
- Feature type: NEW_CAPABILITY | ENHANCEMENT | REFACTOR | BUG_FIX
- Complexity: LOW | MEDIUM | HIGH
- Affected systems list
Complexity Triggers (determines conditional sections):
- LOW: Skip Technical Design, skip expanded Testing Strategy
- MEDIUM: Include Technical Design if API/DB changes; include Integration Tests
- HIGH: Include ALL Technical Design sub-sections; include full Testing Strategy with perf benchmarks
Testing Decision Gates
| Flag | Condition | Effect |
|---|
NEEDS_INTEGRATION_TESTS | Complexity ≥ MEDIUM AND crosses service boundary | Include Integration Tests section |
NEEDS_PERF_BENCH | Involves DB queries, API endpoints, or data processing | Include Performance Benchmarks |
SECURITY_SENSITIVE | Handles user input, auth, data storage | Include security edge cases |
Formulate user story:
As a <user type>
I want to <action/goal>
So that <benefit/value>
Fast-track Mode (--fast)
When --fast flag provided:
- Skip: Phase 3 (Research), Phase 4.2 (Technical Design), Phase 5 (Design UX)
- Compact plan: Summary, Metadata (with runner), Files to Change (with Insert At), Integration Points, Tasks (max 5), Validation Commands (pre-filled), Confidence Score
- No: UX diagrams, Mandatory Reading, Patterns to Mirror, expanded Testing Strategy, Risks table
- Add plan metadata:
Mode: fast-track
Warning (complexity mismatch): If complexity > LOW detected:
WARNING: Feature appears too complex for fast-track. Detected: {reason}.
Consider running without --fast for full planning.
Proceeding with fast-track anyway...
PHASE_1_CHECKPOINT:
Phase 2: EXPLORE — Codebase Intelligence
If monorepo with MONOREPO_PACKAGE set: Focus exploration on {PACKAGE_DIR} first, then check shared packages (e.g., packages/shared/, packages/common/). Only explore other packages if cross-package integration is needed.
2.0 Pre-Exploration — ck-first (zero LLM cost)
Before spawning Explore agents or reading files, gather structured codebase context via code-knowledge MCP tools (if available):
-
Check ck availability: Verify the target repo is indexed by running ck_query or checking ck repos via Bash.
- If repo IS indexed → proceed with steps 2-4
- If ck tools NOT available or repo NOT indexed → skip directly to step 2.1
-
Architecture overview: Call ck_onboard("{repo_name}")
- Returns: directory tree, entry points, dependencies, modules
- Use this to understand repo structure before reading any files
-
Targeted search: Call ck_query("{repo_name}", "{feature keywords from Phase 1}")
- Returns: relevant files ranked by name/signature/doc match
- Use results to scope file reads in step 2.1 to ONLY these files
-
Blast radius (if modifying existing code): Call ck_impact("{repo_name}", "{symbol_to_change}")
- Returns: all callers/importers of the target symbol
- Use to identify integration points and test targets
ck results reduce the Explore scope: Instead of reading 15-20 files, read only 3-5 files identified by ck. Pass ck results as pre-loaded context to any Explore agent spawned in step 2.1.
2.1 Codebase Exploration
Thoroughly explore the codebase to discover (scope to ck-identified files when available):
- Similar implementations with file:line references
- Naming conventions with actual examples
- Error handling patterns — how errors are created, thrown, caught
- Logging patterns — logger usage, message formats
- Type definitions — relevant interfaces and types
- Test patterns — test file structure, assertion styles
- Integration points — where new code connects to existing
- Dependencies — relevant libraries already in use with versions
- Integration wiring — where do similar features get called from? What imports/registers them?
- Insertion positions — for files that need UPDATE, where should new code be inserted? (line number, after which section)
Document discoveries in table format:
| Category | File:Lines | Pattern Description | Code Snippet |
|---|
| NAMING | src/features/X/service.ts:10-15 | camelCase functions | export function createThing() |
| ERRORS | src/features/X/errors.ts:5-20 | Custom error classes | class ThingNotFoundError |
| LOGGING | src/core/logging/index.ts:1-10 | getLogger pattern | const logger = getLogger("domain") |
| TESTS | src/features/X/tests/service.test.ts:1-30 | describe/it blocks | describe("service", () => { |
| TYPES | src/features/X/models.ts:1-20 | Drizzle inference | type Thing = typeof things.$inferSelect |
Explore Fallback (when <3 codebase patterns found)
If fewer than 3 relevant patterns found, expand search:
- Analogous patterns: Similar concepts in different domains within codebase
- Official library examples: Docs of libraries in package.json (match versions)
- Framework conventions: Framework-standard patterns
Tag each source:
SOURCE: codebase (file:line) — primary, highest trust
SOURCE: analogous (file:line) — similar concept, different domain
SOURCE: external ({library} v{version} docs) — official documentation
SOURCE: convention ({framework} standard) — framework convention
Token Budget: Max 20K tokens for exploration (typically 5-8K when ck pre-loads context). If hitting limit, document "Exploration incomplete."
PHASE_2_CHECKPOINT:
Phase 3: RESEARCH — External Documentation
ONLY AFTER Phase 2 is complete. Solutions must fit existing codebase patterns first.
Search for:
- Official documentation for involved libraries (match versions from package.json)
- Known gotchas, breaking changes, deprecations
- Security considerations and best practices
Format references:
- [Library Docs v{version}](url#specific-section)
- KEY_INSIGHT: {what we learned}
- APPLIES_TO: {which task/file}
- GOTCHA: {pitfall and mitigation}
PHASE_3_CHECKPOINT:
Phase 4: ARCHITECT — Strategic Design
Analyze:
- ARCHITECTURE_FIT: How does this integrate with existing architecture?
- EXECUTION_ORDER: What must happen first → second → third?
- FAILURE_MODES: Edge cases, race conditions, error scenarios?
- PERFORMANCE: Will this scale? Database queries optimized?
- SECURITY: Attack vectors? Data exposure risks?
- MAINTAINABILITY: Will future devs understand this?
Document:
APPROACH_CHOSEN: {description}
RATIONALE: {why this over alternatives — reference codebase patterns}
ALTERNATIVES_REJECTED:
- {Alt 1}: Rejected because {reason}
- {Alt 2}: Rejected because {reason}
NOT_BUILDING (explicit scope limits):
- {Item 1 — out of scope and why}
- {Item 2 — out of scope and why}
Design Doc Integration
ls .prp-output/designs/{feature}-design-*.md 2>/dev/null
If found: incorporate API contracts, DB schema, NFRs. Design doc takes precedence over Explore findings.
Phase 4.2: TECHNICAL DESIGN (Conditional)
Include if: Complexity HIGH, OR new API endpoints, DB schema changes, multi-service integration.
Skip if: Complexity LOW, simple enhancement/bug fix.
4.2.1 API Contracts (if new/modified endpoints)
- Endpoint path, method, auth requirement
- Request/response schemas with types and validation
- Error codes table (status, code, description)
4.2.2 Database Schema (if schema changes)
- New/modified table definitions (SQL or ORM format)
- Index strategy for query performance
- Migration approach + rollback plan
4.2.3 Sequence Diagrams (if complex multi-component flow)
- Critical path using Mermaid syntax
- Error/failure path
4.2.4 Non-Functional Requirements (if HIGH complexity)
- Performance targets: p50, p95, p99 latency
- Caching strategy (what, TTL, invalidation)
- Security considerations, monitoring
4.2.5 Migration & Rollback (if modifying existing behavior)
- Data migration steps
- Feature flag approach
- Rollback triggers and steps
PHASE_4_CHECKPOINT:
Phase 5: DESIGN — UX Transformation
Architecture constraints from Phase 4 should inform UX design decisions.
Create Before/After ASCII diagrams showing:
- User experience and data flow changes
- USER_FLOW, PAIN_POINT/VALUE_ADD, DATA_FLOW
Interaction Changes table:
| Location | Before | After | User_Action | Impact |
|---|
/route | State A | State B | Click X | Can now Y |
PHASE_5_CHECKPOINT:
Phase 6: GENERATE — Plan File
Artifact Naming
TIMESTAMP=$(date +%Y%m%d-%H%M)
ls .prp-output/plans/{kebab-case-feature-name}*.plan.md 2>/dev/null
Path: .prp-output/plans/{kebab-case-feature-name}-{TIMESTAMP}.plan.md
Create directory: mkdir -p .prp-output/plans
Complexity Validation (Pre-save check)
| Declared | Expected Scope | If Mismatch |
|---|
| LOW | ≤3 tasks, no API/DB changes | WARN: "Consider MEDIUM" |
| MEDIUM | 4-10 tasks, OR API/DB changes | WARN if >10 tasks |
| HIGH | >10 tasks, OR multi-service | OK |
Plan Structure
The plan file MUST include lifecycle frontmatter (status: pending, runner, mode) and ALL these sections:
- Summary — what we're building
- User Story — who, what, why
- Problem/Solution Statements — specific and testable
- Metadata — type, complexity, systems, dependencies, task count, Runner + Type Check + Lint + Test + Build commands (+ Monorepo/Package/Filter if applicable)
- UX Design — before/after ASCII diagrams + interaction changes table
- Mandatory Reading — P0/P1/P2 priority files the implementer MUST read first, external docs with version
- Patterns to Mirror — ACTUAL code snippets with SOURCE tags: naming, errors, logging, repository, service, tests
- Files to Change — CREATE/UPDATE list with Insert At hints and justifications
- Integration Points — new code → existing code hook locations (file:line, wiring details)
- NOT Building — explicit scope limits
- Step-by-Step Tasks — ordered, atomic, each with:
- ACTION: What to do (CREATE/UPDATE)
- IMPLEMENT: Specific details
- MIRROR: Source file:lines to copy pattern from
- IMPORTS: Exact import statements
- GOTCHA: Known pitfalls to avoid
- VALIDATE: Exact command to verify (pre-filled, no placeholders)
- Testing Strategy — unit tests table + integration tests (conditional) + test data + performance benchmarks (conditional) + edge cases checklist
- Docs Impact — list docs pages to update/create, or "N/A" with per-feature justification. If the plan changes user-facing behavior, list which
packages/docs/ pages need updating and include docs + translation as implementation steps (the implementing agent writes EN docs + translates to 13 locales in the same PR). Blank = ⚠️ warning at gate audit.
- Gate Compliance (ALWAYS emit — agent-devops#799) — a
## Gate Compliance section that maps the project's /gate operational checklists to plan tasks so the pre-implement gate-audit (Layer 3) can verify completeness. Classify the change and scale the content (tiered — never silently omit):
- User-facing / new endpoint / schema / new entity / feature flag / billing change → map each applicable
new_feature + epic_kickoff + post_ship item to an owning plan task/phase: smoke-test L1/L2 for new endpoints, seed-uat-roles for new entities, nav entry points for new pages, ALTER TYPE … ADD VALUE for new enums, feature-flag verify-all-envs, docs redeploy, post-ship rollback/version-bump/branch-cleanup.
- Genuinely internal-only (docs/config/refactor with no user-facing or CI-observable change) →
Gate Compliance: N/A — <enumerated reason>. A blanket "N/A — no new features" is REJECTED (mirrors the Docs Impact N/A bar): enumerate what was checked (no packages/web pages, no /api routes, no schema/entities, no flags/billing) and why none apply.
- The always-present, justified classification is what lets the gate-auditor mechanically verify L3. If this project ships a
/gate skill (e.g. claude-code/codex), run /gate audit pre-implement to verify this section (other toolchains: skip — this line degrades gracefully).
- Validation Commands — 6 levels (Static Analysis, Unit Tests, Full Suite, Database, Browser, Manual), pre-filled with actual commands
- Confidence Score — 5 dimensions × 2pts = 10 formula: Patterns + Gotchas + Integration + Validation + Testing
- Acceptance Criteria — definition of done (including unit tests cover >= 90% of new code)
- Completion Checklist — all 6 validation levels
- Risks and Mitigations — likelihood, impact, strategy
- Technical Design (conditional, HIGH or API/DB) — API contracts, DB schema, sequence diagrams, NFRs, migration & rollback
IMPORTANT: The saved plan file MUST NOT contain any unfilled {...} placeholders in Validation Commands section. Pre-fill with actual detected commands.
Output
Save file to: .prp-output/plans/{kebab-case-feature-name}-{TIMESTAMP}.plan.md
After saving, verify the file was written:
test -f ".prp-output/plans/{filename}" || echo "FATAL: Plan file write failed"
If verification fails, STOP — do not report success.
If from PRD: Update PRD status to in-progress, link plan file path. After update, verify the PRD file was modified (re-read and confirm status changed). If update fails, WARN: "Could not update PRD status. Manually update the phase status to in-progress."
Commit the plan artifact for durable git history (agent-devops#801): the plan (and any design/review artifacts under .prp-output/) should live in git, not only on disk. After saving, commit the artifact — but ONLY on a real feature branch:
BR=$(git branch --show-current)
if [ -n "$BR" ] && [ "$BR" != "main" ] && [ "$BR" != "master" ]; then
git add -f .prp-output/plans/{filename}
if git commit -q -m "docs(plan): {kebab-case-feature-name} plan artifact"; then
echo "Plan committed on $BR: $(git rev-parse --short HEAD)"
else
echo "WARNING: plan commit did not succeed (nothing staged / hook / unset git identity) — commit the artifact manually before it is lost (#801)"
fi
else
echo "WARNING: on '${BR:-<detached HEAD>}' — NOT committing plan to main/master or a detached HEAD. Create a feature branch and commit the artifact so it isn't lost (repeatedly flagged by Warden — #801)."
fi
The [ -n "$BR" ] guard is essential — on a detached HEAD git branch --show-current is empty and "" != "main" would otherwise pass, orphaning the commit. Never commit plan artifacts directly to main/master. Report the commit outcome (sha or the WARNING) in the "Report to user" block below so it is auditable. (Epics: EPIC-ORCHESTRATION kickoff carries a matching 'commit plan/design artifacts to the feature branch' item.)
Report to user:
## Plan Created
**File**: `.prp-output/plans/{feature-name}-{TIMESTAMP}.plan.md`
{If from PRD:}
**Source PRD**: `{prd-file-path}`
**Phase**: #{number} - {phase name}
**PRD Updated**: Status set to `in-progress`, plan linked
{If parallel phases:}
**Parallel Opportunity**: Phase {X} can run concurrently.
**Summary**: {2-3 sentence overview}
**Complexity**: {LOW/MEDIUM/HIGH} - {brief rationale}
**Scope**:
- {N} files to CREATE
- {M} files to UPDATE
- {K} total tasks
**Key Patterns**:
- {Pattern 1 from codebase with file:line}
- {Pattern 2 from codebase with file:line}
**External Research**:
- {Key doc 1 with version}
**UX Transformation**:
- BEFORE: {one-line current state}
- AFTER: {one-line new state}
**Risks**:
- {Primary risk}: {mitigation}
**Confidence Score**: {X}/10 (P:{p} G:{g} I:{i} V:{v} T:{t})
**Next Step**: `/prp-implement .prp-output/plans/{feature-name}-{TIMESTAMP}.plan.md`
Verification
Before saving, verify:
Context Completeness:
Implementation Readiness:
Pattern Faithfulness:
Validation Coverage:
UX Clarity:
NO_PRIOR_KNOWLEDGE_TEST: Could an agent unfamiliar with this codebase implement using ONLY the plan?
Success Criteria
- CONTEXT_COMPLETE: All patterns, gotchas, integration points from actual codebase
- IMPLEMENTATION_READY: Tasks executable top-to-bottom without questions
- PATTERN_FAITHFUL: Every new file mirrors existing codebase style
- VALIDATION_DEFINED: Every task has executable verification command (pre-filled)
- TOOLCHAIN_DETECTED: Runner and commands auto-detected and pre-filled
- INTEGRATION_MAPPED: All hook locations specified with file:line
- UX_DOCUMENTED: Before/After transformation visually clear
- ONE_PASS_TARGET: Confidence score 8+/10