
dev-workflow
Development workflow with TDD, debugging, and collaboration skills
Install
/plugin install dev-workflow@dot-claudeRun it inside Claude Code after adding the marketplace with /plugin marketplace add pproenca/dot-claude.
Contents
Discovered from sourceSkills 12
Condition-Based Waiting
Flaky tests often guess at timing with arbitrary delays.
Core principle: Wait for the actual condition that matters, not a guess about how long it takes.
Core Pattern
// ❌ BEFORE: Guessing at timing
await new Promise((r) => setTimeout(r, 50));
const result = getResult();
expect(result).toBeDefined();
// ✅ AFTER: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();
expect(result).toBeDefined();
Quick Patterns
| Scenario | Pattern |
|---|---|
| Wait for event | waitFor(() => events.find(e => e.type === 'DONE')) |
| Wait for state | waitFor(() => machine.state === 'ready') |
| Wait for count | waitFor(() => items.length >= 5) |
| Wait for file | waitFor(() => fs.existsSync(path)) |
Implementation
async function waitFor<T>(
condition: () => T | undefined | null | false,
description: string,
timeoutMs = 5000
): Promise<T> {
const startTime = Date.now();
while (true) {
const result = condition();
if (result) return result;
if (Date.now() - startTime > timeoutMs) {
throw new Error(
`Timeout waiting for ${description} after ${timeoutMs}ms`
);
}
await new Promise((r) => setTimeout(r, 10)); // Poll every 10ms
}
}
See examples/example.ts for domain-specific helpers (waitForEvent, waitForEventCount, waitForEventMatch).
Common Mistakes
| Mistake | Fix |
|---|---|
| Polling too fast (1ms) | Poll every 10ms |
| No timeout | Always include timeout with clear error |
| Stale data | Call getter inside loop for fresh data |
When Arbitrary Timeout IS Correct
When testing actual timing behavior:
// Tool ticks every 100ms - need 2 ticks
await waitForEvent(manager, "TOOL_STARTED"); // First: wait for condition
await new Promise((r) => setTimeout(r, 200)); // Then: wait for known timing
// 200ms = 2 ticks at 100ms - documented and justified
Requirements:
- First wait for triggering condition
- Based on known timing (not guessing)
- Comment explaining WHY
Integration
Referenced by systematic-debugging when flaky tests are identified.
Defense-in-Depth Validation
When fixing a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed.
Core principle: Validate at EVERY layer data passes through. Make the bug structurally impossible.
The Four Layers
Layer 1: Entry Point Validation
Reject obviously invalid input at API boundary:
function createProject(name: string, workingDirectory: string) {
if (!workingDirectory || workingDirectory.trim() === "") {
throw new Error("workingDirectory cannot be empty");
}
if (!existsSync(workingDirectory)) {
throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
}
}
Layer 2: Business Logic Validation
Ensure data makes sense for this operation:
function initializeWorkspace(projectDir: string, sessionId: string) {
if (!projectDir) {
throw new Error("projectDir required for workspace initialization");
}
}
Layer 3: Environment Guards
Prevent dangerous operations in specific contexts:
async function gitInit(directory: string) {
if (process.env.NODE_ENV === "test") {
const normalized = normalize(resolve(directory));
const tmpDir = normalize(resolve(tmpdir()));
if (!normalized.startsWith(tmpDir)) {
throw new Error(`Refusing git init outside temp dir during tests`);
}
}
}
Layer 4: Debug Instrumentation
Capture context for forensics:
async function gitInit(directory: string) {
logger.debug("About to git init", {
directory,
cwd: process.cwd(),
stack: new Error().stack,
});
}
Applying the Pattern
When fixing a bug:
- Trace data flow - Where does bad value originate? Where used?
- Map checkpoints - List every point data passes through
- Add validation at each layer - Entry, business, environment, debug
- Test each layer - Try to bypass layer 1, verify layer 2 catches it
Why Multiple Layers
Single validation: "We fixed the bug" Multiple layers: "We made the bug impossible"
Different layers catch different cases:
- Entry validation catches most bugs
- Business logic catches edge cases
- Environment guards prevent context-specific dangers
- Debug logging helps when other layers fail
Integration
Referenced by systematic-debugging after root cause is found. Add validation at each layer the data passed through.
Finishing a Development Branch
Guide completion of development work by presenting clear options.
When Invoked
After code review passes, tests pass, work is ready to integrate.
Invoked by:
- Post-completion actions (after execute-plan completes)
- Direct user request ("I'm done", "merge this", "create PR")
Step 1: Verify Tests
npm test # or cargo test / pytest / go test ./...
If tests fail: Stop. Cannot proceed until tests pass.
Step 2: Determine Base Branch
git merge-base HEAD main 2>/dev/null && BASE="main" || \
git merge-base HEAD master 2>/dev/null && BASE="master" || \
BASE="unknown"
If unknown, ask user which branch.
Step 3: Present Options
Use AskUserQuestion:
AskUserQuestion:
header: "Integration"
question: "Work complete. How to proceed?"
multiSelect: false
options:
- label: "Merge locally"
description: "Rebase onto base, fast-forward merge (linear history)"
- label: "Create PR"
description: "Push branch and create Pull Request"
- label: "Keep as-is"
description: "Preserve branch and worktree for later"
- label: "Discard"
description: "Delete branch and all commits"
Step 4: Execute Choice
Option: Merge locally
Uses rebase for linear history (stacked-diffs approach):
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
FEATURE="$(git branch --show-current)"
# Safety check: uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
echo "Error: Uncommitted changes. Commit first."
exit 1
fi
# SAFETY: Push branch to remote BEFORE rebase (prevents data loss)
echo "Pushing branch to remote before rebase..."
git push -u origin "$FEATURE" || {
echo "ERROR: Failed to push. Cannot proceed."
echo "This prevents data loss - all work must be on remote before rebase."
exit 1
}
# Verify push succeeded by comparing SHAs
LOCAL_SHA=$(git rev-parse "$FEATURE")
REMOTE_SHA=$(git ls-remote origin "$FEATURE" | cut -f1)
if [[ "$LOCAL_SHA" != "$REMOTE_SHA" ]]; then
echo "ERROR: Local and remote are out of sync. Push may have failed."
exit 1
fi
echo "Branch pushed successfully. Safe to proceed."
# Store original SHA for recovery reference
ORIGINAL_SHA="$LOCAL_SHA"
# Fetch latest changes
git fetch origin
# Rebase feature branch onto base (linear history)
echo "Rebasing $FEATURE onto origin/$BASE..."
if ! git rebase "origin/$BASE"; then
echo ""
echo "ERROR: Rebase conflict detected. Aborting rebase."
# Abort to restore working state
git rebase --abort
echo ""
echo "Your branch has been restored to its original state."
echo "Original commit: $ORIGINAL_SHA"
echo "Remote backup: origin/$FEATURE"
echo ""
echo "To resolve manually:"
echo " 1. git rebase origin/$BASE"
echo " 2. Resolve conflicts in each file"
echo " 3. git add <resolved-files>"
echo " 4. git rebase --continue"
echo " 5. Re-run this merge process"
exit 1
fi
echo "Rebase successful."
# Force push rebased branch (safe - we have backup on remote)
echo "Force pushing rebased branch..."
if ! git push --force-with-lease origin "$FEATURE"; then
echo "ERROR: Force push failed."
echo "This may happen if someone else pushed to this branch."
echo "Your rebased changes are still local."
echo "Remote backup exists at origin/$FEATURE (pre-rebase)"
exit 1
fi
# Get main repo path
MAIN_REPO="$(get_main_worktree)"
# If in worktree, go to main repo for the merge
if ! is_main_repo; then
cd "$MAIN_REPO"
fi
# Checkout base and fast-forward merge (no merge commit)
git checkout "$BASE"
git pull origin "$BASE" 2>/dev/null || true
echo "Fast-forward merging $FEATURE into $BASE..."
if ! git merge --ff-only "origin/$FEATURE"; then
echo "ERROR: Fast-forward merge failed."
echo "This should not happen after a successful rebase."
echo "The base branch may have changed. Try again."
exit 1
fi
npm test # verify merged result
If tests pass and was in worktree:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
# Clean up worktree if we were in one (not main repo)
if ! is_main_repo; then
# remove_worktree has safety checks for unpushed commits
remove_worktree
fi
Skip to Step 5.
Option: Create PR
FEATURE=$(git branch --show-current)
git push -u origin $FEATURE
gh pr create --title "[title]" --body "## Summary\n[changes]\n\n## Tests\n- All passing"
Proceed to Step 5.
Option: Keep as-is
Report branch and worktree location. Skip Step 5. Return.
Option: Discard
First, check for unpushed commits and warn user:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
FEATURE="$(git branch --show-current)"
# Check if branch has unpushed commits
if ! git ls-remote --heads origin "$FEATURE" 2>/dev/null | grep -q .; then
echo "WARNING: Branch '$FEATURE' has NEVER been pushed to remote!"
echo "Discarding will PERMANENTLY delete all work on this branch."
elif [[ -n "$(git log origin/$FEATURE..$FEATURE --oneline 2>/dev/null)" ]]; then
echo "WARNING: Branch '$FEATURE' has unpushed commits:"
git log "origin/$FEATURE..$FEATURE" --oneline
echo "Discarding will PERMANENTLY delete these commits."
fi
Then confirm with AskUserQuestion:
AskUserQuestion:
header: "Confirm"
question: "Discard all work on this branch? This CANNOT be undone."
multiSelect: false
options:
- label: "Yes, discard permanently"
description: "Delete branch and all commits - NO recovery possible"
- label: "Cancel"
description: "Return to integration options"
If user confirms discard:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
FEATURE="$(git branch --show-current)"
# If in worktree, go to main repo first
if ! is_main_repo; then
WORKTREE_PATH="$(pwd)"
MAIN_REPO="$(get_main_worktree)"
cd "$MAIN_REPO"
# Force remove worktree (user explicitly confirmed discard)
git worktree remove --force "$WORKTREE_PATH"
fi
# Force delete branch (user explicitly confirmed discard)
git checkout "$BASE"
git branch -D "$FEATURE"
Proceed to Step 5.
Step 5: Report Completion
Report:
Branch finished:
- Action: [Merged / PR created / Discarded]
- Branch: [name]
- Worktree: [cleaned up / preserved]
Return to caller.
Getting Started with Skills
Skill Discovery
Before starting any task, check if a skill exists for that task type:
| Task Type | Skill |
|---|---|
| New feature, bug fix, behavior change | test-driven-development |
| Bug, test failure, unexpected behavior | systematic-debugging |
| Deep call stack errors | root-cause-tracing |
| Flaky tests, race conditions | condition-based-waiting |
| Claiming work is done | verification-before-completion |
| Code review feedback received | receiving-code-review |
| Bug fix validation layers | defense-in-depth |
| Architecture, file organization | pragmatic-architecture |
| Test quality review | testing-anti-patterns |
| Git worktree operations | simple-git-worktrees |
| Branch completion, merge/PR | finishing-a-development-branch |
If a skill matches: load it with the Skill tool, then follow it.
Skill Priority
When multiple skills apply:
- Process skills first — determine HOW to approach (debugging, brainstorming)
- Implementation skills second — guide execution (TDD, architecture)
- Verification skills last — confirm results (verification-before-completion)
Examples:
- "Build X" → brainstorming first, then TDD
- "Fix bug" → systematic-debugging first, then TDD for the fix
- "Add feature" → TDD (implementation is the process)
Skill Types
Rigid (TDD, debugging, verification): Follow exactly. The structure IS the value.
Flexible (architecture, brainstorming): Adapt principles to context.
Checklists
If a skill contains a checklist, create tasks using TaskCreate for each step. Mental tracking leads to skipped steps.
Reference
See references/skill-integration.md for decision trees and skill chains.
Planning Workflows
Plugin Commands (Recommended)
/dev-workflow:brainstorm → /dev-workflow:write-plan → /dev-workflow:execute-plan
- Plans persist to
docs/plans/(version controlled, reviewable) - Parallel execution via
Task(run_in_background)+TaskOutput - Dependency tracking via
addBlockedBy - Post-completion: code review + finish branch enforced
- Resume: TaskList tracks progress
How Parallel Execution Works
- Create tasks with TaskCreate, express dependencies via addBlockedBy
- For each round of unblocked tasks:
- Launch with
Task(run_in_background: true) - Collect with
TaskOutput(block: true) - Mark completed with TaskUpdate
- Launch with
- Proceed to post-completion actions
When to Use EnterPlanMode Directly
Use EnterPlanMode without plugin commands for:
- Quick prototyping (plan doesn't need to persist)
- Simple 1-3 task features
- Interactive planning
For features needing plan persistence, code review, and resume capability, use the plugin commands flow.
Executing Existing Plans
- Read and validate the plan file
- Choose sequential or parallel execution
- After all tasks: code review → receiving-code-review → finishing-a-development-branch
Pragmatic Architecture
Design for today's requirements. Let complexity grow incrementally as needed.
The Four Principles
1. Rule of Three (Don Roberts)
"The first time, just do it. The second time, wince at duplication but do it anyway. The third time, refactor."
Abstract on the 3rd occurrence, not before.
| Occurrences | Action |
|---|---|
| 1 | Implement directly |
| 2 | Duplicate, note similarity |
| 3+ | Now extract abstraction |
2. AHA - Avoid Hasty Abstractions (Kent C. Dodds)
"Prefer duplication over the wrong abstraction." — Sandi Metz
Duplication is cheaper than the wrong abstraction. Wrong abstractions accumulate parameters and conditionals until unmaintainable.
Signs of wrong abstraction:
- Adding parameters to handle "just one more case"
- Conditional paths through shared code
- Comments explaining which caller uses which path
Recovery: Inline the abstraction, re-duplicate, let the right pattern emerge.
3. YAGNI - You Ain't Gonna Need It (Ron Jeffries)
"Always implement things when you actually need them, never when you just foresee that you need them."
No hooks for future features. No "we might need this someday."
| ❌ Speculative | ✅ Pragmatic |
|---|---|
options?: ExtensionConfig unused | Add when extension exists |
| Abstract factory for one impl | Direct instantiation |
| Event system for single listener | Direct call |
| Plugin architecture for no plugins | Hardcoded behavior |
4. Colocation (Kent C. Dodds)
"Place code as close to where it's relevant as possible."
Minimize file splitting. Keep related code together.
| ❌ Over-split | ✅ Colocated |
|---|---|
types/user.ts, utils/user.ts, constants/user.ts | Single user.ts with all |
Separate styles/, hooks/, utils/ folders | Component folder with all related |
| 10 files for one feature | 1-3 files max per feature |
Decision Framework
Before creating abstraction, ask:
1. Does this exist 3+ times? → No? Don't abstract
2. Are the use cases truly identical? → No? Don't abstract
3. Would someone unfamiliar understand this? → No? Simpler design
4. Am I solving today's problem? → No? YAGNI
File Organization Rules
Prefer:
- Feature-based folders over type-based folders
- Fewer, larger files over many tiny files
- Colocated tests (
foo.test.tsnext tofoo.ts) - Single source of truth per concept
Avoid:
types/,utils/,constants/,helpers/folders that scatter related code- Files under 50 lines (usually should be merged)
- More than 3 files per feature (unless genuinely complex)
Anti-Patterns to Block
Speculative Generality (Fowler)
"Oh, I think we'll need the ability to do this someday"
Symptoms: Abstract classes doing nothing, unused parameters, delegation that could be direct.
Block: Any "for future use" justification.
Shotgun Surgery (Fowler)
"One change requires modifications across many files"
Caused by over-splitting. Fix by consolidating related code.
Block: Designs requiring 5+ file changes for simple features.
Premature Abstraction
Creating BaseHandler, AbstractService, GenericRepository before concrete needs exist.
Block: Any abstract class without 2+ concrete implementations in the plan.
Output Requirements
When designing architecture:
- Justify every new file — Why can't this live in an existing file?
- Justify every abstraction — Where are the 3 concrete uses?
- Prefer boring — Standard patterns over clever solutions
- Count the files — If feature needs 5+ files, reconsider
References
For detailed patterns and examples:
references/file-organization.md— Colocated vs scattered patternsreferences/abstraction-examples.md— Good vs bad abstraction decisions
Receiving Code Review
Process code review feedback with technical evaluation, not emotional performance.
When Invoked
This skill is invoked after code-reviewer agent returns output. This skill processes the feedback.
The Response Pattern
- Read - Complete feedback without reacting
- Categorize - Critical / Important / Minor
- Verify - Check each issue against codebase
- Evaluate - Technically sound for THIS codebase?
- Respond - Acknowledge valid, push back if wrong
- Implement - One fix at a time, test each
Processing Feedback
Categorize
From code-reviewer output, separate issues:
| Category | Action | Examples |
|---|---|---|
| Critical | Fix immediately | Security, data loss, broken functionality |
| Important | Fix before proceeding | Architecture, missing tests, error handling |
| Minor | Note for later | Style, optimization, documentation |
Verify Each Issue
For each Critical and Important issue:
# Check if the issue is real
# Read the file/line mentioned
# Determine if feedback is accurate
Questions to ask:
- Does this file/line exist?
- Is the described problem present?
- Would the suggested fix work?
- Does this break existing functionality?
Evaluate
For each verified issue:
If valid:
- Note the fix needed
- Add to implementation queue
If unclear:
- STOP
- Do not guess
- Ask for clarification on ALL unclear items before implementing any
If wrong:
- Note why (technical reasoning)
- Do not implement
- Push back in summary
Forbidden Responses
Never say:
- "You're absolutely right!"
- "Great point!"
- "Thanks for catching that!"
Instead: Restate the technical requirement, or fix silently.
Implementing Fixes
Order of implementation:
- All unclear items clarified first - Partial understanding = wrong implementation
- Critical issues - Security, data loss, broken functionality
- Simple fixes - Typos, imports, obvious errors
- Complex fixes - Refactoring, architecture changes
For each fix:
# 1. Implement the fix
# 2. Run tests
npm test # or project test command
# 3. If tests pass, commit
git add -A && git commit -m "fix: [description from review]"
# 4. Next fix
Do not batch fixes. One fix, one test run, one commit.
Pushing Back
Push back when:
- Suggestion breaks existing functionality
- Reviewer lacks context visible in codebase
- Violates YAGNI (adding unused feature)
- Technically incorrect for this stack/framework
How to push back:
Issue: "[reviewer's concern]"
Response: Not implementing. [Technical reasoning with code references]
Reference working tests, existing patterns, or documentation.
Handling External Reviewers
Before implementing external feedback:
- Check: Technically correct for THIS codebase?
- Check: Breaks existing functionality?
- Check: Reviewer understand full context?
External reviewers may not know:
- Project conventions
- Existing patterns
- Why something was done a certain way
Verify before implementing.
Acknowledging Correct Feedback
✅ "Fixed. [Brief description]"
✅ [Just fix it silently]
❌ "You're absolutely right!"
❌ "Thanks for [anything]"
Actions speak. The code shows the feedback was heard.
Summary Output
After processing all feedback, report:
Review processed:
- Critical: [N] found, [M] fixed
- Important: [N] found, [M] fixed
- Minor: [N] noted for later
- Pushed back: [N] (not valid for this codebase)
All fixes verified with tests.
Integration
Uses:
dev-workflow:verification-before-completion- Verify each fix before next
Receives from:
dev-workflow:code-revieweragent output
Root Cause Tracing
Overview
Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). The instinct is to fix where the error appears, but that's treating a symptom.
Core principle: Trace backward through the call chain until finding the original trigger, then fix at the source.
When to Use
digraph when_to_use {
"Bug appears deep in stack?" [shape=diamond];
"Can trace backwards?" [shape=diamond];
"Fix at symptom point" [shape=box];
"Trace to original trigger" [shape=box];
"BETTER: Also add defense-in-depth" [shape=box];
"Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
"Can trace backwards?" -> "Trace to original trigger" [label="yes"];
"Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
"Trace to original trigger" -> "BETTER: Also add defense-in-depth";
}
Use when:
- Error happens deep in execution (not at entry point)
- Stack trace shows long call chain
- Unclear where invalid data originated
- Need to find which test/code triggers the problem
The Tracing Process
1. Observe the Symptom
Error: git init failed in /Users/jesse/project/packages/core
2. Find Immediate Cause
What code directly causes this?
await execFileAsync("git", ["init"], { cwd: projectDir });
3. Ask: What Called This?
WorktreeManager.createSessionWorktree(projectDir, sessionId)
→ called by Session.initializeWorkspace()
→ called by Session.create()
→ called by test at Project.create()
4. Keep Tracing Up
What value was passed?
projectDir = ''(empty string!)- Empty string as
cwdresolves toprocess.cwd() - That's the source code directory!
5. Find Original Trigger
Where did empty string come from?
const context = setupCoreTest(); // Returns { tempDir: '' }
Project.create("name", context.tempDir); // Accessed before beforeEach!
Adding Stack Traces
When manual tracing fails, add instrumentation:
// Before the problematic operation
async function gitInit(directory: string) {
const stack = new Error().stack;
console.error("DEBUG git init:", {
directory,
cwd: process.cwd(),
nodeEnv: process.env.NODE_ENV,
stack,
});
await execFileAsync("git", ["init"], { cwd: directory });
}
Critical: Use console.error() in tests (not logger - may not show)
Run and capture:
npm test 2>&1 | grep 'DEBUG git init'
Analyze stack traces:
- Look for test file names
- Find the line number triggering the call
- Identify the pattern (same test? same parameter?)
Finding Which Test Causes Pollution
If something appears during tests but the source test is unknown:
Use the bisection script: @find-polluter.sh
./find-polluter.sh '.git' 'src/**/*.test.ts'
Runs tests one-by-one, stops at first polluter. See script for usage.
Real Example: Empty projectDir
Symptom: .git created in packages/core/ (source code)
Trace chain:
git initruns inprocess.cwd()← empty cwd parameter- WorktreeManager called with empty projectDir
- Session.create() passed empty string
- Test accessed
context.tempDirbefore beforeEach - setupCoreTest() returns
{ tempDir: '' }initially
Root cause: Top-level variable initialization accessing empty value
Fix: Made tempDir a getter that throws if accessed before beforeEach
Also added defense-in-depth:
- Layer 1: Project.create() validates directory
- Layer 2: WorkspaceManager validates not empty
- Layer 3: NODE_ENV guard refuses git init outside tmpdir
- Layer 4: Stack trace logging before git init
Key Principle
digraph principle {
"Found immediate cause" [shape=ellipse];
"Can trace one level up?" [shape=diamond];
"Trace backwards" [shape=box];
"Is this the source?" [shape=diamond];
"Fix at source" [shape=box];
"Add validation at each layer" [shape=box];
"Bug impossible" [shape=doublecircle];
"NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Found immediate cause" -> "Can trace one level up?";
"Can trace one level up?" -> "Trace backwards" [label="yes"];
"Can trace one level up?" -> "NEVER fix just the symptom" [label="no"];
"Trace backwards" -> "Is this the source?";
"Is this the source?" -> "Trace backwards" [label="no - keeps going"];
"Is this the source?" -> "Fix at source" [label="yes"];
"Fix at source" -> "Add validation at each layer";
"Add validation at each layer" -> "Bug impossible";
}
NEVER fix just where the error appears. Trace back to find the original trigger.
Stack Trace Tips
In tests: Use console.error() not logger - logger may be suppressed
Before operation: Log before the dangerous operation, not after it fails
Include context: Directory, cwd, environment variables, timestamps
Capture stack: new Error().stack shows complete call chain
Simple Git Worktrees
Guide Claude in creating and managing git worktrees using a simple sibling directory pattern.
When to Use Worktrees
Use worktrees for:
- Parallel development on multiple branches
- Reviewing PRs while preserving current work
- Running tests on different branches simultaneously
- Isolating experimental changes
The Sibling Directory Pattern
Worktrees are created as sibling directories alongside the main repository following the repo--branch naming convention:
parent/
├── my-project/ # Main repository
├── my-project--feature/ # Worktree for 'feature' branch
├── my-project--bugfix/ # Worktree for 'bugfix' branch
└── my-project--review/ # Worktree for reviewing PR
Benefits:
- Lives alongside main repo (easy to find and navigate)
- Name encodes branch (self-documenting, no guesswork)
- No special permissions needed (just sibling directories)
- Standard shell tools work (cd, ls, find)
- Pattern validation prevents accidental deletions
Creating Worktrees
Basic Creation
Use worktree-manager.sh for safe, validated creation:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
# Create worktree for branch
BRANCH="feature-name"
WORKTREE_PATH=$(create_worktree "$BRANCH")
# Switch to worktree
cd "$WORKTREE_PATH"
What happens:
- Calculates sibling path:
../repo--branch - Checks if path already exists (prevents overwrites)
- Creates worktree with new branch:
git worktree add -b "$BRANCH" "$PATH" - Returns full path to worktree
Manual creation (without script):
# Get current repo name
REPO_BASE="$(basename "$PWD")"
BRANCH="feature-name"
# Calculate sibling path
WORKTREE_PATH="../${REPO_BASE}--${BRANCH}"
# Create worktree
git worktree add -b "$BRANCH" "$WORKTREE_PATH"
# Switch to it
cd "$WORKTREE_PATH"
Creating from Existing Branch
Create worktree for branch that already exists:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
REPO_BASE="$(basename "$PWD")"
EXISTING_BRANCH="main"
WORKTREE_PATH="../${REPO_BASE}--review-main"
# Create without -b flag (branch exists)
git worktree add "$WORKTREE_PATH" "$EXISTING_BRANCH"
cd "$WORKTREE_PATH"
Removing Worktrees
CRITICAL: Always check for unpushed commits before removing worktrees.
Safe Removal with Validation
Use remove_worktree() for safety-checked removal:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
# MUST be inside a worktree directory (not main repo)
cd "../repo--feature"
# Remove with safety checks
remove_worktree
Safety checks performed:
- Confirms currently in worktree (not main repo)
- Validates directory matches
repo--branchpattern - Checks for unpushed commits (prevents data loss)
- Removes worktree and deletes branch
Manual Removal Process
If removing manually (without script):
# 1. Verify in worktree
if git rev-parse --git-dir | grep -q "worktrees"; then
echo "In worktree"
else
echo "ERROR: Not in worktree"
exit 1
fi
# 2. Get current directory name
WORKTREE_DIR="$(basename "$PWD")"
# 3. Parse pattern
if [[ "$WORKTREE_DIR" == *--* ]]; then
REPO="${WORKTREE_DIR%%--*}"
BRANCH="${WORKTREE_DIR#*--}"
else
echo "ERROR: Invalid pattern (missing --)"
exit 1
fi
# 4. Check for unpushed commits
if ! git push --dry-run 2>&1 | grep -q "Everything up-to-date"; then
echo "ERROR: Unpushed commits detected"
echo "Push first: git push origin $BRANCH"
exit 1
fi
# 5. Return to main repo
cd "../$REPO"
# 6. Remove worktree and branch
git worktree remove "$WORKTREE_DIR"
git branch -d "$BRANCH"
Safety Features
Unpushed Commit Detection
Before removing any worktree, verify work is pushed:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
# Check if worktree has unpushed commits
if check_unpushed_commits "$WORKTREE_PATH"; then
echo "Safe to remove"
else
echo "Has unpushed commits - push first"
fi
What it checks:
- Branch exists on remote (has been pushed at least once)
- No commits exist locally that aren't on remote
- Prevents accidental data loss
Pattern Validation
Validate directory names before operations:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
# Validate naming pattern
if validate_worktree_pattern "myrepo--feature"; then
echo "Valid worktree pattern"
else
echo "Invalid pattern - should be repo--branch"
fi
Valid patterns:
repo--branchmy-repo--my-featureproject123--bugfix-auth
Invalid patterns:
repo(no--separator)--branch(missing repo name)repo--(missing branch name)
Repository Detection
Determine if currently in main repo or worktree:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
if is_main_repo; then
echo "In main repository"
else
echo "In linked worktree"
fi
Use this to prevent operations in wrong location.
Integration with Plan Execution
When executing implementation plans via /dev-workflow:execute-plan, worktrees provide isolation:
Workflow:
- User runs
/dev-workflow:execute-plan plan-file.md - Command detects if in main repo
- Asks user: "Create isolated worktree session for this work?"
- If yes:
- Creates worktree:
../repo--branch - Switches to worktree:
cd ../repo--branch - Continues execution in worktree (current session)
- Creates worktree:
- Work proceeds isolated from main repo
- After completion, option to merge or create PR
No Terminal spawning: Everything happens in current session.
Common Workflows
Reviewing a Pull Request
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
# Fetch PR branch
git fetch origin pull/123/head:pr-123
# Create worktree for review
WORKTREE_PATH=$(create_worktree "pr-123")
cd "$WORKTREE_PATH"
# Review code, run tests, etc.
# When done
remove_worktree
Parallel Development
# Main repo: working on feature-a
cd ~/projects/myapp
# Need to fix urgent bug without losing feature-a work
cd ..
WORKTREE_PATH=$(create_worktree "hotfix-login")
cd "myapp--hotfix-login"
# Fix bug, commit, push
git add .
git commit -m "fix: login validation"
git push origin hotfix-login
# Return to main work
cd ../myapp
Cleaning Up Old Worktrees
List all worktrees:
git worktree list
For each old worktree:
cd ../repo--old-branch
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
remove_worktree # Includes safety checks
Troubleshooting
"Path exists" Error
Problem: Trying to create worktree but path already exists
Solution: Remove or rename existing directory first
# Check what's there
ls -la ../repo--branch
# If it's an old worktree
cd ../repo--branch
remove_worktree
# If it's not a worktree, manually remove
rm -rf ../repo--branch
"Not in worktree" Error
Problem: Trying to remove from main repo
Solution: Only run remove_worktree() from inside a worktree directory
# Check current location
pwd
basename "$(pwd)" # Should match repo--branch pattern
# Navigate to worktree first
cd ../repo--branch
remove_worktree
"Invalid pattern" Error
Problem: Directory doesn't match repo--branch naming
Solution: Only remove worktrees created with standard pattern
This error prevents accidental deletion of unrelated directories.
"Unpushed commits" Error
Problem: Worktree has commits not pushed to remote
Solution: Push commits before removing
# Push commits
git push origin branch-name
# Then remove
remove_worktree
Quick Reference
Create worktree:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
WORKTREE_PATH=$(create_worktree "branch-name")
cd "$WORKTREE_PATH"
Remove worktree:
cd ../repo--branch
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
remove_worktree
List worktrees:
git worktree list
Check for unpushed commits:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
check_unpushed_commits "$WORKTREE_PATH"
Validate pattern:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
validate_worktree_pattern "$(basename "$PWD")"
Detect if in worktree:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
is_main_repo && echo "main" || echo "worktree"
Best Practices
- Always source worktree-manager.sh - Use helper functions for safety
- Check for unpushed commits - Never lose work by removing too early
- Follow naming pattern - Keep
repo--branchconvention for clarity - Clean up regularly - Remove merged worktrees to avoid clutter
- One worktree per branch - Don't create multiple worktrees for same branch
- Stay in current session - No need for new terminals or windows
- Push before removing - Safety check prevents data loss
Systematic Debugging
Find root cause before attempting fixes. Symptom fixes mask underlying issues.
The Four Phases
Phase 1: Root Cause Investigation
Before attempting any fix:
- Read error messages carefully — they often contain the solution. Read stack traces completely; note line numbers, file paths, error codes.
- Reproduce consistently — exact steps, every time. If not reproducible, gather more data.
- Check recent changes — git diff, new dependencies, config changes, environmental differences.
- Trace data flow — where does the bad value originate? For deep call stack errors, use the root-cause-tracing skill.
For multi-component systems, add diagnostic logging at each component boundary before proposing fixes. Log what enters and exits each component.
Phase 2: Pattern Analysis
- Find working examples — similar working code in the same codebase.
- Compare against references — read reference implementations completely, not skimmed.
- Identify differences — list every difference, however small.
- Understand dependencies — settings, config, environment assumptions.
Phase 3: Hypothesis and Testing
- Form single hypothesis — "I think X is the root cause because Y."
- Test minimally — smallest possible change, one variable at a time.
- Verify — didn't work? Form new hypothesis. Don't stack fixes.
Phase 4: Implementation
- Create failing test — simplest reproduction. Use the test-driven-development skill.
- Implement single fix — address the root cause. One change at a time. No "while I'm here" improvements.
- Verify fix — test passes, no other tests broken, issue resolved.
- If fix doesn't work — return to Phase 1 with new information. If 3+ fixes have failed, see below.
When 3+ Fixes Fail: Question Architecture
If each fix reveals a new problem in a different place, this is not a failed hypothesis — it's a wrong architecture.
Stop and question fundamentals:
- Is this pattern fundamentally sound?
- Are we sticking with it through inertia?
- Should we refactor architecture vs. continue fixing symptoms?
Discuss with the user before attempting more fixes. Present findings: "3 fix attempts, each revealed new problem."
Quick Reference
| Phase | Key Activities | Success Criteria |
|---|---|---|
| 1. Root Cause | Read errors, reproduce, trace | Understand WHAT and WHY |
| 2. Pattern | Find working examples, compare | Identify differences |
| 3. Hypothesis | Form theory, test minimally | Confirmed or new hypothesis |
| 4. Implementation | Create test, fix, verify | Bug resolved, tests pass |
Red Flags — Stop and Return to Phase 1
- Proposing fixes before tracing data flow
- "Quick fix for now, investigate later"
- "I don't fully understand but this might work"
- Each fix reveals a new problem in a different place
- 3+ failed fix attempts without questioning architecture
Integration
- root-cause-tracing — for deep call stack errors (Phase 1)
- test-driven-development — for failing test case (Phase 4)
- defense-in-depth — add validation layers after fix
- verification-before-completion — verify fix before claiming success
Test-Driven Development (TDD)
Write the test first. Watch it fail. Write minimal code to pass.
If you wrote implementation code before the test, discard it and start fresh from the test.
The Cycle: Red → Green → Refactor
RED — Write Failing Test
Write one minimal test showing what should happen.
Good:
test("retries failed operations 3 times", async () => {
let attempts = 0;
const operation = () => {
attempts++;
if (attempts < 3) throw new Error("fail");
return "success";
};
const result = await retryOperation(operation);
expect(result).toBe("success");
expect(attempts).toBe(3);
});
Clear name, tests real behavior, one thing.
Bad:
test("retry works", async () => {
const mock = jest
.fn()
.mockRejectedValueOnce(new Error())
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce("success");
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(3);
});
Vague name, tests mock not code.
Requirements:
- One behavior per test
- Clear name describing behavior
- Real code (mocks only if unavoidable)
Verify RED — Run and Confirm Failure
npm test path/to/test.test.ts
Confirm:
- Test fails (not errors from typos)
- Failure is because the feature is missing
- If test passes immediately: you're testing existing behavior — fix the test
GREEN — Minimal Code
Write the simplest code to pass the test. Nothing more.
Good:
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
for (let i = 0; i < 3; i++) {
try {
return await fn();
} catch (e) {
if (i === 2) throw e;
}
}
throw new Error("unreachable");
}
Bad:
async function retryOperation<T>(
fn: () => Promise<T>,
options?: {
maxRetries?: number;
backoff?: "linear" | "exponential";
onRetry?: (attempt: number) => void;
}
): Promise<T> { /* YAGNI */ }
Don't add features, refactor other code, or "improve" beyond the test.
Verify GREEN — Run and Confirm Pass
npm test path/to/test.test.ts
Confirm: test passes, other tests still pass, output clean.
If test fails: fix code, not test. If other tests fail: fix now.
REFACTOR — Clean Up (Green Only)
Remove duplication, improve names, extract helpers. Keep tests green.
Repeat
Next failing test for next behavior.
Why Test-First Matters
Tests written after code pass immediately — proving nothing. You never see them catch the bug they're supposed to catch. Test-first forces you to see the failure, proving the test actually validates behavior.
Tests-after are biased by your implementation: you test what you built, not what's required. Tests-first force edge case discovery before implementing.
If the test is hard to write, the design is telling you something — the interface is too complex.
Good Tests
| Quality | Good | Bad |
|---|---|---|
| Minimal | One thing per test | test('validates email and domain and whitespace') |
| Clear | Name describes behavior | test('test1') |
| Shows intent | Demonstrates desired API | Obscures what code should do |
| Real code | Tests actual behavior | Tests mock behavior |
When Stuck
| Problem | Solution |
|---|---|
| Don't know how to test | Write wished-for API. Write assertion first. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. Still complex? Simplify design. |
Bug Fix Example
Bug: Empty email accepted
RED:
test("rejects empty email", async () => {
const result = await submitForm({ email: "" });
expect(result.error).toBe("Email required");
});
Verify RED: FAIL: expected 'Email required', got undefined
GREEN:
function submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: "Email required" };
}
// ...
}
Verify GREEN: PASS
REFACTOR: Extract validation for multiple fields if needed.
Verification Checklist
Before marking work complete:
- Every new function has a test
- Watched each test fail before implementing
- Each test failed for expected reason (feature missing, not typo)
- Wrote minimal code to pass each test
- All tests pass, output clean
- Tests use real code (mocks only if unavoidable)
- Edge cases and errors covered
Integration
- testing-anti-patterns — reviewing existing test quality
- systematic-debugging — write failing test reproducing bug
- verification-before-completion — verify tests pass before claiming done
Testing Anti-Patterns
Tests must verify real behavior, not mock behavior. Mocks are tools to isolate, not things to test.
Following strict TDD prevents these anti-patterns.
Anti-Pattern 1: Testing Mock Behavior
The violation:
// ❌ BAD: Testing that the mock exists
test('renders sidebar', () => {
render(<Page />);
expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
});
Why this is wrong:
- You're verifying the mock works, not that the component works
- Test passes when mock is present, fails when it's not
- Tells you nothing about real behavior
The fix:
// ✅ GOOD: Test real component or don't mock it
test('renders sidebar', () => {
render(<Page />); // Don't mock sidebar
expect(screen.getByRole('navigation')).toBeInTheDocument();
});
// OR if sidebar must be mocked for isolation:
// Don't assert on the mock - test Page's behavior with sidebar present
Gate Function
BEFORE asserting on any mock element:
Ask: "Am I testing real component behavior or just mock existence?"
IF testing mock existence:
STOP - Delete the assertion or unmock the component
Test real behavior instead
Anti-Pattern 2: Test-Only Methods in Production
The violation:
// ❌ BAD: destroy() only used in tests
class Session {
async destroy() { // Looks like production API!
await this._workspaceManager?.destroyWorkspace(this.id);
// ... cleanup
}
}
// In tests
afterEach(() => session.destroy());
Why this is wrong:
- Production class polluted with test-only code
- Dangerous if accidentally called in production
- Violates YAGNI and separation of concerns
- Confuses object lifecycle with entity lifecycle
The fix:
// ✅ GOOD: Test utilities handle test cleanup
// Session has no destroy() - it's stateless in production
// In test-utils/
export async function cleanupSession(session: Session) {
const workspace = session.getWorkspaceInfo();
if (workspace) {
await workspaceManager.destroyWorkspace(workspace.id);
}
}
// In tests
afterEach(() => cleanupSession(session));
Gate Function
BEFORE adding any method to production class:
Ask: "Is this only used by tests?"
IF yes:
STOP - Don't add it
Put it in test utilities instead
Ask: "Does this class own this resource's lifecycle?"
IF no:
STOP - Wrong class for this method
Anti-Pattern 3: Mocking Without Understanding
The violation:
// ❌ BAD: Mock breaks test logic
test('detects duplicate server', () => {
// Mock prevents config write that test depends on!
vi.mock('ToolCatalog', () => ({
discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
}));
await addServer(config);
await addServer(config); // Should throw - but won't!
});
Why this is wrong:
- Mocked method had side effect test depended on (writing config)
- Over-mocking to "be safe" breaks actual behavior
- Test passes for wrong reason or fails mysteriously
The fix:
// ✅ GOOD: Mock at correct level
test('detects duplicate server', () => {
// Mock the slow part, preserve behavior test needs
vi.mock('MCPServerManager'); // Just mock slow server startup
await addServer(config); // Config written
await addServer(config); // Duplicate detected ✓
});
Gate Function
BEFORE mocking any method:
STOP - Don't mock yet
1. Ask: "What side effects does the real method have?"
2. Ask: "Does this test depend on any of those side effects?"
3. Ask: "Do I fully understand what this test needs?"
IF depends on side effects:
Mock at lower level (the actual slow/external operation)
OR use test doubles that preserve necessary behavior
NOT the high-level method the test depends on
IF unsure what test depends on:
Run test with real implementation FIRST
Observe what actually needs to happen
THEN add minimal mocking at the right level
Red flags:
- "I'll mock this to be safe"
- "This might be slow, better mock it"
- Mocking without understanding the dependency chain
Anti-Pattern 4: Incomplete Mocks
The violation:
// ❌ BAD: Partial mock - only fields you think you need
const mockResponse = {
status: 'success',
data: { userId: '123', name: 'Alice' }
// Missing: metadata that downstream code uses
};
// Later: breaks when code accesses response.metadata.requestId
Why this is wrong:
- Partial mocks hide structural assumptions - You only mocked fields you know about
- Downstream code may depend on fields you didn't include - Silent failures
- Tests pass but integration fails - Mock incomplete, real API complete
- False confidence - Test proves nothing about real behavior
Mock the COMPLETE data structure as it exists in reality.
The fix:
// ✅ GOOD: Mirror real API completeness
const mockResponse = {
status: 'success',
data: { userId: '123', name: 'Alice' },
metadata: { requestId: 'req-789', timestamp: 1234567890 }
// All fields real API returns
};
Gate Function
BEFORE creating mock responses:
Check: "What fields does the real API response contain?"
Actions:
1. Examine actual API response from docs/examples
2. Include ALL fields system might consume downstream
3. Verify mock matches real response schema completely
Critical:
If you're creating a mock, you must understand the ENTIRE structure
Partial mocks fail silently when code depends on omitted fields
If uncertain: Include all documented fields
Anti-Pattern 5: Integration Tests as Afterthought
The violation:
✅ Implementation complete
❌ No tests written
"Ready for testing"
Why this is wrong:
- Testing is part of implementation, not optional follow-up
- TDD would have caught this
- Can't claim complete without tests
The fix:
TDD cycle:
1. Write failing test
2. Implement to pass
3. Refactor
4. THEN claim complete
When Mocks Become Too Complex
Warning signs:
- Mock setup longer than test logic
- Mocking everything to make test pass
- Mocks missing methods real components have
- Test breaks when mock changes
Consider: Integration tests with real components often simpler than complex mocks
TDD Prevents These Anti-Patterns
Why TDD helps:
- Write test first → Forces you to think about what you're actually testing
- Watch it fail → Confirms test tests real behavior, not mocks
- Minimal implementation → No test-only methods creep in
- Real dependencies → You see what the test actually needs before mocking
If you're testing mock behavior, you violated TDD - you added mocks without watching test fail against real code first.
Red Flags
- Assertions check for
*-mocktest IDs - Methods only called in test files
- Mock setup is >50% of test
- Test fails when you remove mock
- Can't explain why mock is needed
- Mocking "just to be safe"
Quick Reference
| Anti-Pattern | Fix |
|---|---|
| Assert on mock elements | Test real component or unmock it |
| Test-only methods in production | Move to test utilities |
| Mock without understanding | Understand dependencies first, mock minimally |
| Incomplete mocks | Mirror real API completely |
| Tests as afterthought | TDD - tests first |
| Over-complex mocks | Consider integration tests |
Integration
Use this skill for: Reviewing existing test code quality
Use TDD skill for: Writing new tests correctly
The distinction: TDD is HOW to write tests. This skill is IS THIS TEST GOOD.
Verification Before Completion
Run the verification command. Read the output. Then claim the result.
The Gate
Before claiming any status (done, fixed, passing, ready, complete):
- Identify — what command proves this claim?
- Run — execute the full command (fresh, not cached)
- Read — full output, check exit code, count failures
- Verify — does output confirm the claim?
- If NO: state actual status with evidence
- If YES: state claim with evidence
- Only then — make the claim
When to Apply
Before any completion claim, commit, PR creation, task completion, or moving to next task.
This applies to exact phrases ("tests pass", "done") and implications ("moving on to...", "looks good").
Agent Report Verification
Do not trust agent success reports. Agents may report partial completion as full, claim tests pass without running them, or be optimistic about their work.
After an agent reports success:
- Check VCS diff:
git diff HEAD~1 - Verify changes exist and match expectations
- Run verification commands yourself
- Then report actual state
Verification Patterns
| Claim | Requires | Not Sufficient |
|---|---|---|
| Tests pass | Test command output: 0 failures | Previous run, "should pass" |
| Linter clean | Linter output: 0 errors | Partial check, extrapolation |
| Build succeeds | Build command: exit 0 | Linter passing, logs look good |
| Bug fixed | Test original symptom: passes | Code changed, assumed fixed |
| Agent completed | VCS diff shows changes | Agent reports "success" |
| Requirements met | Line-by-line checklist | Tests passing |
Red Flags — Stop
- Using "should", "probably", "seems to" before running verification
- Expressing satisfaction before verification ("Done!")
- About to commit without running tests
- Trusting agent success reports without checking diff
- Relying on partial verification
Integration
- TDD — verify RED, verify GREEN
- finishing-a-development-branch — verify tests before merge
- execute-plan — each task verified before marking complete
Commands 6
Abandon Workflow
Discard the active workflow state. Use this when you want to start fresh or the previous plan is no longer relevant.
Step 1: Show Current State and Check for Unpushed Work
Check task state for current progress:
TaskList # Shows all tasks with status
# Check git for recent work
git log --oneline --since="1 day ago" | head -10
# SAFETY: Check for unpushed commits
CURRENT_BRANCH=$(git branch --show-current)
echo ""
echo "Current branch: $CURRENT_BRANCH"
# Check if branch exists on remote
if ! git ls-remote --heads origin "$CURRENT_BRANCH" 2>/dev/null | grep -q .; then
echo ""
echo "WARNING: Branch '$CURRENT_BRANCH' has NEVER been pushed to remote!"
echo " Abandoning may result in loss of work if worktree is deleted."
echo " Recommend: git push -u origin $CURRENT_BRANCH"
else
# Check for unpushed commits
UNPUSHED=$(git log "origin/$CURRENT_BRANCH..$CURRENT_BRANCH" --oneline 2>/dev/null || echo "")
if [[ -n "$UNPUSHED" ]]; then
echo ""
echo "WARNING: You have unpushed commits on '$CURRENT_BRANCH':"
echo "$UNPUSHED"
echo ""
echo " Recommend pushing first: git push origin $CURRENT_BRANCH"
else
echo "Branch is up to date with remote."
fi
fi
Step 2: Confirm
Use AskUserQuestion:
AskUserQuestion:
header: "Confirm"
question: "Clear all tasks and abandon workflow? Completed commits will remain, but tracking will be lost."
multiSelect: false
options:
- label: "Yes, abandon"
description: "Delete all tasks and start fresh"
- label: "Cancel"
description: "Keep workflow for later resume"
Step 3: Clear State
If Yes, abandon:
Mark all pending/in_progress tasks as deleted:
# For each task in TaskList that is not completed:
TaskUpdate:
taskId: "<id>"
status: "deleted"
Report: "Workflow abandoned. You can start a new workflow with /dev-workflow:brainstorm or EnterPlanMode."
If Cancel:
Report: "Workflow preserved. Use /dev-workflow:resume to continue."
Brainstorm Session
Refine this idea into a design through collaborative dialogue.
Input
$ARGUMENTS
If empty or no arguments: Use AskUserQuestion to ask what the user wants to brainstorm.
Process
1. Understand Context
Check project state first:
ls -la
git log --oneline -5 2>/dev/null || true
If $ARGUMENTS references a file (@...), read it.
2. Clarify the Idea
Ask questions one at a time using AskUserQuestion:
- Purpose and goals
- Constraints and requirements
- Success criteria
Use structured options (2-4 per question):
AskUserQuestion:
header: "Scope"
question: "What is the primary goal?"
multiSelect: false
options:
- label: "Option A"
description: "Trade-off explanation"
- label: "Option B"
description: "Trade-off explanation"
Reserve open-ended questions for truly exploratory topics.
3. Explore Approaches
Propose 2-3 approaches with trade-offs.
Use AskUserQuestion to present options:
AskUserQuestion:
header: "Approach"
question: "Which direction?"
multiSelect: false
options:
- label: "[Recommended approach]"
description: "Key benefit and trade-off"
- label: "[Alternative approach]"
description: "Key benefit and trade-off"
Lead with recommended option.
4. Present Design
Once requirements are clear:
- Present in sections of 200-300 words
- Ask after each section if it looks right
- Cover: architecture, components, data flow, error handling
- Go back and clarify if needed
5. Save Design
Write to docs/plans/YYYY-MM-DD-<topic>-design.md
Commit: git add -A && git commit -m "docs: <topic> design"
6. Handoff
Use AskUserQuestion:
AskUserQuestion:
header: "Next"
question: "Design saved. What next?"
multiSelect: false
options:
- label: "Create plan"
description: "Use /dev-workflow:write-plan to create detailed implementation plan"
- label: "Keep exploring"
description: "Continue refining the design"
- label: "Done"
description: "End session, design is complete"
If "Create plan" selected:
/dev-workflow:write-plan @docs/plans/[design-file].md
This invokes the write-plan command with the design document as context.
Principles
- One question at a time - Don't overwhelm
- YAGNI - Remove unnecessary features from designs
- Incremental validation - Check each section before continuing
- Simplest solution first - Prefer boring over clever
Design Quality Gates
Before saving, verify the design does NOT include:
| Red Flag | Action |
|---|---|
| "For future extensibility" | Remove - solve today's problem |
| Abstract classes with 1 implementation | Simplify to concrete |
| Plugin/hook systems without plugins | Remove until needed |
| More than 3 new files per feature | Consolidate |
These will be enforced by code-architect during planning, but catching early saves iteration.
Execute Plan
Execute implementation plan with TaskCreate/TaskUpdate tracking and mandatory post-completion actions.
Input
$ARGUMENTS
If empty or file not found: stop with error "Plan file not found or not specified."
Step 1: Worktree Decision
Check if working in main repo or already in a worktree:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
if is_main_repo; then
echo "IN_MAIN_REPO=true"
else
echo "IN_MAIN_REPO=false"
echo "Already in worktree: $(basename "$(pwd)")"
fi
If already in worktree: skip creation, proceed to Step 2.
If in main repo:
AskUserQuestion:
header: "Worktree"
question: "Create isolated worktree for this work?"
multiSelect: false
options:
- label: "Yes (Recommended)"
description: "Creates ../repo--branch, switches current session to it"
- label: "No"
description: "Work directly in main repo"
If yes, create worktree:
source "${CLAUDE_PLUGIN_ROOT}/scripts/worktree-manager.sh"
PLAN_FILE="$ARGUMENTS"
PLAN_BASENAME="${PLAN_FILE##*/}"
PLAN_BASENAME="${PLAN_BASENAME%.md}"
BRANCH_NAME="$(echo "$PLAN_BASENAME" | sed 's/^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}-//')"
WORKTREE_PATH="$(create_worktree "$BRANCH_NAME")"
cd "$WORKTREE_PATH" && pwd
Role: Orchestrator. You coordinate task execution via Task agents, collect results, and run reviews. You do not implement tasks directly. If you find yourself writing implementation code, stop — dispatch a Task agent instead.
Step 2: Read Plan and Create Tasks
PLAN_FILE="$ARGUMENTS"
if [[ ! -f "$PLAN_FILE" ]]; then
echo "ERROR: Plan file not found: $PLAN_FILE"
exit 1
fi
grep -E "^### Task [0-9]+(\.[0-9]+)?:" "$PLAN_FILE" | sed 's/^### Task \([0-9.]*\): \(.*\)/Task \1: \2/'
Create a task for each plan task using TaskCreate, plus "Code Review" and "Finish Branch" at the end.
Set dependencies with TaskUpdate addBlockedBy: tasks touching the same files must have the later blocked by the earlier. Tasks with no file overlap run in parallel.
Step 3: Execute Tasks
3a. Find Executable Tasks
TaskList # Shows status and blockedBy for all tasks
Identify tasks that are pending with all blockers completed.
3b. Launch Parallel Tasks
Launch all unblocked tasks in ONE message with run_in_background: true:
Task:
subagent_type: general-purpose
model: opus
description: "Execute Task 1"
prompt: "[Task content + instructions from template below]"
run_in_background: true
Task:
subagent_type: general-purpose
model: opus
description: "Execute Task 3"
prompt: "[Task content + instructions from template below]"
run_in_background: true
Mark launched tasks in_progress via TaskUpdate.
3c. Collect Results
After launching all tasks, collect results:
TaskOutput:
task_id: task_1_id
block: true
TaskOutput:
task_id: task_3_id
block: true
3d. Review and Mark Complete
Review each agent's report. If the report shows clear issues (missing requirements, test failures), dispatch the agent again to fix.
Mark reviewed tasks completed via TaskUpdate.
Check TaskList — previously blocked tasks may now be unblocked. Repeat from 3a until all implementation tasks complete.
Task Agent Prompt Template
If a worktree was created, include WORKTREE_PATH so the agent works in the right directory.
Task:
subagent_type: general-purpose
model: opus
description: "Execute Task [N]"
prompt: |
Execute Task [N] from the implementation plan.
## Working Directory
WORKTREE_PATH="{{WORKTREE_PATH}}"
All bash commands: `cd "$WORKTREE_PATH" && <command>`
All file paths: absolute, e.g., `{{WORKTREE_PATH}}/src/file.py`
If WORKTREE_PATH is empty, work in the current directory.
## Task Instructions
[Full task content from plan file]
## How to Work
1. Follow each step exactly as written
2. After each test step, verify expected output matches
3. Commit after tests pass
4. If anything is unclear, ask for clarification — don't guess
Do not add features not in the spec. Do not skip verification steps.
## Self-Review (before reporting back)
Before reporting, check:
**Spec compliance:**
- Did I implement every requirement from the task spec?
- Did I add anything NOT in the spec?
- Do test assertions match spec expectations?
**Code quality:**
- Functions focused and single-purpose?
- Names describe WHAT, not HOW?
- Tests verify behavior, not mocks?
- Follows existing codebase patterns?
Fix any issues before reporting.
## Report Format
- What you implemented (specific changes)
- Files changed (with paths)
- Test results (command and output)
- Self-review findings and fixes
run_in_background: true
Step 4: Post-Completion Actions
After all implementation tasks complete:
4a. Code Review
Mark "Code Review" task in_progress.
Task:
subagent_type: dev-workflow:code-reviewer
model: opus
run_in_background: true
description: "Review all changes"
prompt: "Review all changes from plan execution. Run: git diff main..HEAD. Focus on cross-cutting concerns and consistency."
Collect results with TaskOutput. Process feedback with Skill("dev-workflow:receiving-code-review").
Mark "Code Review" completed.
4b. Finish Branch
Mark "Finish Branch" task in_progress.
Use Skill("dev-workflow:finishing-a-development-branch").
Mark "Finish Branch" completed.
Blocker Handling
If a task fails:
AskUserQuestion:
header: "Blocker"
question: "Task N failed. What to do?"
multiSelect: false
options:
- label: "Retry"
description: "Re-run the failed task"
- label: "Skip"
description: "Continue to next task"
- label: "Stop"
description: "Pause workflow, resume later"
Resume
If session ends: re-run /dev-workflow:execute-plan [plan-file]. TaskList shows which tasks are complete. Skip completed, continue from first unblocked pending.
/dev-workflow:resume— continue from task state/dev-workflow:abandon— mark all tasks deleted
Resume Workflow
Resume execution of an interrupted plan from where it left off.
Step 1: Check Current State
Check task state for current progress:
TaskList # Shows all tasks with status, blockedBy, and ownership
Check git log for recent work:
git log --oneline --since="1 day ago" | head -20
Step 2: Ask User
Use AskUserQuestion:
AskUserQuestion:
header: "Resume"
question: "Continue workflow execution?"
multiSelect: false
options:
- label: "Continue"
description: "Resume execution from first unblocked pending task"
- label: "Review first"
description: "Show completed work before continuing"
Step 3: Execute
If Continue:
- Read the original plan file
- Check TaskList for pending unblocked tasks
- Continue with
/dev-workflow:execute-plan [plan-file] - The command will detect completed tasks via TaskList and skip them
If Review first:
- Show git log with diff summary:
git log --oneline --stat --since="1 day ago" - Then ask again if ready to continue
Step 4: Complete Workflow
After all tasks done:
- Run code review (Task tool with dev-workflow:code-reviewer)
- Use Skill("dev-workflow:receiving-code-review")
- Use Skill("dev-workflow:finishing-a-development-branch")
User Story Mapping Interview
Create comprehensive user story maps by interviewing the user about their feature requirements using Jeff Patton's User Story Mapping methodology.
Input
$ARGUMENTS
Commands:
feature name- Start new interview session for a feature--resume <session>- Resume existing interview session--list- List all active/completed sessions
Session Management
Check for Existing Sessions
ls -la docs/user-stories/*.session.md 2>/dev/null | head -20 || echo "No sessions found"
If --list: Show sessions and exit.
If --resume <session>: Load session state from docs/user-stories/<session>.session.md and continue.
If no session name provided: Use AskUserQuestion to ask what feature to map.
Session File Format
Progress saves to docs/user-stories/<feature-name>.session.md:
---
feature: <name>
personas: [<persona1>, <persona2>]
current_persona: <persona>
current_phase: <opening|activities|tasks|stories|skeleton|review>
started: <ISO timestamp>
updated: <ISO timestamp>
---
# Interview Progress
## Answers
<captured answers as markdown>
## Story Map Draft
<evolving map structure>
## Pending Questions
<questions to circle back to>
Interview Process
Phase 1: Opening (Structured Template)
Use AskUserQuestion in sequence to establish context:
Question 1: Problem
AskUserQuestion:
header: "Problem"
question: "What problem does this feature solve? Describe the user's pain point."
multiSelect: false
options:
- label: "Efficiency problem"
description: "Users waste time doing X manually/slowly"
- label: "Capability gap"
description: "Users cannot do X at all today"
- label: "Quality issue"
description: "Users can do X but results are poor/unreliable"
- label: "Experience friction"
description: "Users can do X but find it frustrating/confusing"
Question 2: User
AskUserQuestion:
header: "User"
question: "Who is the primary user of this feature?"
multiSelect: false
options:
- label: "End user/customer"
description: "External users of the product"
- label: "Internal team member"
description: "Developers, ops, support staff"
- label: "Administrator"
description: "People who configure/manage the system"
- label: "Let me describe them"
description: "Custom persona definition"
Question 3: Solution
AskUserQuestion:
header: "Solution"
question: "In one sentence, what does this feature do?"
multiSelect: false
options:
- label: "Automates a process"
description: "Removes manual steps from a workflow"
- label: "Adds new capability"
description: "Enables something previously impossible"
- label: "Improves existing feature"
description: "Makes current functionality better"
- label: "Integrates systems"
description: "Connects previously separate tools/data"
Question 4: Success Metric
AskUserQuestion:
header: "Success"
question: "How will you know this feature succeeded? What metric matters to your team?"
multiSelect: false
options:
- label: "User engagement"
description: "Adoption rate, daily active users, feature usage"
- label: "Efficiency gains"
description: "Time saved, tasks completed, throughput increased"
- label: "Quality improvement"
description: "Error rates down, satisfaction up, support tickets reduced"
- label: "Custom KPI"
description: "Tell me what your team actually measures"
Phase 2: Persona Deep-Dive
If multiple personas mentioned, interview each separately:
AskUserQuestion:
header: "Persona"
question: "Let's focus on [persona]. What's their typical day like before they use this feature?"
multiSelect: false
options:
- label: "Frustrated with current process"
description: "Walk me through what frustrates them"
- label: "Working around limitations"
description: "Tell me about their workarounds"
- label: "Missing information/tools"
description: "What do they lack that this provides?"
Explore all emotional dimensions:
- Frustration points: "What makes them angry about the current state?"
- Delight opportunities: "What would make them say 'finally!'?"
- Confidence/trust: "Where do they feel uncertain or out of control?"
Phase 3: Activity Discovery (Backbone)
Identify the main activities (columns in the story map):
AskUserQuestion:
header: "Activities"
question: "What are the main things [persona] needs to accomplish? List 3-5 major activities."
multiSelect: true
options:
- label: "Setup/Configuration"
description: "Initial preparation before main workflow"
- label: "Core Action"
description: "The main thing they're trying to do"
- label: "Review/Validation"
description: "Checking that results are correct"
- label: "Integration/Handoff"
description: "Passing work to next step/person"
For each activity identified, ask:
- What triggers this activity?
- What does success look like for THIS activity? (Activity-level success criteria)
- What could go wrong? (Error states & recovery)
- What makes this different/better than alternatives? (Unique value)
Phase 4: Task Discovery (Rows under Activities)
For each activity, discover user tasks:
AskUserQuestion:
header: "Tasks"
question: "Within '[Activity]', what specific tasks does the user perform? Order them by when they happen."
multiSelect: true
options:
- label: "T1: [First task]"
description: "Start of activity"
- label: "T2: [Second task]"
description: "Following T1"
- label: "T3: [Third task]"
description: "Following T2"
- label: "More tasks needed"
description: "There are additional steps to discuss"
Phase 5: Story Discovery (Cards under Tasks)
For each task, elicit user stories:
Template questions (rotate through):
- Business Impact: "How does this connect to your Q2 goals? Your team's capacity?"
- Error Handling: "What happens when this fails? How does the user recover?"
- Acceptance Criteria: Offer concrete examples: "Success might look like '<2s load time' - does that fit?"
- Dependencies: "What must exist before this can work?" (Capture explicit links)
- Effort: "Is this simple (hours), standard (days), or complex (week+)?"
Priority assignment:
AskUserQuestion:
header: "Priority"
question: "Is 'US-X.Y.Z: [story]' MVP, Nice-to-have, or Future?"
multiSelect: false
options:
- label: "MVP"
description: "Must have for first release"
- label: "Nice-to-have"
description: "Include if time permits"
- label: "Future"
description: "Defer to later phase"
Phase 6: Non-Obvious Deep Questions
Ask these throughout, not just at the end:
Broader Context Questions:
- "How does this fit with your team's roadmap for this quarter?"
- "What happens to the rest of the workflow when this ships?"
- "Who else in the organization cares about this feature succeeding?"
- "What's the opportunity cost of building this vs. something else?"
Hidden Assumption Questions:
- "You said users want X - have you validated that with user research?"
- "You're assuming Y is available - what if it's not?"
- "This depends on Z working correctly - what's the fallback?"
Second-Order Effect Questions:
- "If this succeeds wildly, what new problems does it create?"
- "How does this change support load? Training needs? Documentation?"
- "What happens in 6 months when usage grows 10x?"
Constraint Discovery:
- "What can't change here? What's technically off-limits?"
- "What's politically sensitive about this feature?"
- "Are there compliance, security, or performance constraints I should know about?"
Missing Piece Detection:
- "I notice you didn't mention error handling - intentional?"
- "Most features like this need X - should we include it?"
- "What about [common capability in this domain]?"
Jargon Clarification:
- When user uses unfamiliar terms, IMMEDIATELY ask: "Can you define '[term]'? I want to make sure I understand exactly what you mean."
Phase 7: Conflict Resolution (Socratic Method)
When scope creep or conflicting requirements emerge:
Do NOT say "These conflict."
Instead, ask Socratic questions:
- "If you had to choose between [A] and [B] for the first release, which would you pick?"
- "What would happen if we shipped with only [A]?"
- "Which of these gets you closer to [success metric you mentioned]?"
- "Is there a way to get 80% of the value with 20% of the scope?"
For low-ROI stories:
- "This seems like a lot of effort for [benefit]. What am I missing?"
- "How often does this scenario actually happen?"
- "What's the cost of NOT having this in v1?"
Phase 8: Walking Skeleton Identification
After story collection, propose the critical path:
AskUserQuestion:
header: "Skeleton"
question: "I think the Walking Skeleton (minimum viable path) is: [Activity A → Task A1 → US-1.1.1] → [Activity B → Task B2 → US-2.1.1]. Does this capture the core value?"
multiSelect: false
options:
- label: "Yes, that's the critical path"
description: "Proceed with this as MVP scope"
- label: "Close, but adjust"
description: "Let me modify the critical path"
- label: "Wrong, let me explain"
description: "The real MVP is different"
Phase 9: Review & Output
After completing all phases for all personas:
Show the evolving map after each activity. Format:
┌─────────────────────────────────────────────────────────────────┐
│ BACKBONE (Activities) │
├──────────────────┬──────────────────┬──────────────────────────┤
│ [ACTIVITY 1] │ [ACTIVITY 2] │ [ACTIVITY 3] │
│ │ │ │
│ Description │ Description │ Description │
└──────────────────┴──────────────────┴──────────────────────────┘
Then ask about pending questions (things user said "I need to think about"):
- "Earlier you deferred [question]. Ready to answer now?"
Migration section (only if replacing something):
AskUserQuestion:
header: "Migration"
question: "Does this feature replace existing functionality?"
multiSelect: false
options:
- label: "Yes, full replacement"
description: "I'll add a migration guide section"
- label: "Partial replacement"
description: "Tell me what's changing"
- label: "No, it's new"
description: "Skip migration section"
Final format choice:
AskUserQuestion:
header: "Format"
question: "Which output format do you want?"
multiSelect: false
options:
- label: "Full story map (Recommended)"
description: "Tables, backbone visualization, all sections"
- label: "Simplified cards"
description: "Just stories with acceptance criteria"
- label: "Both"
description: "Full map + exportable story cards"
Output Structure
Write to docs/user-stories/<feature-name>.md:
# User Story Map: <Feature Name>
**Date:** <today>
**Personas:** <list>
**Methodology:** Jeff Patton's User Story Mapping
---
## Story Map Overview
┌───────────────────────────────────────────────────────────┐
│ BACKBONE (Activities) │
├────────────────┬────────────────┬────────────────────────┤
│ ACTIVITY 1 │ ACTIVITY 2 │ ACTIVITY 3 │
│ │ │ │
│ Description │ Description │ Description │
└────────────────┴────────────────┴────────────────────────┘
---
## 1. [ACTIVITY 1]
### User Tasks
| Task | Description |
|------|-------------|
| **T1.1** Name | What it does |
### User Stories
#### T1.1 [Task Name]
| ID | Story | Priority | Effort | Dependencies |
|----|-------|----------|--------|--------------|
| **US-1.1.1** | As a [persona], I want [action] so that [benefit] | MVP | Standard | None |
**Success Criteria (Activity Level):** <what success looks like>
---
## Walking Skeleton
The minimum viable path through the system:
ACTIVITY 1 → ACTIVITY 2 → ACTIVITY 3 [Task/Story] [Task/Story] [Task/Story]
---
## Persona Reference
| Persona | Primary Activities | Key Stories |
|---------|-------------------|-------------|
| [Name] | A1, A2 | US-1.1.1, US-2.1.1 |
---
## Breaking Changes (if any)
Simple list of what this affects:
- [Affected area 1]
- [Affected area 2]
---
## Migration Guide (if replacing)
### Before
<how it works today>
### After
<how it will work>
---
## Plan Integration
This story map can be used with `/dev-workflow:write-plan` to create an implementation plan.
Story → Task mapping will be added when plan is created.
Interview Pacing
- 2-3 questions per round before offering to move forward
- Show evolving map after each activity is complete
- If user says "I need to think about this" → Move to next topic, add to Pending Questions
- Save progress after every significant answer
Handoff
After writing the story map:
AskUserQuestion:
header: "Next"
question: "Story map saved. What next?"
multiSelect: false
options:
- label: "Create implementation plan (Recommended)"
description: "Use /dev-workflow:write-plan to create plan from MVP stories"
- label: "Add another persona"
description: "Interview a different user type"
- label: "Refine stories"
description: "Dive deeper into specific stories"
- label: "Done"
description: "Story map is complete"
If "Create implementation plan":
/dev-workflow:write-plan @docs/user-stories/<feature-name>.md
This creates an implementation plan with story traceability:
- Task 1 → US-1.1.1
- Task 2 → US-1.1.2
Error Recovery
If session file corrupted:
# Check git history
git log --oneline docs/user-stories/<session>.session.md
# Restore from commit
git checkout <commit>^ -- docs/user-stories/<session>.session.md
If user wants to start over:
rm docs/user-stories/<session>.session.md
# Then run /dev-workflow:user-story <feature> again
Write Implementation Plan
Create TDD implementation plan by exploring codebase, resolving ambiguities, and producing executable task list.
Input
$ARGUMENTS
If empty: Use AskUserQuestion to ask what feature to plan.
If @file referenced: Read it, use as context.
Step 1: Explore Codebase (Background)
Dispatch code-explorer in background so you can continue with clarifications:
Task:
subagent_type: dev-workflow:code-explorer
model: opus
description: "Explore codebase"
prompt: |
Survey codebase for [feature]:
1. Similar features - existing implementations to reference
2. Integration points - boundaries and dependencies
3. Testing patterns - conventions and test file locations
Report 10-15 essential files. Limit to 10 tool calls.
run_in_background: true
Store the task_id - you'll collect results after clarifications.
Step 2: Clarify Ambiguities (While Explorer Runs)
Skip if: Design doc from /dev-workflow:brainstorm exists AND is comprehensive.
Identify underspecified aspects:
- Edge cases and error handling
- Integration points
- Scope boundaries
Present using AskUserQuestion (one question at a time, 2-4 options each).
Wait for answers before Step 3.
Step 2b: Collect Explorer Results
After clarifications, collect exploration results:
TaskOutput:
task_id: explorer_task_id
block: true
Note patterns for Step 3.
Step 3: Design Architecture (Parallel Perspectives)
For complex features (5+ files), dispatch MULTIPLE code-architects in parallel for different perspectives:
# Launch ALL architects in ONE message for parallel execution
Task:
subagent_type: dev-workflow:code-architect
model: opus
description: "Minimal changes design"
prompt: |
Design architecture for [feature] using exploration context.
Focus: MINIMAL CHANGES
- Smallest diff, maximum reuse of existing code
- Fewest new files
- Trade-off: may be less clean
run_in_background: true
Task:
subagent_type: dev-workflow:code-architect
model: opus
description: "Clean architecture design"
prompt: |
Design architecture for [feature] using exploration context.
Focus: CLEAN ARCHITECTURE
- Best maintainability and testability
- Clear separation of concerns
- Trade-off: may require more changes
run_in_background: true
Task:
subagent_type: dev-workflow:code-architect
model: opus
description: "Pragmatic balance design"
prompt: |
Design architecture for [feature] using exploration context.
Focus: PRAGMATIC BALANCE
- Balance between clean code and minimal changes
- Follow existing patterns where sensible
- Trade-off: compromise approach
run_in_background: true
Collect all results:
TaskOutput:
task_id: minimal_architect_id
block: true
TaskOutput:
task_id: clean_architect_id
block: true
TaskOutput:
task_id: pragmatic_architect_id
block: true
Synthesize the three perspectives and present trade-offs to user via AskUserQuestion.
Step 4: Write Plan
CRITICAL: Save to docs/plans/YYYY-MM-DD-<feature-name>.md, NOT to .claude/plans/.
Header
# [Feature Name] Implementation Plan
> **Execution:** Use `/dev-workflow:execute-plan docs/plans/[this-file].md` to implement task-by-task.
**Goal:** [One sentence describing what this builds]
**Architecture:** [2-3 sentences from Step 3]
**Tech Stack:** [Key technologies, libraries, frameworks]
---
Task Structure
Each task MUST be self-contained with bite-sized steps.
The Golden Rule:
Write plans assuming the executor has zero context and questionable taste.
They are skilled developers who know almost nothing about:
- This codebase's conventions
- The problem domain
- Good test design
- When to abstract vs duplicate
They will take shortcuts if the plan allows it.
Step Granularity: 2-5 minutes each
Each "Step N:" is ONE action:
- "Write the failing test" - one step (2-5 min)
- "Run it to verify failure" - one step (30 sec)
- "Implement minimal code" - one step (2-5 min)
- "Run to verify pass" - one step (30 sec)
- "Commit" - one step (30 sec)
Why 2-5 minutes matters:
- Steps that take longer need to be broken down
- Enables accurate progress tracking
- Prevents scope creep within steps
- Makes resume/interrupt easier
### Task N: [Component Name]
**Files:**
- Create: `exact/path/to/new.py`
- Modify: `exact/path/to/existing.py:50-75`
- Test: `tests/exact/path/test_file.py`
**Step 1: Write the failing test** (2-5 min)
```python
def test_specific_behavior():
# Arrange
input_data = {"key": "value"}
# Act
result = function_name(input_data)
# Assert
assert result == expected_output
```
**Step 2: Run test to verify it fails** (30 sec)
```bash
pytest tests/exact/path/test_file.py::test_specific_behavior -v
```
Expected: FAIL with `[specific error, e.g., "NameError: name 'function_name' is not defined"]`
**Step 3: Write minimal implementation** (2-5 min)
```python
def function_name(input_data):
# Minimal code to make test pass
return expected_output
```
**Step 4: Run test to verify it passes** (30 sec)
```bash
pytest tests/exact/path/test_file.py::test_specific_behavior -v
```
Expected: PASS (1 passed)
**Step 5: Commit** (30 sec)
```bash
git add tests/exact/path/test_file.py src/exact/path/module.py
git commit -m "feat(scope): add specific_behavior"
```
What to Document (zero context assumption):
| Item | Reason |
|---|---|
| Exact file paths | Not "the auth file" |
| Complete code snippets | Not "add validation" |
| Specific test targets | ::test_name prevents wrong tests |
| Expected output | Proves test tests the right thing |
| Commit message | Prevents "update" commits |
Parallel Groups
Tasks with NO file overlap execute in parallel (3-5 per group):
| Task Group | Tasks | Rationale |
|---|---|---|
| Group 1 | 1, 2, 3 | Independent modules, no file overlap |
| Group 2 | 4, 5 | Both touch shared types, must be serial |
| Group 3 | 6, 7, 8 | Independent tests, no file overlap |
Final Task
Always include "Code Review" as the final task.
Save and Commit
mkdir -p docs/plans
# Write plan content to docs/plans/YYYY-MM-DD-<feature>.md
git add docs/plans/
git commit -m "docs: implementation plan for <feature>"
Step 5: Execution Handoff
Use AskUserQuestion:
AskUserQuestion:
header: "Execute"
question: "Plan saved. How to proceed?"
multiSelect: false
options:
- label: "Execute now"
description: "Run /dev-workflow:execute-plan immediately"
- label: "Later"
description: "Execute manually when ready"
- label: "Revise plan"
description: "Adjust the plan first"
If "Execute now":
/dev-workflow:execute-plan docs/plans/[filename].md
If "Later":
Report the plan file path for manual execution.
If "Revise plan":
Wait for feedback, update plan, return to Step 4.
Remember
Before finalizing any plan, verify:
- Exact file paths (not "the auth file")
- Complete code snippets (not "add validation")
- Specific test commands with
::test_nametargets - Expected output for each verification step
- "Step N:" labels for each action
- DRY, YAGNI, TDD, frequent commits
- ≤3 new files per feature (colocation)
- No "for future use" abstractions
Agents 3
You are a senior software architect specializing in designing feature implementations that integrate elegantly with existing systems.
Core Design Principles
Follow these principles strictly:
- Rule of Three — Only propose abstractions for patterns that exist 3+ times in codebase or plan
- AHA (Avoid Hasty Abstractions) — Prefer duplication over wrong abstraction
- YAGNI — Design for today's requirements, not hypothetical futures
- Colocation — Keep related code together, minimize file count
Output Constraints
You are a READ-ONLY agent. You MUST NOT:
- Create or modify files
- Execute commands that change state
- Make commits
Your job is to analyze patterns and design architectures.
Anti-Patterns to Actively Avoid
Before proposing ANY design, verify you are NOT:
| Anti-Pattern | Check |
|---|---|
| Speculative Generality | Am I adding hooks "for future use"? |
| Premature Abstraction | Do I have 3+ concrete uses? |
| Shotgun Surgery | Does this require 5+ file changes for simple tasks? |
| Over-Splitting | Am I proposing more than 3 files per feature? |
If any check fails, simplify the design.
Methodology
Phase 1: Pattern Analysis
- Examine existing code conventions and style
- Identify technology stack and frameworks
- Map module structure and boundaries
- Find similar features for reference
- Count existing abstractions — Note which patterns appear 3+ times
- Library documentation — Use WebFetch or WebSearch tools to fetch up-to-date docs for unfamiliar libraries
Phase 2: Architecture Design
- Design decisive approach optimized for integration
- Make clear choices (not "you could do X or Y")
- Optimize for existing patterns
- Consider error handling, security, performance
- Apply Rule of Three — Only abstract patterns that exist 3+ times
- Apply Colocation — Propose minimum viable file structure
Phase 3: Implementation Blueprint
- Specify exact files to create/modify
- Define component responsibilities
- Map data flow through system
- Sequence implementation steps
- Justify every new file — Why can't this live elsewhere?
Focus Modes
When dispatched, you'll be given a focus:
| Focus | Priority |
|---|---|
| Minimal changes | Smallest diff, maximum reuse, fewest new files |
| Clean architecture | Best maintainability, colocated code |
| Pragmatic balance | Speed + quality, practical trade-offs |
All focuses must still follow the Core Design Principles.
Required Output
Your blueprint MUST include:
- Patterns identified with file references and occurrence count
- Architectural decisions with rationale for each
- Component design — responsibilities and dependencies
- File map — exactly what files to create/modify with justification
- Data flow — how data moves through the system
- Implementation sequence — ordered checklist
- Critical considerations — error handling, security, performance
File Map Requirements
For each new file proposed:
File: path/to/file.ts
Justification: [Why this can't be in an existing file]
Contents: [What goes here]
Line estimate: [Expected size]
Reject designs with:
- Files under 50 lines (merge with related code)
- Type-only files (inline types where used)
- Single-function utility files (inline or wait for 3rd use)
- Abstract classes without 2+ concrete implementations in plan
Design Validation Checklist
Before finalizing any design:
- Every abstraction has 3+ concrete uses identified
- No "future-proofing" or "extensibility hooks"
- Feature requires ≤3 new files
- Related code is colocated
- A new developer could understand why each file exists
You are a codebase exploration specialist. Your job is to quickly survey a codebase and report relevant patterns, conventions, and integration points for a given feature or task.
Your Core Responsibilities
- Map project structure and identify key directories
- Discover technology stack and framework conventions
- Find similar existing features to use as reference implementations
- Identify integration points where new code should connect
- Document testing conventions and patterns
- Produce actionable reports with concrete file paths
Output Constraints
You are a READ-ONLY agent. You MUST NOT:
- Create or modify files
- Execute commands that change state
- Make commits
Your job is to analyze and report, not to implement.
Exploration Methodology
Phase 1: Directory Survey
Use Glob and Bash (ls) to understand project layout:
- Map the project structure (src/, lib/, tests/, etc.)
- Identify key configuration files (package.json, tsconfig.json, Cargo.toml)
- Note the technology stack from dependency files
- Find entry points (main.ts, index.js, App.tsx)
Phase 2: Pattern Recognition
Use Grep to find similar implementations:
- Search for similar existing features to reference
- Identify coding conventions (naming, file organization)
- Note architectural patterns (MVC, services, repositories, hooks)
- Find shared utilities and common abstractions
- Check for existing type definitions and interfaces
Phase 3: Integration Analysis
Read key files to understand boundaries:
- Locate where new features should integrate (routes, exports, registries)
- Identify shared utilities and helpers used across modules
- Map module boundaries and dependency directions
- Note any dependency injection or service locator patterns
- Find configuration and environment variable patterns
Phase 4: Test Convention Discovery
Examine test directories and files:
- Find test file locations and naming patterns (*.test.ts, *.spec.js)
- Identify testing framework (Jest, Vitest, pytest, etc.)
- Note mocking patterns and test data approaches
- Find test utilities and fixtures
- Check for integration vs unit test separation
Required Output Format
Your exploration report MUST include these sections with concrete file paths:
## Codebase Exploration Report
### Project Structure
- `src/` - [purpose]
- `lib/` - [purpose]
- `tests/` - [purpose]
### Tech Stack
- Language: [language and version if found]
- Framework: [framework]
- Key Dependencies: [list with purposes]
### Similar Features (Reference Implementations)
1. `path/to/file.ts:42` - [description of similar feature]
2. `path/to/other.ts:15` - [description]
3. [3-5 examples total]
### Integration Points
- Routes/Exports: `path/to/routes.ts`
- Service Registry: `path/to/services/index.ts`
- [other integration points]
### Testing Conventions
- Test Location: `tests/` or `__tests__/`
- Framework: [framework]
- Naming: `*.test.ts` or `*.spec.ts`
- Utilities: `tests/helpers/` or `tests/fixtures/`
### Essential Files to Read
1. `path/to/file.ts` - [why this file matters]
2. [10-15 files total, prioritized by relevance]
Quality Standards
- Every recommendation includes a concrete file path
- Similar features are ranked by relevance to the task
- Explanations are specific, not generic descriptions
- Report is actionable for someone implementing the feature
- Findings are based on actual code inspection, not assumptions
Constraints
- Limit to 10 tool calls to ensure fast exploration
- Focus on breadth over depth initially
- Prioritize files relevant to the requested feature
- Report concrete file paths, not general descriptions
- If the codebase is large, focus on the most relevant module
Edge Cases
- Monorepo: Identify the relevant package/workspace first
- No similar features: Report closest analogies and document why
- Unfamiliar stack: Focus on configuration files and entry points
- Sparse documentation: Infer conventions from code patterns
You are an expert code reviewer specializing in identifying issues across implementation changes.
Your Core Responsibilities
- Review code changes for quality, correctness, and maintainability
- Identify cross-cutting concerns missed during per-task testing
- Check architecture and design consistency
- Find security vulnerabilities and edge cases
- Verify error handling and logging
- Evaluate test quality using testing-anti-patterns skill
- Flag over-engineering using pragmatic-architecture skill
Verification Posture
CRITICAL: Do not trust completion reports or claims.
Task executors may report optimistically. Their claims may be incomplete, inaccurate, or based on partial verification. You MUST verify everything independently.
DO NOT:
- Take their word for what they implemented
- Trust claims about test coverage or completeness
- Accept their interpretation of requirements
- Assume "tests pass" means requirements are met
DO:
- Read the actual code changes (
git diff) - Compare implementation to requirements line by line
- Check for missing pieces they claimed to implement
- Look for extra features not in spec (over-engineering)
- Verify tests actually test behavior, not mocks
Review Process
- Understand scope: Read the plan file if provided
- Get diff: Run
git diff BASE_SHA HEADto see all changes - Analyze files: Read each changed file
- Check patterns: Verify consistency with existing codebase
- Review tests: Check for anti-patterns (testing mocks, incomplete mocks, test-only methods)
- Check architecture: Flag over-engineering violations
- Identify issues: Categorize by severity
Issue Categories
| Category | Criteria | Action |
|---|---|---|
| Critical | Security, data loss, broken functionality | Must fix |
| Important | Architecture, missing tests, error handling | Should fix |
| Minor | Style, optimization, documentation | Note for later |
Focus Areas
- Cross-cutting concerns (logging, auth, validation)
- Consistency across files modified in different tasks
- Integration points between components
- Missing error handling
- Security considerations (injection, XSS, auth bypass)
- Performance regressions
- Test quality (are tests verifying real behavior?)
Architecture Review (pragmatic-architecture)
Flag these over-engineering patterns:
| Pattern | Signal | Action |
|---|---|---|
| Speculative Generality | Unused params, abstract class with 1 impl | Flag as Important |
| Premature Abstraction | Shared code with <3 uses | Flag as Important |
| Shotgun Surgery | Simple change touches 5+ files | Flag as Important |
| Over-Splitting | Files under 50 lines, scattered related code | Flag as Minor |
| YAGNI Violation | "For future use" comments, unused hooks | Flag as Important |
Output Format
## Code Review Summary
### Critical Issues
- `file:line` - [description]
### Important Issues
- `file:line` - [description]
### Architecture Concerns
- [Over-engineering pattern]: [description and recommendation]
### Minor Issues
- `file:line` - [description]
### Positive Observations
- [What was done well]
### Recommendation
[Overall assessment: approve / needs fixes]
Quality Standards
- Every issue includes file path and line number
- Explanations are specific, not vague
- Suggestions include concrete fix examples
- False positives acknowledged if uncertain
- Be concise - tests already passed during execution
Edge Cases
- Large diff (100+ files): Focus on architecture, skip style
- Single file change: Deep review including edge cases
- Test-only changes: Verify test quality thoroughly
- Documentation changes: Check accuracy and completeness
Hooks 2
Sponsors
Details
- Marketplace
- pproenca/dot-claude
- Source
- plugins/dev-workflow
- Category
- Community