diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 23b5123..8283924 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -8,7 +8,7 @@ "plugins": [ { "name": "dev-workflow", - "description": "Development workflow tools: subagent-driven implementation, code review, PR merge workflow", + "description": "Complete development workflow: brainstorming, planning, TDD, debugging, subagent execution, code review, PR merge", "source": "./" } ] diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index c50aa08..d6a9390 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,13 +1,13 @@ { "name": "dev-workflow", "version": "2.1.0", - "description": "Development workflow tools: subagent-driven implementation, code review, PR merge workflow", + "description": "Complete development workflow: brainstorming, planning, TDD, debugging, subagent execution, code review, PR merge", "author": { "name": "Tom Baker", "url": "https://github.com/tombakerjr" }, - "homepage": "https://github.com/tombakerjr/claude-code-workflows", - "repository": "https://github.com/tombakerjr/claude-code-workflows", + "homepage": "https://github.com/tombakerjr/claude-code-pr-workflow", + "repository": "https://github.com/tombakerjr/claude-code-pr-workflow", "license": "MIT", "keywords": [ "workflow", diff --git a/CLAUDE.md b/CLAUDE.md index a185de1..603d5b7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,11 +4,11 @@ This file provides guidance to Claude Code when working with this plugin. ## Overview -This is a Claude Code plugin that enforces PR workflow best practices: -- Pre-commit code verification -- PR merge checklists with delayed comment detection -- Git guardrails (block main push, warn on raw merge) -- Comprehensive code review agents +This is a comprehensive Claude Code plugin that supports the full development workflow: +- **Planning**: Brainstorming, specification, and implementation planning +- **Implementation**: Test-driven development, systematic debugging, and subagent-driven execution +- **Review**: Comprehensive code reviews with multiple agent tiers +- **Merge**: Pre-commit verification, PR merge checklists with delayed comment detection, and git guardrails ## Plugin Structure @@ -26,6 +26,13 @@ claude-code-pr-workflow/ │ ├── pr-status.md # /pr-status │ ├── pr-merge.md # /pr-merge │ └── context-recovery.md # /context-recovery +├── skills/ # Workflow skills +│ ├── subagent-driven-development/ # Execute implementation plans +│ ├── test-driven-development/ # TDD workflow +│ ├── systematic-debugging/ # Debug root cause analysis +│ ├── writing-plans/ # Create implementation plans +│ ├── using-git-worktrees/ # Isolated git worktrees +│ └── brainstorming/ # Design dialogue for features ├── hooks/ # Event handlers │ ├── hooks.json # Hook configuration │ ├── run-hook.cmd # Cross-platform wrapper @@ -40,14 +47,14 @@ claude-code-pr-workflow/ ### Testing Changes 1. Make changes to plugin files -2. Uninstall if already installed: `/plugin uninstall pr-workflow@pr-workflow-marketplace` -3. Reinstall: `/plugin install pr-workflow@pr-workflow-marketplace` -4. Restart Claude Code for hooks to take effect +2. Run `claude plugin update` +3. Restart Claude Code for hooks to take effect ### Adding New Components - **New command**: Create `commands/name.md` with frontmatter - **New agent**: Create `agents/name.md` with frontmatter +- **New skill**: Create `skills/skill-name/` directory with `skill.md` and supporting files - **New hook**: Add to `hooks/hooks.json`, create script in `hooks/` ### Cross-Platform Hooks @@ -92,6 +99,16 @@ Agents are invoked automatically based on their descriptions or explicitly: - "Use staff-code-reviewer to review my changes" - Full code review - "Check if this PR is safe to merge" - PR verification +### Skill Invocation + +Skills provide structured workflows for common development tasks: +- "Use dev-workflow:brainstorming" - Start design dialogue for new features +- "Use dev-workflow:systematic-debugging" - Debug with root cause analysis +- "Use dev-workflow:writing-plans" - Create implementation plan with tasks +- "Use dev-workflow:subagent-driven-development" - Execute implementation plans with independent tasks +- "Use dev-workflow:test-driven-development" - TDD workflow with test-first approach +- "Use dev-workflow:using-git-worktrees" - Isolated git worktrees for complex features + ## Customization Users should customize: diff --git a/README.md b/README.md index 1d988ad..9e78670 100644 --- a/README.md +++ b/README.md @@ -1,89 +1,102 @@ -# PR Workflow Plugin for Claude Code +# Development Workflow Plugin for Claude Code -A Claude Code plugin that enforces PR workflow best practices through guardrails, verification agents, and workflow commands. +A comprehensive Claude Code plugin for feature development, bug fixes, and PR workflows. Enforces best practices through upfront planning, parallelized subagent execution, verification agents, and workflow commands. ## Features +- **Upfront planning** - Brainstorming and structured implementation plans before code +- **Subagent execution** - Parallelized work with fresh context per task +- **Git worktree support** - Isolated workspaces for parallel development - **Pre-commit verification** - Type checking, security scans, debug code detection - **PR merge checklist** - CI verification, delayed comment detection, blocker scanning - **Git guardrails** - Blocks direct pushes to main, warns on raw merge commands - **Code review agents** - Staff-level comprehensive reviews - **Context recovery** - Restore state after context compaction -- **Execution preferences** - Enforces subagent-driven-development for plan execution -## Feature Development Workflow +## Philosophy -This plugin enforces a structured workflow for feature development. The diagram below shows the complete lifecycle from starting work to merging. +This plugin enforces three core principles: -```mermaid -flowchart TD - subgraph START ["Start Feature Work"] - A[New task/feature request] --> B{On main branch?} - B -->|Yes| C[Create feature branch] - B -->|No| D[Use current branch] - C --> E[git checkout -b feature/name] - E --> F[Ready to develop] - D --> F - end +### 1. Planning Before Implementation +Features start with **brainstorming** (Socratic exploration of requirements and design), followed by **writing plans** that break work into bite-sized, verifiable tasks. This catches issues early and provides clear success criteria. - subgraph DEV ["Development Iteration"] - F --> G[Write code] - G --> H[Run code-verifier agent] - H --> I{Verification passed?} - I -->|No| J[Fix issues] - J --> G - I -->|Yes| K[Commit changes] - K --> L{More work needed?} - L -->|Yes| G - L -->|No| M[Ready for PR] - end +### 2. Subagents for Context Hygiene +Implementation uses **subagent-driven development** where: +- Main conversation stays clean (planning and orchestration) +- Each task gets fresh context (implementer subagent reads files it needs) +- Prevents context bloat from 50k+ token file dumps +- Enables independent work verification - subgraph PR ["Pull Request"] - M --> N["/pr-create"] - N --> O["Typecheck + Push + Create PR"] - O --> P[Wait for CI] - P --> Q[Request review / Run staff-code-reviewer] +### 3. Parallelization Through Isolation +**Git worktrees** + subagents enable true parallel development: +- Multiple features/experiments in isolated workspaces +- Subagents work independently without blocking +- Easy cleanup (delete worktree, no branch pollution) + +## Complete Development Workflow + +```mermaid +flowchart TD + subgraph FEATURE ["Feature Development Path"] + A[New feature request] --> B[Brainstorming skill] + B --> C["Explore requirements & design"] + C --> D[Using-git-worktrees skill] + D --> E[Create isolated workspace] + E --> F[Writing-plans skill] + F --> G["Break into tasks with acceptance criteria"] + G --> H[Subagent-driven-development skill] + H --> I["Parallel execution with fresh context"] + I --> J["/pr-create"] + J --> K[PR ready] end - subgraph REVIEW ["Review Iteration"] - Q --> R{Review feedback?} - R -->|Changes requested| S[Address feedback] - S --> T[Commit fixes] - T --> U[Push updates] - U --> P - R -->|Approved| V[Ready to merge] + subgraph BUG ["Bug Fix Path"] + L[Bug report] --> M[Systematic-debugging skill] + M --> N["4-phase root cause analysis"] + N --> O[Test-driven-development skill] + O --> P["Red → Green → Refactor"] + P --> Q[Commit fix] + Q --> R["/pr-create"] + R --> K end - subgraph MERGE ["Safe Merge"] - V --> W["/pr-merge"] - W --> X[Typecheck] - X --> Y[Verify CI passed] - Y --> Z[Wait 10-12 seconds] - Z --> AA[Fetch ALL comments] - AA --> AB{Blockers found?} - AB -->|Yes| AC[Address blockers] - AC --> T - AB -->|No| AD[Merge PR] - AD --> AE[Delete branch] - AE --> AF[Done!] + subgraph MERGE ["PR Merge Workflow"] + K --> S[CI + Reviews] + S --> T{Approved?} + T -->|No| U[Address feedback] + U --> S + T -->|Yes| V["/pr-merge"] + V --> W["Checklist: typecheck, CI, poll for review comment, scan"] + W --> X{Blockers?} + X -->|Yes| U + X -->|No| Y[Merge & cleanup] end - style START fill:#e1f5fe - style DEV fill:#fff3e0 - style PR fill:#f3e5f5 - style REVIEW fill:#e8f5e9 + style FEATURE fill:#e3f2fd + style BUG fill:#fff3e0 style MERGE fill:#fce4ec ``` -### Workflow Phases +### Feature Development Path -| Phase | Key Actions | Plugin Support | -|-------|-------------|----------------| -| **Start** | Create feature branch, never commit to main | `git-guard.py` blocks commits on main | -| **Develop** | Write code, verify before commits | `code-verifier` agent, iterative fixes | -| **PR Creation** | Typecheck, push, create PR | `/pr-create` command | -| **Review** | Get feedback, iterate on changes | `staff-code-reviewer` agent | -| **Merge** | Full checklist before merge | `/pr-merge` with 10-12s wait for delayed comments | +| Phase | Skill/Command | Purpose | +|-------|---------------|---------| +| **1. Design** | `brainstorming` | Socratic exploration of requirements and design trade-offs | +| **2. Isolate** | `using-git-worktrees` | Create isolated workspace (optional, for parallel work) | +| **3. Plan** | `writing-plans` | Break feature into bite-sized tasks with acceptance criteria | +| **4. Execute** | `subagent-driven-development` | Parallel execution with fresh context per task | +| **5. PR** | `/pr-create` | Typecheck, push, create PR | +| **6. Merge** | `/pr-merge` | Full checklist with delayed comment detection | + +### Bug Fix Path + +| Phase | Skill/Command | Purpose | +|-------|---------------|---------| +| **1. Analyze** | `systematic-debugging` | 4-phase root cause analysis (gather, hypothesize, verify, fix) | +| **2. Test** | `test-driven-development` | Red-green-refactor discipline | +| **3. Commit** | N/A | Commit fix with conventional message | +| **4. PR** | `/pr-create` | Create PR for review | +| **5. Merge** | `/pr-merge` | Full merge checklist | ### Git Guards @@ -99,8 +112,8 @@ The plugin prevents common mistakes: When executing implementation plans (from `writing-plans` or similar), this plugin enforces: -- **Use**: `superpowers:subagent-driven-development` -- **Not**: `superpowers:executing-plans` +- **Use**: `dev-workflow:subagent-driven-development` +- **Not**: Alternative execution methods that cause context bloat Subagent-driven development keeps work in the current session with fresh context per task, avoiding context bloat from long-running executions. @@ -110,7 +123,7 @@ Subagent-driven development keeps work in the current session with fresh context ```bash /plugin marketplace add tombakerjr/claude-code-pr-workflow -/plugin install pr-workflow@claude-code-pr-workflow +/plugin install dev-workflow@claude-code-pr-workflow ``` Then restart Claude Code. @@ -120,7 +133,7 @@ Then restart Claude Code. ```bash git clone https://github.com/tombakerjr/claude-code-pr-workflow.git /plugin marketplace add /path/to/claude-code-pr-workflow -/plugin install pr-workflow@pr-workflow-marketplace +/plugin install dev-workflow@tombakerjr-claude-tools ``` Then restart Claude Code. @@ -144,6 +157,20 @@ Then restart Claude Code. | `quick-reviewer` | Fast combined spec+quality review for simple tasks (≤2 files) | | `code-verifier` | Pre-commit: typecheck, security scan, debug code detection | | `pr-verifier` | Pre-merge: CI status, comment wait, blocker detection | +| `implementer` | Task implementation agent (Sonnet default, Haiku for mechanical work) | +| `spec-reviewer` | Verify implementation matches spec and acceptance criteria | +| `quality-reviewer` | Fast quality gate: code quality, test coverage, documentation | + +### Skills + +| Skill | Description | +|-------|-------------| +| `subagent-driven-development` | Execute implementation plans with parallel subagents and fresh context | +| `test-driven-development` | Red-green-refactor discipline for features and bug fixes | +| `systematic-debugging` | 4-phase root cause analysis: gather, hypothesize, verify, fix | +| `writing-plans` | Create bite-sized task plans with acceptance criteria | +| `using-git-worktrees` | Create isolated workspaces for parallel development | +| `brainstorming` | Socratic exploration of requirements and design trade-offs | ### Hooks @@ -158,13 +185,12 @@ Then restart Claude Code. The `/pr-merge` command enforces this critical workflow: 1. **Typecheck** - Catch type errors before merge -2. **CI passes** - All checks must show passed -3. **Wait 10-12 seconds** - Review comments post AFTER CI passes -4. **Fetch ALL comments** - Don't miss delayed bot comments -5. **Scan for blockers** - CRITICAL, FIX, BLOCKER, DO NOT MERGE -6. **Only merge when clear** - Human verification required +2. **CI passes** - Use `gh pr checks --watch` to wait for completion +3. **Poll for review comment** - Claude review ALWAYS posts a comment +4. **Scan for blockers** - CRITICAL, FIX, BLOCKER, DO NOT MERGE +5. **Only merge when clear** - Human verification required -**Why the 10-12 second wait?** Many CI/review bots post their comments several seconds *after* CI completes. Without waiting, you'll miss critical review feedback. +**Why poll for the review comment?** Claude code review ALWAYS posts a comment (either approving or requesting fixes). The absence of this comment is NOT tacit approval - we poll until found to ensure no review feedback is missed. ## Usage Examples @@ -238,15 +264,6 @@ blocked = [ - Git - For Windows: Git for Windows (provides bash for hooks) -## Recommended Pairing - -This plugin works well with the [superpowers](https://github.com/obra/superpowers) plugin: - -- `subagent-driven-development` - Main agent coordinates, subagents implement -- `systematic-debugging` - Structured root cause analysis -- `verification-before-completion` - Evidence before success claims -- `receiving-code-review` - Rigorous feedback response - ## License MIT diff --git a/agents/implementer.md b/agents/implementer.md index 5ed4f9a..61ceb17 100644 --- a/agents/implementer.md +++ b/agents/implementer.md @@ -71,6 +71,29 @@ If ANYTHING is unclear about: Fix any issues found before reporting. +## TDD Principles + +Default to Test-Driven Development for bug fixes and new functionality: + +1. **Write a failing test first** - Understand the requirement through tests +2. **Write minimal production code** - Only enough code to make the test pass +3. **Refactor once green** - Improve code quality while tests stay passing +4. **Never guess about test results** - Run tests and show actual output + +For detailed workflow guidance, use the `dev-workflow:test-driven-development` skill. + +## Verification Discipline + +**Evidence before assertions:** + +- **Run tests and capture output** - Never say "tests should pass"; show the actual results +- **Include test output in your report** - Paste relevant sections from test runs +- **Fix before reporting success** - If tests fail, fix the code and re-run +- **Verify all three gates** - Typecheck, Build, Tests (not "should pass" but actual passing) +- **Be honest about skipped items** - Mark SKIPPED only when explicitly acceptable + +This discipline ensures reports are credible and issues are caught early. + ### Report Format When done, provide this structured report: diff --git a/agents/pr-verifier.md b/agents/pr-verifier.md index 27dfa81..db6c34d 100644 --- a/agents/pr-verifier.md +++ b/agents/pr-verifier.md @@ -20,16 +20,47 @@ Execute these steps in order: - ALL checks must show passed - If any pending or failed: BLOCKED -3. **Wait for delayed comments**: `sleep 12` - - Comments often post 5-15 seconds after CI passes +3. **Watch CI completion**: `gh pr checks --watch` + - Waits for all checks to complete - This step is CRITICAL - never skip it -4. **Fetch all comments**: +4. **Poll for Claude review comment**: + - The Claude code review ALWAYS posts a comment + - Poll until found (max 12 retries = 60 seconds) + - Look for bot usernames: "claude", "code-review", "github-actions" + - If not found after retries, BLOCKED (review missing) + + ```bash + MAX_RETRIES=12 + RETRY_COUNT=0 + FOUND=0 + + while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do + COMMENTS=$(gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/pulls/$(gh pr view --json number -q .number)/comments --jq '.[] | .user.login + ": " + .body' 2>/dev/null) + REVIEWS=$(gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/pulls/$(gh pr view --json number -q .number)/reviews --jq '.[] | select(.body != "") | .user.login + ": " + .body' 2>/dev/null) + + ALL_TEXT="$COMMENTS $REVIEWS" + + if echo "$ALL_TEXT" | grep -iq "claude\|code-review\|github-actions"; then + FOUND=1 + break + fi + + RETRY_COUNT=$((RETRY_COUNT + 1)) + sleep 5 + done + + [ $FOUND -eq 0 ] && echo "BLOCKED: Claude review comment not found" + ``` + +5. **Fetch all comments**: ```bash - gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/issues/$(gh pr view --json number -q .number)/comments --jq '.[] | "\(.user.login): \(.body)"' + gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/pulls/$(gh pr view --json number -q .number)/comments --jq '.[] | "\(.user.login): \(.body)"' + gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/pulls/$(gh pr view --json number -q .number)/reviews --jq '.[] | select(.body != "") | "\(.user.login) - \(.state): \(.body)"' ``` -5. **Scan for blockers**: +6. **Scan for blockers**: + - No Claude review comment found = BLOCKED - CRITICAL = BLOCKED - FIX = BLOCKED - BLOCKER = BLOCKED @@ -53,6 +84,7 @@ VERDICT: SAFE TO MERGE | DO NOT MERGE ## Rules - Be strict. When in doubt, report DO NOT MERGE. -- Never skip the 12-second wait. +- Never skip polling for Claude review comment. +- Claude review comment is REQUIRED before evaluating merge readiness. - Read EVERY comment, not just recent ones. - A single blocker means DO NOT MERGE. diff --git a/commands/pr-merge.md b/commands/pr-merge.md index c88524b..c7c3cee 100644 --- a/commands/pr-merge.md +++ b/commands/pr-merge.md @@ -52,14 +52,54 @@ pnpm typecheck && pnpm build && pnpm test !`gh pr checks` -**If checks pending:** Wait and re-check. Do not proceed until all pass. +**If checks pending:** Wait for all checks to complete. + +!`gh pr checks --watch` + **If checks failed:** Stop. CI must pass before merge. -## Step 4: Wait for Delayed Comments +## Step 4: Poll for Claude Review Comment + +The Claude code review ALWAYS posts a comment. Wait for it before proceeding. + +```bash +# Poll for Claude review comment +MAX_RETRIES=12 +RETRY_COUNT=0 +FOUND=0 + +echo "Polling for Claude code review comment..." -Review comments often post 5-15 seconds AFTER CI completes. +while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do + # Fetch all comments and reviews + COMMENTS=$(gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/pulls/$(gh pr view --json number -q .number)/comments --jq '.[] | .user.login + ": " + .body' 2>/dev/null) + REVIEWS=$(gh api repos/$(gh repo view --json nameWithOwner -q .nameWithOwner)/pulls/$(gh pr view --json number -q .number)/reviews --jq '.[] | select(.body != "") | .user.login + ": " + .body' 2>/dev/null) -!`echo "Waiting 12 seconds for delayed review comments..." && sleep 12` + ALL_TEXT="$COMMENTS $REVIEWS" + + # Look for Claude review indicators (bot username or review keywords) + if echo "$ALL_TEXT" | grep -iq "claude\|code-review\|github-actions"; then + echo "✓ Claude review comment found" + FOUND=1 + break + fi + + RETRY_COUNT=$((RETRY_COUNT + 1)) + echo "Retry $RETRY_COUNT/$MAX_RETRIES - waiting 5 seconds..." + sleep 5 +done + +if [ $FOUND -eq 0 ]; then + echo "⚠️ WARNING: No Claude review comment found after 60 seconds" + echo "This is unexpected. The review may still be processing." + echo "" + echo "Do you want to:" + echo "1. Wait longer (another 60 seconds)" + echo "2. Proceed without review comment (NOT RECOMMENDED)" + echo "3. Abort merge" + exit 1 +fi +``` ## Step 5: Fetch All Comments diff --git a/hooks/workflow-preferences.sh b/hooks/workflow-preferences.sh index 60f021e..f41a60c 100755 --- a/hooks/workflow-preferences.sh +++ b/hooks/workflow-preferences.sh @@ -3,7 +3,7 @@ cat << 'EOF' { "hookSpecificOutput": { "hookEventName": "SessionStart", - "additionalContext": "Use subagent-driven-development (not executing-plans). Never commit to main." + "additionalContext": "Use subagent-driven-development for plan execution. Never commit to main. For new features: dev-workflow:brainstorming. For bugs: dev-workflow:systematic-debugging." } } EOF diff --git a/skills/brainstorming/SKILL.md b/skills/brainstorming/SKILL.md new file mode 100644 index 0000000..9bffb5d --- /dev/null +++ b/skills/brainstorming/SKILL.md @@ -0,0 +1,295 @@ +--- +name: brainstorming +description: You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation. +--- + +# Brainstorming + +## Iron Law + +**No implementation without design dialogue first.** + +When faced with creative work (new features, components, behavior changes), you must understand the problem deeply before jumping to solutions. Design emerges through conversation, not upfront specification. + +## The Socratic Approach + +### Ask ONE Question at a Time + +**Never present a list of questions.** Each question is an opportunity to learn and adjust the next question based on the answer. + +Good: +``` +What's the primary goal of this feature? + +A) Enable users to export data +B) Provide admin oversight +C) Integrate with external system +D) Other (please describe) +``` + +Bad: +``` +I need to understand: +1. What's the primary goal? +2. Who are the users? +3. What are the constraints? +4. How does this integrate? +5. What's the timeline? +``` + +### Prefer Multiple Choice + +**Reduce user typing burden.** Offer options based on common patterns, always include "Other" as escape hatch. + +Structure: +- 3-5 clear options +- One "Other (please describe)" option +- Brief explanation if options need context + +### Build Understanding Incrementally + +**Each answer shapes the next question.** Don't follow a rigid script. Adapt based on what you learn. + +Flow: +1. Start broad (what/why) +2. Narrow to specifics (who/when/where) +3. Explore constraints (technical/timeline/resources) +4. Consider alternatives (tradeoffs) + +## The Design Document + +### Structure (200-300 Word Sections) + +Build the design in digestible chunks. After each section, pause for validation. + +**Section 1: Problem Statement** +- What problem exists? +- Who experiences it? +- Why does it matter? +- Current workarounds (if any) + +**Validation:** "Does this accurately capture the problem you're trying to solve?" + +**Section 2: Proposed Solution** +- High-level approach +- Key architectural decisions +- How it addresses the problem +- What's explicitly out of scope + +**Validation:** "Does this direction align with your vision?" + +**Section 3: Technical Design** +- Components/modules involved +- Data models or structures +- Integration points +- Error handling approach + +**Validation:** "Any technical concerns or missing pieces?" + +**Section 4: Implementation Notes** +- Development phases (if multi-part) +- Testing strategy +- Migration/rollout plan +- Success metrics + +**Validation:** "Anything we should prioritize or defer?" + +### Save Location + +``` +docs/plans/YYYY-MM-DD--design.md +``` + +Topic should be kebab-case, descriptive. Examples: +- `2026-01-27-user-export-feature-design.md` +- `2026-01-27-admin-dashboard-redesign.md` +- `2026-01-27-payment-integration-design.md` + +## Process + +### 1. Understand the Problem + +**Questions to explore:** +- What needs to exist or change? (multiple choice of common patterns) +- Why is this important now? (priority/urgency) +- Who will use or benefit from this? (users/stakeholders) +- What constraints exist? (technical/timeline/resources) + +**Checkpoint:** You understand the "why" behind the work. + +### 2. Explore Solutions + +**Questions to explore:** +- What approaches have you considered? (list options, ask to pick or add) +- What tradeoffs matter most? (speed vs. flexibility, simple vs. complete) +- Are there existing patterns in the codebase to follow? (consistency) +- What could go wrong? (risks/edge cases) + +**Checkpoint:** Multiple options identified, tradeoffs clear. + +### 3. Design the Solution + +**Build the document section by section:** +1. Write Problem Statement → validate +2. Write Proposed Solution → validate +3. Write Technical Design → validate +4. Write Implementation Notes → validate + +**Checkpoint:** Complete design document saved to docs/plans/. + +### 4. Prepare for Implementation + +**Chain to related skills:** + +``` +Should we set up an isolated workspace for this work? + +A) Yes - use git worktrees for clean separation +B) No - work directly in current branch +``` + +If A: Chain to `dev-workflow:using-git-worktrees` + +Then: + +``` +Ready to create implementation plan? + +This will break the design into concrete tasks with verification steps. +``` + +Chain to `dev-workflow:writing-plans` + +## When to Use This Skill + +**Always use for:** +- New features or capabilities +- Significant behavior changes +- UI/UX components or flows +- Architecture decisions +- Integration with external systems +- Refactoring with unclear scope + +**Use when requirements are:** +- Vague or high-level ("make it better") +- Creative ("design a dashboard") +- Complex (multiple components/stakeholders) +- Risky (big changes, unclear impact) + +**Skip when:** +- Fixing clear bugs (use systematic-debugging) +- Implementing from detailed spec +- Making trivial changes (typos, formatting) + +## Integration with Other Skills + +**Chains to `dev-workflow:using-git-worktrees`:** +- After design is complete, offer to set up isolated workspace +- Worktree provides clean environment for implementation +- Easy to abandon if design changes during implementation + +**Chains to `dev-workflow:writing-plans`:** +- Design document becomes input to planning +- Plan breaks design into tasks with verification +- Each task references relevant sections of design + +**Works with `dev-workflow:implementer`:** +- Implementer references design document during work +- Design provides context for decisions +- Implementation may surface design issues (feedback loop) + +## Anti-Patterns to Avoid + +❌ Asking multiple questions at once (overwhelming) +❌ Open-ended questions when multiple choice would work (too much typing) +❌ Writing full design without validation (wasted effort) +❌ Skipping problem exploration and jumping to solution +❌ Not documenting the design (context loss) +❌ Continuing to implementation without user sign-off + +## Success Criteria + +✅ Problem is clearly understood and documented +✅ Multiple solution approaches were considered +✅ Design choices have clear rationale (tradeoffs) +✅ User validated each section before continuing +✅ Complete design saved to docs/plans/ +✅ Clear path to implementation (chained to worktrees/planning) + +## Example Flow + +``` +USER: "I want to add user exports to the admin panel" + +ASSISTANT: Let me understand what you're trying to accomplish. + +What's the primary goal of this export feature? + +A) Enable admins to audit user activity +B) Provide data portability for users +C) Generate reports for compliance +D) Other (please describe) + +USER: "A - audit user activity" + +ASSISTANT: Got it, auditing focus. + +What format would be most useful for admins? + +A) CSV (spreadsheet-compatible) +B) JSON (programmatic processing) +C) PDF (human-readable report) +D) Multiple formats (let admin choose) + +USER: "A - CSV is fine" + +ASSISTANT: Perfect, CSV keeps it simple. + +Should this export: + +A) All users (full database dump) +B) Filtered subset (search/filter first) +C) Single user (from user detail page) +D) Multiple options above + +USER: "B - filtered subset" + +ASSISTANT: Makes sense, working with existing filters. + +[Continue dialogue, then...] + +I'll now write up the Problem Statement section: + +--- +**Problem Statement** + +Admins need to export filtered user lists as CSV for audit purposes. +Currently, they must manually copy data from the UI table, which is +error-prone and limited by pagination. This blocks quarterly compliance +reviews where admins must analyze user activity patterns across hundreds +of users. + +**Who experiences it:** Admin users performing audits/compliance reviews + +**Why it matters:** Manual data collection is time-consuming and creates +compliance risk if data is incomplete or incorrect. + +**Current workaround:** Copy-paste from UI table, limited to current page +--- + +Does this accurately capture the problem you're trying to solve? + +USER: "Yes, that's right" + +ASSISTANT: Great. Now for the Proposed Solution... + +[Continue through all sections, validate each, then save] + +Design complete! I've saved it to: +docs/plans/2026-01-27-admin-user-export-design.md + +Should we set up an isolated workspace for this work? + +A) Yes - use git worktrees for clean separation +B) No - work directly in current branch +``` diff --git a/skills/subagent-driven-development/SKILL.md b/skills/subagent-driven-development/SKILL.md index 73afa9d..cd6abbf 100644 --- a/skills/subagent-driven-development/SKILL.md +++ b/skills/subagent-driven-development/SKILL.md @@ -326,4 +326,8 @@ Options: - `/pr-merge` command - CI check, comment assessment, merge **Works with:** -- `superpowers:writing-plans` - creates plans with model recommendations +- `dev-workflow:writing-plans` - creates plans with model recommendations +- `dev-workflow:brainstorming` - design exploration before planning +- `dev-workflow:systematic-debugging` - bug investigation workflow +- `dev-workflow:test-driven-development` - TDD discipline for implementation +- `dev-workflow:using-git-worktrees` - isolated workspaces for parallel execution diff --git a/skills/systematic-debugging/SKILL.md b/skills/systematic-debugging/SKILL.md new file mode 100644 index 0000000..81ce63d --- /dev/null +++ b/skills/systematic-debugging/SKILL.md @@ -0,0 +1,168 @@ +--- +name: systematic-debugging +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes +--- + +# Systematic Debugging + +## Iron Law + +**No fixes without root cause identification first.** + +You may not propose or implement fixes until you understand why the system is behaving incorrectly. If you don't know the root cause, you must investigate further. + +## The 4-Phase Framework + +### 1. Investigate - Gather Evidence + +**Reproduce and observe:** +1. Reproduce the bug reliably in isolation +2. Document exact steps to trigger the behavior +3. Capture error messages, stack traces, logs +4. Identify what works vs. what fails (boundary conditions) +5. Check when this last worked (git bisect if needed) + +**Checkpoint:** Bug is reproducible. Evidence is documented. + +### 2. Analyze - Understand the System + +**Study the code paths:** +1. Read the code where the bug manifests +2. Trace the execution flow backward from symptom +3. Identify assumptions in the code +4. Check related test coverage (what's tested vs. not) +5. Look for recent changes in this area + +**Checkpoint:** You understand what the code is trying to do and where it deviates. + +### 3. Hypothesize - Form Root Cause Theory + +**Develop testable hypothesis:** +1. State your theory about WHY the bug occurs +2. Predict what would happen if theory is correct +3. Identify evidence that would confirm or refute theory +4. Test hypothesis (add logging, debugger, or minimal test case) +5. Refine theory based on results + +**Checkpoint:** You have a theory that explains all observed symptoms. + +### 4. Implement - Fix Using TDD + +**Use test-driven development:** +1. Chain to `dev-workflow:test-driven-development` skill +2. Write failing test that exposes the bug (RED) +3. Implement minimal fix (GREEN) +4. Refactor if needed (REFACTOR) +5. Verify original reproduction steps now pass + +**Checkpoint:** Bug is fixed. Test prevents regression. + +## The 3-Fix Rule + +**After 3 failed fix attempts, STOP and reassess:** + +1. **Question your assumptions** - What if your mental model is wrong? +2. **Broaden the search** - Is the real cause elsewhere in the system? +3. **Escalate or pair** - Get fresh eyes on the problem +4. **Consider architectural issues** - Maybe the design makes this bug inevitable + +Don't keep trying variations. If 3 attempts failed, your understanding is incomplete. + +## Process + +### Starting a Debug Session + +1. **Document the symptom** - What's wrong? Expected vs. actual behavior +2. **Reproduce reliably** - Can you trigger it on demand? +3. **Gather evidence** - Error messages, logs, stack traces +4. **Analyze the system** - Read code, understand flow +5. **Form hypothesis** - Why does this happen? +6. **Test hypothesis** - Prove or disprove your theory +7. **Fix with TDD** - Write test, implement fix, verify + +### Verification at Each Phase + +- After INVESTIGATE: Bug reproduces consistently +- After ANALYZE: You understand the code's intent and actual behavior +- After HYPOTHESIZE: Theory explains all symptoms +- After IMPLEMENT: Bug is fixed, tests pass, no regression + +## When to Use This Skill + +**Always use for:** +- Test failures (existing tests that started failing) +- Production bugs (unexpected behavior in live code) +- Integration issues (two components don't work together) +- Performance regressions (something got slower) +- Intermittent failures (flaky tests, race conditions) + +**This is the required approach for all debugging work.** + +## Integration with Other Skills + +**Chains to `dev-workflow:test-driven-development`:** +- Phase 1-3 (Investigate/Analyze/Hypothesize) identify root cause +- Phase 4 uses TDD to implement fix +- TDD's RED step writes test that exposes bug +- TDD's GREEN step implements minimal fix +- Result: Bug fixed + regression test added + +**Works with `dev-workflow:implementer`:** +- Implementer invokes systematic-debugging when tests fail +- Follows 4-phase framework to understand failure +- Uses TDD to implement fix + +**Works with `dev-workflow:subagent-driven-development`:** +- When verification step fails, orchestrator may invoke debugger +- Debugger identifies root cause, TDD implements fix +- Re-verify in main workflow loop + +## Anti-Patterns to Avoid + +❌ Trying random fixes hoping something works +❌ Fixing symptoms without understanding cause +❌ Skipping hypothesis phase and jumping to implementation +❌ Not reproducing the bug before claiming it's fixed +❌ Continuing past 3 failed attempts without reassessing +❌ Implementing fixes without tests + +## Success Criteria + +✅ Root cause is clearly identified and explained +✅ Hypothesis was tested and confirmed before fixing +✅ Fix has corresponding test that would catch regression +✅ Original reproduction steps now pass +✅ No new failures introduced +✅ If 3 attempts failed, escalation or reassessment occurred + +## Example Flow + +``` +BUG: User login fails with "Invalid token" error + +Phase 1 - INVESTIGATE +- Reproduced: POST /login with valid credentials → 401 +- Stack trace shows: TokenValidator.verify() throwing +- Works in dev, fails in staging +- Started failing after deploy 2 days ago + +Phase 2 - ANALYZE +- Read TokenValidator code: checks exp claim +- Token generation: sets exp to 1h from now +- Environment difference: staging uses UTC, dev uses local time +- Recent change: Updated time library 2 days ago + +Phase 3 - HYPOTHESIZE +Theory: New time library returns different timezone format, +causing exp claim to be misinterpreted in staging. + +Test: Add logging to show exact exp value and current time. +Result: Confirmed - exp is ISO string, validator expects Unix timestamp. + +Phase 4 - IMPLEMENT +→ Invoke dev-workflow:test-driven-development +→ RED: Write test with ISO exp format → expect to pass +→ GREEN: Update TokenValidator to handle both formats +→ REFACTOR: Clean up time handling +→ VERIFY: All tests pass, staging login works +``` diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md new file mode 100644 index 0000000..ba853c3 --- /dev/null +++ b/skills/test-driven-development/SKILL.md @@ -0,0 +1,94 @@ +--- +name: test-driven-development +description: Use when implementing any feature or bugfix, before writing implementation code +--- + +# Test-Driven Development + +## Iron Law + +**No production code without a failing test first.** + +You may only write production code to make a failing test pass. If there is no failing test, you must write one before implementing. + +## The Red-Green-Refactor Cycle + +### 1. Red - Write a Failing Test + +**Before any implementation:** +1. Write the smallest test that specifies the next piece of behavior +2. Run the test and verify it fails for the right reason +3. Confirm the failure message indicates what's missing + +**Checkpoint:** Test exists and fails with expected error message. + +### 2. Green - Make it Pass + +**Write minimal implementation:** +1. Write only enough code to make the test pass +2. No additional features or "might need later" code +3. Run the test and verify it passes + +**Checkpoint:** Test passes. All existing tests still pass. + +### 3. Refactor - Clean up + +**Improve without changing behavior:** +1. Remove duplication between test and implementation +2. Improve names, structure, and readability +3. Run all tests to verify behavior unchanged + +**Checkpoint:** All tests pass. Code is cleaner than before. + +## Process + +### Starting a Feature or Bugfix + +1. **Understand the requirement** - What behavior needs to exist or change? +2. **Write the test first** - Describe the expected behavior in test form +3. **Watch it fail** - Confirm current code doesn't already do this +4. **Implement minimally** - Make the test pass, nothing more +5. **Refactor** - Clean up while keeping tests green +6. **Repeat** - Next piece of behavior + +### Verification at Each Step + +- After RED: Test fails with clear, expected error +- After GREEN: This test passes, all tests pass +- After REFACTOR: All tests still pass, code improved + +## When to Use This Skill + +**Always use for:** +- New features (any size) +- Bug fixes (write test that exposes bug, then fix) +- Refactoring (tests prove behavior unchanged) +- API changes (test new contract first) + +**This is the default mode for implementation work.** + +## Integration with Other Skills + +**Works with `dev-workflow:systematic-debugging`:** +- Debugging finds root cause → TDD writes test that exposes it → TDD fixes it +- The test from TDD becomes the regression test + +**Works with `dev-workflow:implementer`:** +- Implementer follows TDD cycle for each task in the plan +- Each commit includes both test and implementation + +## Anti-Patterns to Avoid + +❌ Writing tests after implementation ("test-after") +❌ Writing implementation for "future needs" without tests +❌ Skipping the RED phase (assuming test would fail) +❌ Writing multiple tests before any implementation +❌ Committing code without tests + +## Success Criteria + +✅ Every production code change has a corresponding test +✅ Tests were written before the implementation +✅ Each test failed before its implementation was written +✅ All tests pass before moving to next requirement +✅ Code is clean and well-factored diff --git a/skills/using-git-worktrees/SKILL.md b/skills/using-git-worktrees/SKILL.md new file mode 100644 index 0000000..b73789f --- /dev/null +++ b/skills/using-git-worktrees/SKILL.md @@ -0,0 +1,364 @@ +--- +name: using-git-worktrees +description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - creates isolated git worktrees with smart directory selection and safety verification +--- + +# Using Git Worktrees + +## Iron Law + +**One worktree per feature branch to avoid git index conflicts.** + +When running multiple implementer agents in parallel or executing implementation plans with isolated workspaces, worktrees prevent git index conflicts and provide clean workspace isolation. + +## When to Use This Skill + +**Always use for:** +- Executing implementation plans with `dev-workflow:subagent-driven-development` +- Running multiple implementer agents in parallel +- Starting feature work that needs isolation from main workspace +- Working on multiple features simultaneously without switching branches + +**This prevents:** +- Git index conflicts between parallel agents +- Accidental changes to main branch workspace +- Stale file state when switching branches +- Build artifacts polluting git status + +## Why Worktrees + +Git worktrees allow multiple working directories for the same repository: + +- **Parallel Development**: Multiple agents can work simultaneously without conflicts +- **Clean Workspace**: Each feature gets its own directory with fresh state +- **Fast Switching**: No need to stash/commit when checking other branches +- **Isolated Builds**: Dependencies and artifacts stay separate per worktree + +## The Setup Process + +### Phase 1: Safety Checks + +**Verify current state is clean:** + +```bash +# Check if we're in a clean state +git status + +# Check if branch name already exists (local or remote) +git branch -a | grep feature-name +``` + +**Checkpoint:** Main repo is clean. Branch name is available. + +### Phase 2: Create Branch and Worktree + +**Create the feature branch:** + +```bash +# Create branch from current HEAD (usually main) +git branch feature-name +``` + +**Create worktree with smart directory naming:** + +```bash +# Sibling directory pattern: ../repo-feature-name +# Example: claude-code-workflows → ../claude-code-workflows-feature-auth + +cd /home/tbaker/workspace/claude-code-workflows +git worktree add ../claude-code-workflows-feature-auth feature-auth +``` + +**Directory naming convention:** +- Pattern: `../REPO_NAME-BRANCH_NAME` +- Example: `../claude-code-workflows-context-recovery` +- Keeps worktrees organized as siblings to main repo +- Easy to identify and clean up later + +**Checkpoint:** Worktree created. Directory exists. + +### Phase 3: Navigate and Verify + +**Navigate to worktree:** + +```bash +cd ../claude-code-workflows-feature-auth +``` + +**Verify worktree state:** + +```bash +# Confirm branch and clean state +git status + +# Verify worktree list +git worktree list +``` + +**Checkpoint:** In worktree directory. Branch is correct. State is clean. + +### Phase 4: Chain to Implementation Planning + +**Now that worktree is set up, chain to writing-plans:** + +``` +The worktree is ready. I'll now invoke the writing-plans skill +to create the implementation plan for [feature description]. +``` + +The implementation plan will execute in this isolated worktree, preventing any conflicts with the main workspace. + +## The Cleanup Process + +### After Feature is Complete + +**When work is merged or PR is created:** + +1. **Return to main repo:** + +```bash +cd /home/tbaker/workspace/claude-code-workflows +``` + +2. **Remove worktree:** + +```bash +# Remove worktree directory and unregister it +git worktree remove ../claude-code-workflows-feature-auth + +# Or if directory was manually deleted: +git worktree prune +``` + +3. **Delete branch (if merged):** + +```bash +# Delete local branch +git branch -d feature-auth + +# Delete remote branch if pushed +git push origin --delete feature-auth +``` + +**Checkpoint:** Worktree removed. Branch deleted if merged. + +### Cleanup Verification + +```bash +# List remaining worktrees +git worktree list + +# Should only show main worktree +``` + +## Common Commands Reference + +### Creating Worktrees + +```bash +# Create worktree for new branch +git worktree add ../repo-branch-name branch-name + +# Create worktree for existing branch +git worktree add ../repo-existing-branch existing-branch + +# Create worktree and new branch from specific commit +git worktree add -b new-branch ../repo-new-branch abc123 +``` + +### Managing Worktrees + +```bash +# List all worktrees +git worktree list + +# Remove specific worktree +git worktree remove ../repo-branch-name + +# Remove worktree (if already deleted manually) +git worktree prune + +# Remove worktree with uncommitted changes (force) +git worktree remove --force ../repo-branch-name +``` + +### Working in Worktrees + +```bash +# Navigate to worktree +cd ../repo-branch-name + +# All git commands work normally +git status +git add . +git commit -m "feat: implement feature" +git push origin branch-name + +# Return to main repo +cd /home/tbaker/workspace/claude-code-workflows +``` + +## Process Flow + +### Starting Feature Work with Worktree + +1. **Verify main repo state** - `git status` shows clean +2. **Check branch availability** - `git branch -a | grep feature-name` is empty +3. **Create feature branch** - `git branch feature-name` +4. **Create worktree** - `git worktree add ../repo-feature-name feature-name` +5. **Navigate to worktree** - `cd ../repo-feature-name` +6. **Verify worktree** - `git status`, `git worktree list` +7. **Chain to writing-plans** - Ready for implementation planning + +### Verification at Each Phase + +- After SAFETY CHECKS: Main clean, branch name available +- After CREATE: Worktree exists, branch created +- After NAVIGATE: In worktree directory, correct branch +- After CHAIN: Implementation plan can execute in isolation + +## Integration with Other Skills + +**Chains to `dev-workflow:writing-plans`:** +- Set up worktree first for isolated workspace +- Then invoke writing-plans in the worktree context +- Implementation plan executes in clean, isolated environment + +**Works with `dev-workflow:subagent-driven-development`:** +- Worktree provides isolated workspace for plan execution +- Prevents git index conflicts between parallel implementers +- Each task in plan works in same worktree context + +**Works with `dev-workflow:implementer`:** +- Implementer agents work in dedicated worktree +- No conflicts with main workspace or other agents +- Clean state for each feature branch + +## Anti-Patterns to Avoid + +❌ Creating worktree when main repo is dirty +❌ Using branch name that already exists +❌ Creating worktree in subdirectory of main repo +❌ Forgetting to navigate to worktree after creation +❌ Leaving worktrees around after feature is merged +❌ Using worktree for quick branch switches (just use `git switch`) +❌ Creating nested worktrees + +## Success Criteria + +✅ Main repo state is clean before worktree creation +✅ Branch name is unique (doesn't exist locally or remotely) +✅ Worktree created in sibling directory with clear naming +✅ Successfully navigated to worktree directory +✅ Worktree list shows both main and new worktree +✅ Implementation plan chains after worktree setup +✅ Cleanup performed after feature merge/completion + +## Example Flow + +``` +SCENARIO: Implementing new authentication feature with parallel agents + +Phase 1 - SAFETY CHECKS +$ cd /home/tbaker/workspace/claude-code-workflows +$ git status + → On branch main, working tree clean ✓ +$ git branch -a | grep feature-auth + → No output, branch name available ✓ + +Phase 2 - CREATE +$ git branch feature-auth +$ git worktree add ../claude-code-workflows-feature-auth feature-auth + → Preparing worktree (new branch 'feature-auth') + → Checking out files: 100% done +$ git worktree list + → /home/tbaker/workspace/claude-code-workflows [main] + → /home/tbaker/workspace/claude-code-workflows-feature-auth [feature-auth] + +Phase 3 - NAVIGATE +$ cd ../claude-code-workflows-feature-auth +$ git status + → On branch feature-auth, nothing to commit, working tree clean ✓ + +Phase 4 - CHAIN TO PLANNING +→ Invoke dev-workflow:writing-plans +→ Create implementation plan for authentication feature +→ Plan executes in isolated worktree +→ No conflicts with main workspace + +Phase 5 - CLEANUP (after merge) +$ cd /home/tbaker/workspace/claude-code-workflows +$ git worktree remove ../claude-code-workflows-feature-auth +$ git branch -d feature-auth +$ git worktree list + → /home/tbaker/workspace/claude-code-workflows [main] + → Worktree cleaned up ✓ +``` + +## Directory Naming Examples + +``` +Main repo: /home/tbaker/workspace/my-app +Worktrees: + ../my-app-feature-auth → Authentication feature + ../my-app-fix-login-bug → Bug fix branch + ../my-app-refactor-api → Refactoring work + ../my-app-add-tests → Test additions + +Main repo: /home/tbaker/workspace/claude-code-workflows +Worktrees: + ../claude-code-workflows-context-recovery + ../claude-code-workflows-pr-merge-improvements + ../claude-code-workflows-new-skill +``` + +## Troubleshooting + +### "Branch already exists" + +```bash +# Check where branch exists +git branch -a | grep branch-name + +# If local, use different name or delete old branch +git branch -d branch-name + +# If remote, fetch and use different name +git fetch origin +``` + +### "Worktree already exists" + +```bash +# List worktrees +git worktree list + +# Remove if stale +git worktree remove ../repo-branch-name + +# Or prune all stale worktrees +git worktree prune +``` + +### "Directory already exists" + +```bash +# Check if directory is a worktree +git worktree list | grep directory-name + +# If not a worktree, remove or use different name +rm -rf ../directory-name +``` + +### "Cannot remove worktree with uncommitted changes" + +```bash +# Option 1: Commit or stash changes +cd ../repo-branch-name +git add . +git commit -m "WIP: save work" + +# Option 2: Force remove (loses changes) +cd /home/tbaker/workspace/main-repo +git worktree remove --force ../repo-branch-name +``` diff --git a/skills/writing-plans/SKILL.md b/skills/writing-plans/SKILL.md new file mode 100644 index 0000000..6416894 --- /dev/null +++ b/skills/writing-plans/SKILL.md @@ -0,0 +1,452 @@ +--- +name: writing-plans +description: Use when you have a spec or requirements for a multi-step task, before touching code +--- + +# Writing Implementation Plans + +Create structured plans that chain to subagent-driven-development for execution. + +**Core principle:** Plan with bite-sized tasks, model recommendations, and TDD embedded. + +## When to Use + +- Have spec or requirements +- Task requires multiple steps (3+) +- Need to coordinate work across multiple files/components +- Want to ensure thorough testing and review + +**Don't use for:** +- Single-file, single-step changes (just implement) +- Trivial updates (config changes, version bumps) +- Exploratory work (use brainstorming first) + +## Plan Structure + +```markdown +# Implementation Plan: [Feature/Component Name] + +**Skill:** `dev-workflow:subagent-driven-development` + +## Overview +[1-2 sentences on what we're building and why] + +## Prerequisites +- [Required context, dependencies, or setup] + +## Phase 1: [Phase Name] +[Brief description of what this phase accomplishes] + +### Task 1.1: [Brief imperative title] +**Model:** haiku | sonnet | opus +**Complexity:** SIMPLE | STANDARD | COMPLEX + +[Description of what to implement] + +**Acceptance criteria:** +- [ ] [Specific, testable criterion] +- [ ] [Another criterion] + +**Testing approach:** [TDD steps or test types needed] + +### Task 1.2: [Next task] +... + +## Phase 2: [Next Phase Name] +... + +## Verification +- [ ] All tests pass +- [ ] Typecheck passes +- [ ] Build succeeds +- [ ] Manual testing: [specific scenarios] + +## Review Checkpoints +- After Phase 1: spec + quality review +- After Phase 2: spec + quality review +- Final: staff-code-reviewer (opus) +``` + +## Model Selection Guide + +Choose model based on task complexity: + +| Complexity | Model | When to Use | Indicators | +|------------|-------|-------------|------------| +| **SIMPLE** | haiku | Mechanical, low-risk | ≤2 files, config, types, boilerplate, doc updates | +| **STANDARD** | sonnet | Typical feature work | Multi-file, business logic, error handling, API changes | +| **COMPLEX** | sonnet/opus | High-risk or novel | Architecture changes, security, performance-critical, unfamiliar patterns | + +**Default to sonnet** unless the task clearly fits SIMPLE or explicitly requires COMPLEX reasoning. + +**Reserve opus for:** +- Staff-level reviews (phase boundaries, final review) +- Complex architectural decisions in implementation (rare) +- Main conversation orchestration + +## Task Structure + +### Anatomy of a Good Task + +```markdown +### Task 1.1: Add user authentication endpoint +**Model:** sonnet +**Complexity:** STANDARD + +Create POST /auth/login endpoint that validates credentials and returns JWT token. + +**Implementation details:** +- Accept email + password in request body +- Validate against database +- Return JWT with 1h expiration +- Return 401 for invalid credentials + +**Acceptance criteria:** +- [ ] Endpoint responds at POST /auth/login +- [ ] Valid credentials return 200 with JWT +- [ ] Invalid credentials return 401 +- [ ] Token includes user ID and expires in 1h + +**Testing approach:** +- RED: Write test for valid credentials → expect JWT +- GREEN: Implement validation and token generation +- RED: Write test for invalid credentials → expect 401 +- GREEN: Add error handling +- REFACTOR: Extract token generation to service +``` + +### What Makes a Task "Bite-Sized" + +✅ **Good task size:** +- Implementable in one focused session (30-60 min) +- Single responsibility or feature slice +- Clear acceptance criteria +- Self-contained (minimal dependencies on incomplete work) + +❌ **Too large:** +- "Implement entire authentication system" +- "Add user management" +- Multiple independent features bundled + +❌ **Too small:** +- "Add import statement" +- "Fix typo in comment" +- Trivial changes that aren't worth separate tasks + +### Task Dependencies + +**Prefer independent tasks** that can be worked on in any order. + +If dependencies exist: +```markdown +### Task 1.2: Add token refresh endpoint +**Model:** sonnet +**Complexity:** STANDARD +**Depends on:** Task 1.1 (uses same token generation) + +[Task description...] +``` + +## TDD Embedded in Tasks + +**Every task that writes code should specify testing approach.** + +### For Features (TDD Cycle) +```markdown +**Testing approach:** +- RED: Write test for [expected behavior] +- GREEN: Implement [minimal code to pass] +- RED: Write test for [edge case] +- GREEN: Handle [edge case] +- REFACTOR: [Extract/improve code] +``` + +### For Bugs (Systematic Debugging → TDD) +```markdown +**Testing approach:** +- Reproduce bug in failing test (exposes root cause) +- RED: Confirm test fails with bug present +- GREEN: Implement fix +- Verify original issue resolved +``` + +### For Refactoring (Test-First Safety) +```markdown +**Testing approach:** +- Ensure existing tests cover current behavior +- Add tests for edge cases if missing +- Refactor while keeping all tests green +``` + +## Phase Boundaries + +**Break work into phases when:** +- Natural checkpoint exists (e.g., "core implementation" then "integration") +- Want to review intermediate state before continuing +- Tasks in later phases depend on earlier ones + +**Review at phase boundaries:** +- SIMPLE-only phases: Skip phase review +- STANDARD+ phases: staff-code-reviewer (opus) + +## Anti-Patterns to Avoid + +❌ **Tasks too large** +- "Implement entire feature" → Break into smaller pieces +- Multiple independent changes → Separate tasks + +❌ **No model recommendations** +- Every task should specify haiku/sonnet/opus +- Defaults to sonnet if unspecified, but be explicit + +❌ **Missing testing approach** +- Tasks that write code must specify how to test +- TDD should be the default, not optional + +❌ **Vague acceptance criteria** +- "Works correctly" → Specify exactly what "works" means +- "Handles errors" → Which errors? What responses? + +❌ **No complexity classification** +- Needed for review path selection +- Helps estimate effort and choose model + +❌ **Sequential dependencies everywhere** +- Makes parallel work impossible +- Prefer independent tasks when possible + +## Example Plans + +### Example 1: Simple Feature (3 Tasks) + +```markdown +# Implementation Plan: Add Health Check Endpoint + +**Skill:** `dev-workflow:subagent-driven-development` + +## Overview +Add GET /health endpoint that returns service status and dependencies. + +## Prerequisites +- Express server already set up +- Database connection exists + +## Phase 1: Implementation + +### Task 1.1: Create health check endpoint +**Model:** haiku +**Complexity:** SIMPLE + +Add GET /health that returns 200 OK with JSON status. + +**Acceptance criteria:** +- [ ] GET /health returns 200 +- [ ] Response includes { status: "ok", timestamp: ISO string } + +**Testing approach:** +- RED: Request GET /health → expect 200 with status +- GREEN: Create endpoint handler +- REFACTOR: Extract status builder if needed + +### Task 1.2: Add database health check +**Model:** sonnet +**Complexity:** STANDARD + +Extend health endpoint to check database connectivity. + +**Acceptance criteria:** +- [ ] Health check attempts database ping +- [ ] Returns db: "healthy" if connection succeeds +- [ ] Returns db: "unhealthy" if connection fails +- [ ] Overall status is "ok" only if all checks pass + +**Testing approach:** +- RED: Test with healthy db → expect db: "healthy" +- GREEN: Implement db ping check +- RED: Test with failed db → expect db: "unhealthy" +- GREEN: Add error handling +- REFACTOR: Extract check logic to service + +### Task 1.3: Add documentation +**Model:** haiku +**Complexity:** SIMPLE + +Document the health check endpoint in API docs. + +**Acceptance criteria:** +- [ ] API.md includes GET /health +- [ ] Response format documented +- [ ] Status values explained + +**Testing approach:** N/A (documentation only) + +## Verification +- [ ] All tests pass +- [ ] GET /health returns correct format +- [ ] Manual test: kill database, verify unhealthy status + +## Review Checkpoints +- After Phase 1: spec + quality review +- Final: staff-code-reviewer (opus) +``` + +### Example 2: Multi-Phase Feature + +```markdown +# Implementation Plan: User Profile Management + +**Skill:** `dev-workflow:subagent-driven-development` + +## Overview +Implement CRUD operations for user profiles with validation and permissions. + +## Prerequisites +- User authentication system exists (JWT auth) +- Database schema includes users table + +## Phase 1: Core Profile Operations + +### Task 1.1: Create profile data model +**Model:** haiku +**Complexity:** SIMPLE + +Define TypeScript interface and database schema for user profiles. + +**Acceptance criteria:** +- [ ] Profile interface includes: name, email, bio, avatarUrl +- [ ] Database migration creates profiles table +- [ ] Foreign key to users table + +**Testing approach:** +- Verify migration runs successfully +- Verify schema matches interface + +### Task 1.2: Implement GET /profile/:id +**Model:** sonnet +**Complexity:** STANDARD + +Create endpoint to fetch user profile by ID. + +**Acceptance criteria:** +- [ ] GET /profile/:id returns profile data +- [ ] Returns 404 if profile doesn't exist +- [ ] Excludes sensitive fields (password, etc.) + +**Testing approach:** +- RED: Request existing profile → expect 200 with data +- GREEN: Implement fetch logic +- RED: Request missing profile → expect 404 +- GREEN: Add not-found handling +- REFACTOR: Extract data mapping to service + +### Task 1.3: Implement PUT /profile/:id +**Model:** sonnet +**Complexity:** STANDARD + +Create endpoint to update user profile with permission checks. + +**Acceptance criteria:** +- [ ] PUT /profile/:id updates profile fields +- [ ] Requires authentication +- [ ] Users can only update their own profile +- [ ] Returns 403 for unauthorized updates +- [ ] Validates input (email format, bio length, etc.) + +**Testing approach:** +- RED: Authenticated user updates own profile → expect 200 +- GREEN: Implement update logic +- RED: User tries to update different profile → expect 403 +- GREEN: Add permission check +- RED: Invalid input → expect 400 with validation errors +- GREEN: Add validation +- REFACTOR: Extract permission logic to middleware + +## Phase 2: Profile Features + +### Task 2.1: Add profile picture upload +**Model:** sonnet +**Complexity:** STANDARD + +Allow users to upload profile pictures with validation. + +**Acceptance criteria:** +- [ ] POST /profile/:id/avatar accepts image file +- [ ] Validates file type (jpg, png, max 5MB) +- [ ] Stores in S3/storage service +- [ ] Updates avatarUrl in profile +- [ ] Returns 400 for invalid files + +**Testing approach:** +- RED: Upload valid image → expect 200 with URL +- GREEN: Implement upload to storage +- RED: Upload invalid file → expect 400 +- GREEN: Add validation +- RED: Upload over size limit → expect 400 +- GREEN: Add size check +- REFACTOR: Extract upload logic to service + +### Task 2.2: Add profile search +**Model:** sonnet +**Complexity:** STANDARD + +Create endpoint to search profiles by name or email. + +**Acceptance criteria:** +- [ ] GET /profiles?q=query returns matching profiles +- [ ] Searches name and email fields +- [ ] Case-insensitive search +- [ ] Returns max 20 results +- [ ] Excludes private profiles + +**Testing approach:** +- RED: Search by name → expect matching results +- GREEN: Implement basic search +- RED: Search with case variations → expect same results +- GREEN: Make search case-insensitive +- REFACTOR: Extract query builder + +## Verification +- [ ] All tests pass (unit + integration) +- [ ] Typecheck passes +- [ ] Manual testing: CRUD operations work end-to-end +- [ ] Permission checks enforced + +## Review Checkpoints +- After Phase 1: spec + quality review +- After Phase 2: spec + quality review +- Final: staff-code-reviewer (opus) +``` + +## Integration + +**Creates plans for:** +- `dev-workflow:subagent-driven-development` - executes the plan + +**Works with:** +- `dev-workflow:brainstorming` - use before planning if requirements unclear +- `dev-workflow:test-driven-development` - embedded in task structure +- `dev-workflow:systematic-debugging` - for bug fix plans + +## Success Criteria + +✅ Plan has clear phases and bite-sized tasks +✅ Every task specifies model (haiku/sonnet/opus) +✅ Every task classified by complexity (SIMPLE/STANDARD/COMPLEX) +✅ Tasks that write code include testing approach +✅ Acceptance criteria are specific and testable +✅ Review checkpoints identified +✅ Plan chains to subagent-driven-development for execution + +## Chains To + +After writing plan, invoke: +``` +/skill dev-workflow:subagent-driven-development +``` + +The execution skill will: +1. Read this plan +2. Extract all tasks with model recommendations +3. Dispatch implementer per task (using recommended model) +4. Run verification and reviews at specified checkpoints +5. Complete implementation following the plan structure