Add new methodology skills for enhanced development workflows

This commit is contained in:
duthaho
2025-11-29 18:27:51 +07:00
parent ef96f165ef
commit 353e55e2fe
24 changed files with 3979 additions and 4 deletions
+59
View File
@@ -14,6 +14,10 @@ This is a comprehensive Claude Kit for Claude Code, designed to accelerate devel
| `/test [scope]` | Generate tests |
| `/ship [msg]` | Commit + PR automation |
| `/plan [task]` | Task decomposition |
| `/plan --detailed [task]` | Detailed plan with 2-5 min tasks |
| `/brainstorm [topic]` | Interactive design session |
| `/execute-plan [file]` | Subagent-driven plan execution |
| `/tdd [feature]` | Test-driven development workflow |
| `/doc [target]` | Documentation generation |
| `/deploy [env]` | Deployment workflow |
@@ -144,6 +148,61 @@ Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
- Reproduce before fixing
- Add regression tests
## Methodology Settings
<!-- CUSTOMIZATION POINT: Configure superpowers methodology -->
Settings to control the integrated superpowers development methodology.
### Planning Granularity
| Mode | Task Size | Use Case |
|------|-----------|----------|
| `standard` | 15-60 min | Quick planning, experienced team |
| `detailed` | 2-5 min | Thorough plans with exact code |
To use detailed mode: `/plan --detailed [task]`
### Brainstorming Style
| Style | Description |
|-------|-------------|
| `standard` | All questions at once |
| `interactive` | One question per message with validation |
To use interactive mode: `/brainstorm [topic]`
### Execution Mode
| Mode | Description |
|------|-------------|
| `manual` | Developer executes tasks from plan |
| `subagent` | Automated execution with code review gates |
To use subagent mode: `/execute-plan [plan-file]`
### TDD Strictness
For strict TDD enforcement (no production code without failing test):
- Use `/tdd [feature]` command
- Reference: `.claude/skills/methodology/test-driven-development/SKILL.md`
### Verification Requirements
Enable mandatory verification before completion claims:
- Reference: `.claude/skills/methodology/verification-before-completion/SKILL.md`
### Available Methodology Skills
| Category | Skills |
|----------|--------|
| Planning | brainstorming, writing-plans, executing-plans |
| Testing | test-driven-development, verification-before-completion, testing-anti-patterns |
| Debugging | systematic-debugging, root-cause-tracing, defense-in-depth |
| Collaboration | dispatching-parallel-agents, requesting-code-review, receiving-code-review, finishing-development-branch |
Skills location: `.claude/skills/methodology/`
## Environment Configuration
<!-- CUSTOMIZATION POINT: Update for your environments -->
+18
View File
@@ -273,6 +273,24 @@ Starting from fundamentals, what's the best way to solve this?
- [ ] Feasibility considered
- [ ] Clear recommendation given
## Methodology Skills
For enhanced interactive brainstorming, use the superpowers methodology:
**Reference**: `.claude/skills/methodology/brainstorming/SKILL.md`
Key principles from superpowers methodology:
- **One question per message**: Ask single questions, wait for response
- **Multiple-choice preference**: Provide structured options when possible
- **YAGNI ruthlessly**: Remove unnecessary features aggressively
- **Incremental validation**: Present design in 200-300 word chunks
- **Design documentation**: Output to timestamped markdown files
To use interactive mode, invoke with:
```
Use the brainstorming methodology skill for one-question-at-a-time design refinement.
```
<!-- CUSTOMIZATION POINT -->
## Project-Specific Overrides
+33
View File
@@ -177,6 +177,39 @@ I am a senior code reviewer providing thorough, constructive feedback on code qu
- [ ] No new linting errors
- [ ] Documentation updated if needed
## Methodology Skills
For enhanced code review workflows, use the superpowers methodology:
### Requesting Reviews
**Reference**: `.claude/skills/methodology/requesting-code-review/SKILL.md`
Include in review requests:
- Scope definition (files, lines changed)
- Context (why changes were made)
- Areas of concern (where to focus)
- Test coverage summary
### Receiving Reviews
**Reference**: `.claude/skills/methodology/receiving-code-review/SKILL.md`
Process feedback by category:
- **Critical**: Must fix before proceeding
- **Important**: Should fix before proceeding
- **Minor**: Can fix later
### Review Between Tasks
When using subagent-driven development:
**Reference**: `.claude/skills/methodology/executing-plans/SKILL.md`
- Review after each task completion
- Fresh agent for unbiased review
- Quality gates prevent proceeding with issues
<!-- CUSTOMIZATION POINT -->
## Project-Specific Overrides
+26
View File
@@ -232,6 +232,32 @@ This agent works with:
- **tester**: To generate regression tests
- **code-reviewer**: To validate the fix
## Methodology Skills
For enhanced systematic debugging, use the superpowers methodology:
**Reference**: `.claude/skills/methodology/systematic-debugging/SKILL.md`
### Four-Phase Methodology
1. **Root Cause Investigation**: Reproduce, trace, gather evidence
2. **Pattern Analysis**: Find working code, identify differences
3. **Hypothesis Testing**: One variable at a time, written hypothesis
4. **Implementation**: Failing test first, single targeted fix
### Key Principle
**"NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST"**
### Three-Fix Rule
If 3+ consecutive fixes fail, STOP - this is an architectural problem.
### Additional Skills
- **Root cause tracing**: `.claude/skills/methodology/root-cause-tracing/SKILL.md`
- **Defense in depth**: `.claude/skills/methodology/defense-in-depth/SKILL.md`
<!-- CUSTOMIZATION POINT -->
## Project-Specific Overrides
+24 -1
View File
@@ -140,10 +140,33 @@ Implement JWT-based authentication with login, logout, and token refresh capabil
- Password complexity: Define requirements before implementation
```
## Methodology Skills
For enhanced detailed planning, use the superpowers methodology:
**Reference**: `.claude/skills/methodology/writing-plans/SKILL.md`
### Detailed Mode (2-5 min tasks)
When `--detailed` flag is used, create superpowers-style plans:
- **Bite-sized tasks**: 2-5 minutes each (vs standard 15-60 min)
- **Exact file paths**: Always specify full paths
- **Complete code samples**: Include actual code, not descriptions
- **TDD steps**: Write test → verify fail → implement → verify pass → commit
- **Expected outputs**: Specify command results
### Execution Options
After creating a detailed plan:
- **Subagent-driven**: Use `executing-plans` skill for automated execution
- **Manual**: Developer follows plan sequentially
**Reference**: `.claude/skills/methodology/executing-plans/SKILL.md`
<!-- CUSTOMIZATION POINT -->
## Project-Specific Overrides
Check CLAUDE.md for:
- Preferred task sizing (default: 15-60 min)
- Preferred task sizing (default: 15-60 min, detailed: 2-5 min)
- Required task metadata
- Project-specific planning templates
+37
View File
@@ -260,6 +260,43 @@ pnpm test path/to/file.test.ts
```
```
## Methodology Skills
For enhanced testing practices, use the superpowers methodology:
### Test-Driven Development
**Reference**: `.claude/skills/methodology/test-driven-development/SKILL.md`
Key principles:
- **NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST**
- Red-green-refactor cycle (non-negotiable)
- Delete code written before tests (don't keep as reference)
- One behavior per test with clear naming
- Real code over mocks when possible
### Verification
**Reference**: `.claude/skills/methodology/verification-before-completion/SKILL.md`
Before claiming tests pass:
1. Identify the command that proves assertion
2. Execute it fully and freshly
3. Read complete output
4. Verify output matches claim
5. Only then make the claim
### Testing Anti-Patterns
**Reference**: `.claude/skills/methodology/testing-anti-patterns/SKILL.md`
Avoid these mistakes:
1. Testing mock behavior instead of real code
2. Polluting production with test-only methods
3. Mocking without understanding dependencies
4. Creating incomplete mocks
5. Writing tests as afterthoughts
<!-- CUSTOMIZATION POINT -->
## Project-Specific Overrides
+159
View File
@@ -0,0 +1,159 @@
# /brainstorm - Interactive Design Session
## Purpose
Start an interactive brainstorming session using the one-question-at-a-time methodology. Refine rough ideas into fully-formed designs through collaborative dialogue.
## Usage
```
/brainstorm [topic or feature to design]
```
## Arguments
- `$ARGUMENTS`: The topic, feature, or problem to brainstorm about
---
Start interactive brainstorming session for: **$ARGUMENTS**
## Methodology
**Reference**: `.claude/skills/methodology/brainstorming/SKILL.md`
This command uses the superpowers brainstorming methodology for optimal results.
## Workflow
### Phase 1: Understanding
**Goal**: Clarify requirements through sequential questioning.
**Rules**:
1. Ask **ONE question per message**
2. Wait for user response before next question
3. Prefer **multiple-choice** over open-ended questions
4. Break complex topics into multiple questions
**Example interaction**:
```
Claude: "What type of authentication should we support?
a) Username/password only
b) OAuth providers (Google, GitHub)
c) Both options
d) Magic link (passwordless)"
User: "b"
Claude: "Which OAuth providers should we integrate?
a) Google only
b) GitHub only
c) Both Google and GitHub
d) Let me specify others..."
```
### Phase 2: Exploration
**Goal**: Present alternatives with clear trade-offs.
Present 2-3 approaches:
- Lead with recommended option
- Explain trade-offs for each
- Let user choose direction
```markdown
## Approach 1: JWT-based (Recommended)
- Stateless, scalable
- Cons: Can't revoke instantly
## Approach 2: Session-based
- Easy revocation
- Cons: Requires session store
Which approach aligns better with your goals?
```
### Phase 3: Design Presentation
**Goal**: Present validated design incrementally.
**Rules**:
- Break into **200-300 word sections**
- Validate after each section
- Cover: architecture, components, data flow, error handling, testing
**Sections to present**:
1. Architecture overview
2. Component breakdown
3. Data flow
4. Error handling
5. Testing considerations
## Core Principles
### YAGNI Ruthlessly
Remove unnecessary features aggressively:
- Question every "nice to have"
- Start with minimal viable design
- "We might need this later" = remove it
### One Question at a Time
Sequential questioning produces better results:
- Gives user time to think deeply
- Prevents overwhelming with choices
- Creates natural conversation flow
### Multiple-Choice Preference
When possible, provide structured options:
- Reduces cognitive load
- Surfaces your understanding
- Makes decisions concrete
## Output
After design is validated, create design document:
```markdown
# Design: [Feature Name]
Date: [YYYY-MM-DD]
## Summary
[2-3 sentences]
## Architecture
[Architecture decisions]
## Components
[Component breakdown]
## Data Flow
[How data moves through system]
## Error Handling
[Error scenarios and handling]
## Testing Strategy
[Testing approach]
## Open Questions
[Any remaining unknowns]
```
## Next Steps After Brainstorming
After design is complete:
1. Commit design document to version control
2. Use `/plan --detailed` for implementation planning
3. Use `/execute-plan` for automated implementation
## When NOT to Use
- Clear "mechanical" processes with known implementation
- Simple bug fixes with obvious solutions
- Tasks with explicit requirements already defined
Use direct implementation instead.
+221
View File
@@ -0,0 +1,221 @@
# /execute-plan - Subagent-Driven Plan Execution
## Purpose
Execute a detailed implementation plan using fresh subagents per task with mandatory code review gates between tasks.
## Usage
```
/execute-plan [plan-file-path]
```
## Arguments
- `$ARGUMENTS`: Path to the plan file (created with `/plan --detailed`)
---
Execute plan from: **$ARGUMENTS**
## Methodology
**Reference**: `.claude/skills/methodology/executing-plans/SKILL.md`
This command uses the superpowers execution methodology for quality-gated implementation.
## Core Pattern
**"Fresh subagent per task + review between tasks = high quality, fast iteration"**
### Why Fresh Agents?
- Prevents context pollution between tasks
- Each task gets focused attention
- Failures don't cascade
- Easier to retry individual tasks
### Why Code Review Between Tasks?
- Catches issues early
- Ensures code matches intent
- Prevents technical debt accumulation
- Creates natural checkpoints
## Workflow
### Step 1: Load Plan
1. Read the plan file
2. Verify plan is complete and approved
3. Create TodoWrite with all tasks from plan
4. Set first task to `in_progress`
### Step 2: Execute Task (For Each Task)
```markdown
1. Dispatch fresh subagent with task details
2. Subagent implements following TDD cycle:
- Write failing test
- Verify test fails
- Implement minimally
- Verify test passes
- Commit
3. Subagent returns completion summary
```
### Step 3: Code Review
After each task:
```markdown
1. Dispatch code-reviewer subagent
2. Review scope: only changes from current task
3. Reviewer returns findings:
- Critical: Must fix before proceeding
- Important: Should fix before proceeding
- Minor: Can fix later
```
### Step 4: Handle Review Findings
```markdown
IF Critical or Important issues found:
1. Dispatch fix subagent for each issue
2. Re-request code review
3. Repeat until no Critical/Important issues
IF only Minor issues:
1. Note for later cleanup
2. Proceed to next task
```
### Step 5: Mark Complete
1. Update TodoWrite - mark task completed
2. Move to next task
3. Repeat from Step 2
### Step 6: Final Review
After all tasks complete:
1. Dispatch comprehensive code review
2. Review entire implementation against plan
3. Verify all success criteria met
4. Run full test suite
5. Use `finishing-development-branch` skill
## Critical Rules
### Never Skip Code Reviews
Every task must be reviewed before proceeding. No exceptions.
### Never Proceed with Critical Issues
Critical issues must be fixed:
```
implement → review → fix critical → re-review → proceed
```
### Never Run Parallel Implementation
Tasks run sequentially:
```
WRONG: Run Task 1, 2, 3 simultaneously
RIGHT: Task 1 → Review → Task 2 → Review → Task 3 → Review
```
### Always Read Plan Before Implementing
```
WRONG: Start coding based on memory of plan
RIGHT: Read plan file, extract task details, then implement
```
## Error Handling
### Task Fails
1. Capture error details
2. Attempt fix (max 2 retries)
3. If still failing, pause execution
4. Report to user with:
- Which task failed
- Error details
- Suggested resolution
5. Wait for user decision
### Review Finds Major Issues
1. List all Critical/Important issues
2. Dispatch fix subagent for each
3. Re-run code review
4. If issues persist after 2 cycles:
- Pause execution
- Report to user
- May need plan revision
## Output
### Progress Updates
```markdown
## Execution Progress
### Task 1: Create User model ✓
- Files modified: src/models/user.ts
- Tests added: 3
- Review: Passed
### Task 2: Add validation ✓
- Files modified: src/models/user.ts
- Tests added: 2
- Review: Passed (1 minor deferred)
### Task 3: Create endpoint [IN PROGRESS]
- Status: Implementing...
```
### Completion Summary
```markdown
## Execution Complete
### Summary
- Tasks completed: 8/8
- Tests added: 24
- Coverage: 92%
### Files Created
- src/models/user.ts
- src/services/user-service.ts
- src/routes/user.ts
### Files Modified
- src/routes/index.ts
- src/types/index.ts
### Deferred Items
- Minor: Variable rename in user-service.ts line 12
### Next Steps
- Run full test suite
- Use /ship to create PR
```
## Prerequisites
Before using this command:
1. Plan file exists and is complete
2. Plan was created with `/plan --detailed`
3. Plan has been reviewed and approved
4. Tests can be run (`npm test` or `pytest`)
## Related Commands
- `/plan --detailed` - Create detailed plan
- `/brainstorm` - Design before planning
- `/ship` - Create PR after execution
+66 -1
View File
@@ -191,11 +191,76 @@ For code improvements
### Migration Plan
For data or system migrations
## Detailed Mode (Superpowers Methodology)
Use `--detailed` flag for superpowers-style plans with 2-5 minute tasks:
```
/plan --detailed [task description]
```
### Detailed Mode Features
**Reference**: `.claude/skills/methodology/writing-plans/SKILL.md`
When `--detailed` is specified:
- **Bite-sized tasks**: 2-5 minutes each (vs standard 15-60 min)
- **Exact file paths**: Always include full paths
- **Complete code samples**: Actual code, not descriptions
- **TDD steps per task**: Write test → verify fail → implement → verify pass → commit
- **Expected command outputs**: Specify what success looks like
### Detailed Task Template
```markdown
## Task [N]: [Task Name]
**Files**:
- Create: `path/to/new-file.ts`
- Modify: `path/to/existing-file.ts`
- Test: `path/to/test-file.test.ts`
**Steps**:
1. Write failing test
```typescript
// Exact test code
```
2. Verify test fails
```bash
npm test -- --grep "test name"
# Expected: 1 failing
```
3. Implement minimally
```typescript
// Exact implementation code
```
4. Verify test passes
```bash
npm test -- --grep "test name"
# Expected: 1 passing
```
5. Commit
```bash
git commit -m "feat: add [feature]"
```
```
### Execution After Planning
Use `/execute-plan [plan-file]` for subagent-driven execution with code review gates.
**Reference**: `.claude/skills/methodology/executing-plans/SKILL.md`
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Task size definitions
- Task size definitions (standard: 15-60 min, detailed: 2-5 min)
- Required plan sections
- Estimation approach
- Risk assessment criteria
+47
View File
@@ -69,6 +69,53 @@ Add more test cases and repeat the cycle.
- Keep the red-green-refactor cycle short
- Commit after each green phase
## Superpowers TDD Methodology
**Reference**: `.claude/skills/methodology/test-driven-development/SKILL.md`
### Non-Negotiable Rule
**NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST**
This is not a guideline - it's a rule.
### If You Already Wrote Code
Delete it. Completely. Don't keep it as reference.
```
WRONG: "I'll keep this code as reference while writing tests"
RIGHT: Delete the code, write test, rewrite implementation
```
### Verification Before Completion
**Reference**: `.claude/skills/methodology/verification-before-completion/SKILL.md`
Before claiming tests pass:
1. **Identify** the command that proves assertion
2. **Execute** it fully and freshly
3. **Read** complete output
4. **Verify** output matches claim
5. **Only then** make the claim
### Forbidden Language
Never use without verification:
- "should work"
- "probably fixed"
- "seems to pass"
### Testing Anti-Patterns to Avoid
**Reference**: `.claude/skills/methodology/testing-anti-patterns/SKILL.md`
1. Testing mock behavior instead of real code
2. Polluting production with test-only methods
3. Mocking without understanding dependencies
4. Creating incomplete mocks
5. Writing tests as afterthoughts
## Output
```markdown
@@ -0,0 +1,158 @@
# Brainstorming
## Description
Interactive design refinement methodology for turning rough ideas into fully-formed designs through collaborative dialogue. Use this skill during creative development phases before implementation begins.
## When to Use
- Designing new features with unclear requirements
- Exploring architecture decisions
- Refining user requirements
- Breaking down complex problems
- When multiple valid approaches exist
## When NOT to Use
- Clear "mechanical" processes with known implementation
- Simple bug fixes with obvious solutions
- Tasks with explicit requirements already defined
---
## Three-Phase Process
### Phase 1: Understanding
**Goal**: Clarify requirements through sequential questioning.
**Rules**:
- Ask only ONE question per message
- If a topic needs more exploration, break it into multiple questions
- Prefer multiple-choice questions over open-ended when possible
- Wait for user response before next question
**Example**:
```
BAD: "What authentication method do you want, and should we support SSO,
and what about password requirements?"
GOOD: "Which authentication method should we use?
a) Username/password only
b) OAuth (Google, GitHub)
c) Both options"
```
### Phase 2: Exploration
**Goal**: Present alternatives with clear trade-offs.
**Process**:
1. Present 2-3 different approaches
2. Lead with the recommended option
3. Explain trade-offs for each
4. Let user choose direction
**Format**:
```markdown
## Approach 1: [Name] (Recommended)
[Description]
- Pros: [Benefits]
- Cons: [Drawbacks]
## Approach 2: [Name]
[Description]
- Pros: [Benefits]
- Cons: [Drawbacks]
Which approach aligns better with your goals?
```
### Phase 3: Design Presentation
**Goal**: Present validated design in digestible chunks.
**Rules**:
- Break design into 200-300 word sections
- Validate incrementally after each section
- Cover: architecture, components, data flow, error handling, testing
- Be flexible - allow user to request clarification or changes
**Sections to Cover**:
1. Architecture overview
2. Component breakdown
3. Data flow
4. Error handling
5. Testing considerations
---
## Core Principles
### YAGNI Ruthlessly
Remove unnecessary features aggressively:
- Question every "nice to have"
- Start with minimal viable design
- Add complexity only when justified
- "We might need this later" = remove it
### One Question at a Time
Sequential questioning produces better results:
- Gives user time to think deeply
- Prevents overwhelming with choices
- Creates natural conversation flow
- Allows follow-up on unclear points
### Multiple-Choice Preference
When possible, provide structured options:
- Reduces cognitive load
- Surfaces your understanding
- Makes decisions concrete
- Still allow "Other" option
---
## Output Format
After design validation, document to timestamped markdown:
```markdown
# Design: [Feature Name]
Date: [YYYY-MM-DD]
## Summary
[2-3 sentences]
## Architecture
[Architecture decisions]
## Components
[Component breakdown]
## Data Flow
[How data moves through system]
## Error Handling
[Error scenarios and handling]
## Testing Strategy
[Testing approach]
## Open Questions
[Any remaining unknowns]
```
---
## Post-Design Workflow
After design is validated:
1. Commit design document to version control
2. Optionally proceed to implementation
3. Use `writing-plans` skill for detailed task breakdown
4. Use `executing-plans` skill for implementation
---
@@ -0,0 +1,285 @@
# Defense-in-Depth
## Description
Multi-layer validation strategy that makes bugs structurally impossible rather than merely fixed. After finding and fixing a bug's root cause, implement validation at every layer data passes through.
## When to Use
- After fixing any data-related bug
- Protecting critical data paths
- Preventing bug recurrence
- Building robust systems
- When single validation points have failed
---
## Core Concept
**"Validate at EVERY layer data passes through. Make the bug structurally impossible."**
Single validation points can be bypassed:
- Alternative code paths skip validation
- Refactoring accidentally removes checks
- Tests mock away the validation
Multiple layers create redundancy:
- Different layers catch different cases
- If one check fails, another catches it
- Bug becomes impossible, not just unlikely
---
## The Four-Layer Approach
### Layer 1: Entry Point Validation
Reject invalid input at API/system boundaries:
```typescript
// API endpoint - first line of defense
app.post('/orders', (req, res) => {
// Type check
if (typeof req.body.userId !== 'string') {
return res.status(400).json({ error: 'userId must be a string' });
}
// Existence check
if (!req.body.userId) {
return res.status(400).json({ error: 'userId is required' });
}
// Format validation
if (!isValidUUID(req.body.userId)) {
return res.status(400).json({ error: 'userId must be a valid UUID' });
}
// Proceed with valid data
orderService.createOrder(req.body);
});
```
### Layer 2: Business Logic Validation
Ensure data semantically makes sense for the operation:
```typescript
// Service layer - business rules
class OrderService {
async createOrder(data: OrderData) {
// Business validation
const user = await this.userRepo.findById(data.userId);
if (!user) {
throw new BusinessError('User does not exist');
}
if (!user.canPlaceOrders) {
throw new BusinessError('User is not allowed to place orders');
}
if (data.items.length === 0) {
throw new BusinessError('Order must have at least one item');
}
// Proceed with valid business state
return this.orderRepo.create(data);
}
}
```
### Layer 3: Environment Guards
Add context-specific safeguards:
```typescript
// Repository layer - environment guards
class OrderRepository {
async create(order: Order) {
// Test environment guard
if (process.env.NODE_ENV === 'test' && !process.env.ALLOW_DB_WRITES) {
throw new Error('Database writes disabled in test environment');
}
// Production safety guard
if (order.total > 100000 && !order.managerApproval) {
throw new Error('Large orders require manager approval');
}
// Dangerous operation guard
if (order.userId === SYSTEM_USER_ID) {
throw new Error('Cannot create orders for system user');
}
return this.db.insert('orders', order);
}
}
```
### Layer 4: Debug Instrumentation
Capture execution context for forensic analysis:
```typescript
// Logging layer - forensic evidence
class OrderRepository {
async create(order: Order) {
// Log entry for debugging
this.logger.debug('Creating order', {
orderId: order.id,
userId: order.userId,
itemCount: order.items.length,
total: order.total,
timestamp: new Date().toISOString(),
requestId: context.requestId
});
try {
const result = await this.db.insert('orders', order);
this.logger.info('Order created successfully', {
orderId: result.id,
duration: Date.now() - start
});
return result;
} catch (error) {
this.logger.error('Order creation failed', {
orderId: order.id,
error: error.message,
stack: error.stack,
order: JSON.stringify(order)
});
throw error;
}
}
}
```
---
## Why Multiple Layers?
### Single Point Failure
```typescript
// Only one check - easily bypassed
function createOrder(data) {
if (!data.userId) throw new Error('userId required'); // Single check
// ...
}
// Direct repository call bypasses validation
orderRepository.create({ items: [] }); // No userId check!
```
### Multi-Layer Protection
```typescript
// Multiple checks - defense in depth
// Layer 1: API validates
// Layer 2: Service validates
// Layer 3: Repository validates
// Even if one is bypassed, others catch it
orderRepository.create({ items: [] });
// Repository throws: "userId is required"
```
---
## Implementation Strategy
When debugging, use this approach:
### 1. Trace the Data Flow
```markdown
User Input → API → Service → Repository → Database
```
### 2. Identify Checkpoints
```markdown
Where does this data pass through?
- API endpoint (Layer 1)
- Service method (Layer 2)
- Repository method (Layer 3)
- Database constraints (Layer 4)
```
### 3. Add Validation at Each
```markdown
For each checkpoint:
- What could be wrong at this point?
- What validation makes sense here?
- What error message helps debug?
```
### 4. Test Layer Independence
```markdown
Remove each layer one at a time:
- Does the bug still get caught?
- Which layer catches it?
- Is there a gap in coverage?
```
---
## Validation by Layer Type
| Layer | What to Validate | Example |
|-------|------------------|---------|
| Entry Point | Type, format, presence | `userId` is string, not empty |
| Business Logic | Semantic correctness | User exists, can place orders |
| Environment | Context-specific rules | Test mode restrictions |
| Data Access | Integrity constraints | Foreign keys, not null |
---
## Anti-Patterns
### Single Checkpoint Fallacy
```typescript
// BAD: One validation point
if (isValid(data)) {
// Assume valid everywhere else
}
```
### Validation in Tests Only
```typescript
// BAD: Tests validate, production doesn't
beforeEach(() => {
validateTestData(data); // This doesn't help production
});
```
### Trust After First Check
```typescript
// BAD: Validated once, trusted forever
const validatedData = validate(input);
// ... many lines later ...
process(validatedData); // Is it still valid?
```
---
## Checklist
After fixing any bug:
- [ ] Root cause identified
- [ ] Fix applied at source
- [ ] Layer 1 validation added (entry point)
- [ ] Layer 2 validation added (business logic)
- [ ] Layer 3 guards added (environment)
- [ ] Layer 4 logging added (instrumentation)
- [ ] Tested: removing any single layer still catches bug
- [ ] Bug is structurally impossible, not just fixed
---
@@ -0,0 +1,260 @@
# Dispatching Parallel Agents
## Description
Pattern for handling multiple independent failures by dispatching concurrent agents. Use when 3+ independent problems exist across different domains that can be solved in parallel.
## When to Use
- Multiple subsystems broken independently
- No shared state between failures
- Each fix is self-contained
- Parallel work won't create conflicts
## When NOT to Use
- Related failures (fixing one solves others)
- Exploratory debugging (need full context)
- Problems require shared understanding
- Sequential dependencies exist
---
## Core Principle
**"Dispatch one agent per independent problem domain. Let them work concurrently."**
### Why Parallel?
- Faster resolution (3 problems in time of 1)
- Focused context per agent
- No context pollution between fixes
- Easy to integrate results
### Why Not Always Parallel?
- Related problems need shared context
- Exploration requires system-wide view
- Conflicting changes cause merge issues
- Some fixes depend on others
---
## Identification Pattern
### Step 1: Group Failures by Domain
```markdown
Test failures:
- src/auth/login.test.ts (3 failures) → Auth domain
- src/cart/checkout.test.ts (2 failures) → Cart domain
- src/user/profile.test.ts (1 failure) → User domain
Each is independent - fixing one doesn't affect others.
```
### Step 2: Verify Independence
```markdown
Ask for each group:
- Does it share state with other groups? NO
- Does fixing it require changes to other groups? NO
- Could fixes conflict with each other? NO
If all NO → Parallel is safe
If any YES → Sequential or combined approach
```
---
## Task Creation Pattern
Each agent receives:
### 1. Specific Scope
```markdown
BAD: "Fix all the tests"
GOOD: "Fix auth/login.test.ts - 3 failing tests"
```
### 2. Clear Goal
```markdown
BAD: "Make it work"
GOOD: "Make all tests in auth/login.test.ts pass"
```
### 3. Constraints
```markdown
- Only modify files in src/auth/
- Don't change the test expectations
- Don't modify shared utilities
```
### 4. Expected Output
```markdown
Return:
- Files modified
- Tests now passing
- Summary of changes
- Any concerns
```
---
## Execution Pattern
### Dispatch Agents Concurrently
```markdown
Agent 1: Fix auth/login.test.ts
Agent 2: Fix cart/checkout.test.ts
Agent 3: Fix user/profile.test.ts
All three run simultaneously.
```
### Monitor Progress
```markdown
While agents working:
- Check for early failures
- Watch for scope violations
- Ready to pause if conflicts detected
```
---
## Integration Pattern
### Step 1: Collect Results
```markdown
Agent 1 returned:
- Modified: src/auth/login-service.ts
- Tests: 3/3 passing
- Summary: Fixed token validation edge case
Agent 2 returned:
- Modified: src/cart/checkout-service.ts
- Tests: 2/2 passing
- Summary: Fixed price calculation rounding
Agent 3 returned:
- Modified: src/user/profile-service.ts
- Tests: 1/1 passing
- Summary: Fixed null handling in profile update
```
### Step 2: Verify No Conflicts
```markdown
Check:
- No overlapping file modifications
- No conflicting changes to shared types
- No incompatible API changes
```
### Step 3: Run Full Test Suite
```bash
npm test
# All tests should pass including:
# - The 6 originally failing tests
# - All other tests (no regressions)
```
### Step 4: Integrate Changes
```bash
# If all agents used branches
git merge agent-1-auth-fixes
git merge agent-2-cart-fixes
git merge agent-3-user-fixes
```
---
## Example Prompts
### Agent Task Prompt Template
```markdown
## Task: Fix [specific test file]
**Scope**: Only modify files in [directory]
**Failing tests**:
1. [test name 1]
2. [test name 2]
**Constraints**:
- Do not modify test expectations
- Do not change shared utilities in src/utils/
- Do not modify types in src/types/
**Goal**: Make all tests in [file] pass
**Return**:
- List of files modified
- Summary of changes made
- Number of tests now passing
- Any concerns about the changes
```
### Result Collection Prompt
```markdown
## Parallel Agent Results
**Agent 1 (Auth)**:
[Paste agent 1 results]
**Agent 2 (Cart)**:
[Paste agent 2 results]
**Agent 3 (User)**:
[Paste agent 3 results]
## Integration Checklist
- [ ] No file conflicts
- [ ] Full test suite passes
- [ ] Changes are isolated to domains
- [ ] Ready to merge
```
---
## Conflict Resolution
If conflicts detected:
```markdown
1. STOP parallel execution
2. Identify conflicting changes
3. Decide which takes priority
4. Continue sequentially from conflict point
5. Learn: Update domain boundaries
```
---
## Checklist
Before parallel dispatch:
- [ ] 3+ independent failures identified
- [ ] Failures grouped by domain
- [ ] Independence verified (no shared state)
- [ ] Scope boundaries clear
- [ ] Conflict potential assessed
After parallel completion:
- [ ] All agent results collected
- [ ] No file conflicts detected
- [ ] Full test suite passes
- [ ] Changes integrated successfully
---
@@ -0,0 +1,259 @@
# Executing Plans
## Description
Subagent-driven development pattern for executing detailed implementation plans with quality gates. Uses fresh agents per task and mandatory code review between tasks.
## When to Use
- Executing plans created with `writing-plans` skill
- Staying in current session with independent tasks
- Wanting quality gates without human delays
- Systematic implementation with verification
## When NOT to Use
- Plan needs review first (use brainstorming)
- Tasks are tightly coupled and need shared context
- Plan requires revision during execution
---
## Core Pattern
**"Fresh subagent per task + review between tasks = high quality, fast iteration"**
### Why Fresh Agents?
- Prevents context pollution between tasks
- Each task gets focused attention
- Failures don't cascade
- Easier to retry individual tasks
### Why Code Review Between Tasks?
- Catches issues early
- Ensures code matches intent
- Prevents technical debt accumulation
- Creates natural checkpoints
---
## Execution Workflow
### Step 1: Load Plan
```markdown
1. Read the plan file
2. Verify plan is complete and approved
3. Create TodoWrite with all tasks from plan
4. Set first task to in_progress
```
### Step 2: Execute Task
For each task:
```markdown
1. Dispatch fresh subagent with task details
2. Subagent implements following TDD cycle:
- Write failing test
- Verify test fails
- Implement minimally
- Verify test passes
- Commit
3. Subagent returns completion summary
```
### Step 3: Code Review
After each task:
```markdown
1. Dispatch code-reviewer subagent
2. Review scope: only changes from current task
3. Reviewer returns findings:
- Critical: Must fix before proceeding
- Important: Should fix before proceeding
- Minor: Can fix later
```
### Step 4: Handle Review Findings
```markdown
IF Critical or Important issues found:
1. Dispatch fix subagent for each issue
2. Re-request code review
3. Repeat until no Critical/Important issues
IF only Minor issues:
1. Note for later cleanup
2. Proceed to next task
```
### Step 5: Mark Complete
```markdown
1. Update TodoWrite - mark task completed
2. Move to next task
3. Repeat from Step 2
```
### Step 6: Final Review
After all tasks complete:
```markdown
1. Dispatch comprehensive code review
2. Review entire implementation against plan
3. Verify all success criteria met
4. Run full test suite
5. Use `finishing-development-branch` skill
```
---
## Critical Rules
### Never Skip Code Reviews
Every task must be reviewed before proceeding. No exceptions.
### Never Proceed with Critical Issues
Critical issues must be fixed. The pattern is:
```
implement → review → fix critical → re-review → proceed
```
### Never Run Parallel Implementation
Tasks run sequentially:
```
WRONG: Run Task 1, 2, 3 simultaneously
RIGHT: Run Task 1 → Review → Task 2 → Review → Task 3 → Review
```
### Always Read Plan Before Implementing
```
WRONG: Start coding based on memory of plan
RIGHT: Read plan file, extract task details, then implement
```
---
## Subagent Communication
### Implementation Subagent Prompt
```markdown
## Task: [Task Name]
**Context**: Executing plan for [Feature Name]
**Files to modify**:
- [File paths from plan]
**Steps**:
[Exact steps from plan]
**Requirements**:
- Follow TDD: test first, then implement
- Commit after completion
- Return summary of what was done
**Output expected**:
- Files modified
- Tests added
- Commit hash
- Any issues encountered
```
### Code Review Subagent Prompt
```markdown
## Code Review Request
**Scope**: Changes from Task [N]
**Files changed**:
- [List of files]
**Review against**:
- Plan requirements for this task
- Code quality standards
- Security best practices
- Test coverage
**Return**:
- Critical issues (must fix)
- Important issues (should fix)
- Minor issues (can defer)
- Approval status
```
---
## TodoWrite Integration
Maintain task status throughout:
```markdown
| Task | Status |
|------|--------|
| Task 1: Create model | completed |
| Task 2: Add validation | completed |
| Task 3: Create endpoint | in_progress |
| Task 4: Add tests | pending |
| Task 5: Documentation | pending |
```
Update status in real-time:
- `pending``in_progress` when starting
- `in_progress``completed` when reviewed and approved
---
## Error Handling
### Task Fails
```markdown
1. Capture error details
2. Attempt fix (max 2 retries)
3. If still failing, pause execution
4. Report to user with:
- Which task failed
- Error details
- Suggested resolution
5. Wait for user decision
```
### Review Finds Major Issues
```markdown
1. List all Critical/Important issues
2. Dispatch fix subagent for each
3. Re-run code review
4. If issues persist after 2 cycles:
- Pause execution
- Report to user
- May need plan revision
```
---
## Completion Checklist
Before declaring plan execution complete:
- [ ] All tasks marked completed
- [ ] All code reviews passed
- [ ] Full test suite passes
- [ ] No Critical issues outstanding
- [ ] No Important issues outstanding
- [ ] Final comprehensive review done
- [ ] Ready for `finishing-development-branch`
---
@@ -0,0 +1,275 @@
# Finishing a Development Branch
## Description
Structured 5-step workflow for completing development branches. Ensures tests pass, presents completion options, and handles cleanup.
## When to Use
- After implementing a feature
- After all tests pass
- Ready to merge or create PR
- Cleaning up after development
---
## The 5-Step Workflow
### Step 1: Verify Tests
Run the project's test suite:
```bash
npm test
# or
pytest
# or
go test ./...
```
**Decision point**:
- Tests PASS → Continue to Step 2
- Tests FAIL → STOP. Cannot proceed with failing tests.
```markdown
⚠️ STOP: Tests failing
Cannot proceed with merge/PR until tests pass.
Fix failing tests first, then restart this workflow.
```
### Step 2: Determine Base Branch
Identify which branch this feature branch originated from:
```bash
# Check tracking branch
git branch -vv
# Or check common bases
git merge-base main feature-branch
git merge-base develop feature-branch
```
Common base branches:
- `main` or `master` - Production
- `develop` - Development
- `release/*` - Release branches
### Step 3: Present Options
Offer exactly four choices:
```markdown
## Branch Completion Options
Your feature branch `feature/email-verification` is ready.
All tests pass (42/42).
Choose how to proceed:
1. **Merge locally** - Merge into [base] on your machine
2. **Create Pull Request** - Push and open PR for review
3. **Keep as-is** - Leave branch for later work
4. **Discard** - Delete this branch and all changes
Enter your choice (1-4):
```
### Step 4: Execute Choice
#### Option 1: Merge Locally
```bash
# Switch to base branch
git checkout main
# Pull latest
git pull origin main
# Merge feature branch
git merge feature/email-verification
# Verify tests still pass
npm test
# Delete feature branch
git branch -d feature/email-verification
```
#### Option 2: Create Pull Request
```bash
# Push branch to remote
git push -u origin feature/email-verification
# Create PR (using gh CLI)
gh pr create \
--title "Add email verification" \
--body "## Summary
- Implements email verification flow
- Adds verification token generation
- Includes tests for all scenarios
## Test Plan
- [x] Unit tests pass
- [x] Integration tests pass
- [x] Manual testing complete"
```
#### Option 3: Keep As-Is
```markdown
Branch preserved: feature/email-verification
Note: Remember to return to this branch later.
Current state: All tests passing, ready for merge.
```
#### Option 4: Discard
```markdown
⚠️ WARNING: This will delete all work on this branch.
Type "discard" to confirm: _______
```
If confirmed:
```bash
# Switch away from branch
git checkout main
# Force delete branch
git branch -D feature/email-verification
# If pushed to remote, delete there too
git push origin --delete feature/email-verification
```
### Step 5: Cleanup Worktree (if applicable)
For options 1, 2, and 4, cleanup the worktree environment:
```bash
# Remove worktree
git worktree remove ../feature-email-verification
# Or if worktree is in special location
git worktree remove /path/to/worktree
```
For option 3 (keep), preserve the worktree.
---
## Decision Flow
```
┌─────────────────────────┐
│ Tests Passing? │
└───────────┬─────────────┘
┌────┴────┐
│ NO │──────► STOP: Fix tests first
└─────────┘
YES
┌─────────────────────────┐
│ Present 4 Options │
└───────────┬─────────────┘
┌───────┼───────┬───────┐
│ │ │ │
▼ ▼ ▼ ▼
Merge PR Keep Discard
│ │ │ │
▼ ▼ │ ▼
Cleanup Cleanup │ Confirm
│ │ │ │
▼ ▼ │ ▼
Done Done Done Cleanup
Done
```
---
## Pull Request Template
When choosing Option 2:
```markdown
## Summary
[Brief description of changes]
## Changes
- [Change 1]
- [Change 2]
- [Change 3]
## Test Plan
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing scenarios:
- [ ] Scenario 1
- [ ] Scenario 2
## Screenshots (if applicable)
[Add screenshots here]
## Related Issues
Closes #[issue number]
```
---
## Verification Before Each Option
### Before Merge
```markdown
- [ ] Tests pass on feature branch
- [ ] Base branch is up to date
- [ ] No merge conflicts
- [ ] Tests pass after merge
```
### Before PR
```markdown
- [ ] Tests pass
- [ ] Branch pushed to remote
- [ ] PR description complete
- [ ] Reviewers assigned (if required)
```
### Before Discard
```markdown
- [ ] Confirmed with user (typed "discard")
- [ ] No valuable uncommitted changes
- [ ] Branch deleted locally
- [ ] Branch deleted from remote (if pushed)
```
---
## Core Principle
**"Verify tests → Present options → Execute choice → Clean up"**
Never:
- Merge with failing tests
- Delete work without confirmation
- Skip the verification step
- Leave orphaned worktrees
---
@@ -0,0 +1,258 @@
# Receiving Code Review
## Description
Workflow for processing code review feedback effectively. Prioritize issues, apply fixes, and iterate until approval.
## When to Use
- After receiving review feedback
- Processing automated review results
- Handling reviewer comments on PRs
- Iterating after code review rejection
---
## Feedback Categories
### Critical Issues
**Definition**: Must fix before proceeding. Security vulnerabilities, data loss risks, broken functionality.
```markdown
Examples:
- SQL injection vulnerability
- Unhandled null pointer
- Data corruption possibility
- Authentication bypass
```
**Response**: Fix immediately. Do not proceed until resolved.
### Important Issues
**Definition**: Should fix before proceeding. Code quality, maintainability, potential bugs.
```markdown
Examples:
- Missing error handling
- Inefficient algorithm
- Poor naming
- Missing tests for edge cases
```
**Response**: Fix before merging. May defer to follow-up if blocking.
### Minor Issues
**Definition**: Can fix later. Style preferences, optional improvements.
```markdown
Examples:
- Variable naming suggestions
- Comment improvements
- Minor refactoring opportunities
- Documentation polish
```
**Response**: Note for later. Can merge without addressing.
---
## Processing Workflow
### Step 1: Categorize All Feedback
```markdown
## Review Feedback
### Critical (Must Fix)
1. Line 45: SQL query vulnerable to injection
2. Line 89: User data exposed in logs
### Important (Should Fix)
1. Line 23: Missing null check
2. Line 67: Test doesn't cover error path
### Minor (Can Defer)
1. Line 12: Consider renaming 'x' to 'count'
2. Line 34: Could extract to helper function
```
### Step 2: Fix Critical Issues First
```markdown
Addressing critical issue 1:
- File: src/db/queries.ts:45
- Issue: SQL injection vulnerability
- Fix: Use parameterized query
- Verification: Tested with malicious input
```
### Step 3: Fix Important Issues
```markdown
Addressing important issue 1:
- File: src/services/user.ts:23
- Issue: Missing null check
- Fix: Added guard clause
- Verification: Test added for null case
```
### Step 4: Note Minor Issues
```markdown
Deferred for follow-up:
- Line 12: Variable rename (tracked in TODO)
- Line 34: Extract helper (low priority)
```
### Step 5: Request Re-Review
After fixes applied, request re-review with:
```markdown
## Re-Review Request
### Fixed Issues
- [x] SQL injection (line 45) - Now uses parameterized query
- [x] Data exposure (line 89) - Removed user data from logs
- [x] Null check (line 23) - Added guard clause
- [x] Test coverage (line 67) - Added error path test
### Deferred (Minor)
- Variable rename (line 12) - Will address in cleanup PR
### Changes Since Last Review
- 4 files modified
- 2 tests added
- All previous feedback addressed
```
---
## Handling Disagreements
### When You Disagree with Feedback
```markdown
1. Don't dismiss immediately
2. Consider the reviewer's perspective
3. Explain your reasoning
4. Provide evidence (code, tests, docs)
5. Be open to being wrong
6. Escalate if needed (tech lead, team discussion)
```
### Disagreement Response Template
```markdown
## Re: [Feedback item]
I considered this feedback carefully. Here's my perspective:
**Reviewer's concern**: [Their point]
**My reasoning**: [Why I did it this way]
**Evidence**: [Tests, benchmarks, docs supporting approach]
**Proposed resolution**: [Accept, discuss, or defer]
```
---
## Common Feedback Types
### Security Issues
Always fix immediately:
```typescript
// Before (vulnerable)
const query = `SELECT * FROM users WHERE id = '${userId}'`;
// After (secure)
const query = 'SELECT * FROM users WHERE id = $1';
const result = await db.query(query, [userId]);
```
### Error Handling
Add comprehensive handling:
```typescript
// Before
const user = await getUser(id);
return user.name;
// After
const user = await getUser(id);
if (!user) {
throw new NotFoundError(`User ${id} not found`);
}
return user.name;
```
### Test Coverage
Add missing tests:
```typescript
// Before: Only happy path tested
it('should return user', async () => {
const user = await getUser('valid-id');
expect(user).toBeDefined();
});
// After: Edge cases covered
it('should return user', async () => { /* ... */ });
it('should throw NotFoundError for missing user', async () => { /* ... */ });
it('should throw ValidationError for invalid id', async () => { /* ... */ });
```
### Performance
Address efficiency concerns:
```typescript
// Before (N+1 query)
const users = await getUsers();
for (const user of users) {
user.orders = await getOrders(user.id);
}
// After (batch query)
const users = await getUsers();
const userIds = users.map(u => u.id);
const ordersByUser = await getOrdersForUsers(userIds);
users.forEach(u => u.orders = ordersByUser[u.id]);
```
---
## Re-Review Checklist
Before requesting re-review:
- [ ] All Critical issues fixed
- [ ] All Important issues fixed (or explicitly deferred with reason)
- [ ] Minor issues noted for follow-up
- [ ] Tests added/updated for fixes
- [ ] Full test suite passes
- [ ] Changes summarized for reviewer
---
## Iteration Limits
```markdown
If review requires 3+ cycles:
1. STOP
2. Schedule discussion with reviewer
3. Identify root cause of misalignment
4. May need design discussion
5. Don't keep iterating endlessly
```
---
@@ -0,0 +1,239 @@
# Requesting Code Review
## Description
Workflow for initiating code reviews with clear scope, context, and expectations. Ensures reviewers have everything needed for effective feedback.
## When to Use
- After completing a task (before proceeding to next)
- After implementing a feature
- Before merging to main branch
- When unsure about implementation approach
- After fixing critical bugs
---
## Review Request Components
### 1. Scope Definition
Clearly state what should be reviewed:
```markdown
## Review Scope
**Files changed**:
- src/services/user-service.ts (modified)
- src/services/user-service.test.ts (added)
- src/types/user.ts (modified)
**Lines changed**: ~150 additions, ~20 deletions
**Not in scope** (don't review):
- package.json changes (unrelated dependency update)
- Generated files in dist/
```
### 2. Context
Explain why these changes were made:
```markdown
## Context
**Task**: Implement user email verification
**Requirements**:
- Users must verify email before accessing features
- Verification link expires after 24 hours
- Users can request new verification email
**Design decisions**:
- Used JWT for verification token (stateless)
- Stored verification status in existing User table
```
### 3. Areas of Concern
Highlight where you want focused attention:
```markdown
## Areas of Concern
1. **Security**: Is the token generation secure enough?
2. **Error handling**: Are all edge cases covered?
3. **Performance**: Will the verification lookup be efficient?
```
### 4. Test Coverage
Show what's tested:
```markdown
## Test Coverage
- Unit tests: 8 new tests in user-service.test.ts
- Integration: Manual testing of full flow
- Edge cases: Expired token, invalid token, already verified
**Not tested** (known gaps):
- Load testing with many concurrent verifications
```
---
## Review Request Template
```markdown
## Code Review Request
### Summary
[1-2 sentence description of changes]
### Files Changed
- `path/to/file1.ts` - [Brief description]
- `path/to/file2.ts` - [Brief description]
### Context
[Why these changes were needed]
### Implementation Notes
[Key decisions made and why]
### Areas for Focus
1. [Specific concern 1]
2. [Specific concern 2]
### Testing
- [x] Unit tests added/updated
- [x] Integration tests pass
- [ ] E2E tests (not applicable)
### Checklist
- [x] Code follows project conventions
- [x] No security vulnerabilities introduced
- [x] Documentation updated if needed
```
---
## What to Include
### Always Include
- List of changed files
- Summary of what changed
- Why the change was needed
- Test status
### Include When Relevant
- Design alternatives considered
- Performance implications
- Security considerations
- Breaking changes
### Never Include
- Unrelated changes
- Formatting-only commits
- Debug code
- TODO comments (resolve first)
---
## Review Types
### Quick Review
For small, low-risk changes:
```markdown
## Quick Review: Fix typo in error message
**File**: src/errors.ts
**Change**: Fixed "recieved" → "received" in error message
**Risk**: None
```
### Standard Review
For typical feature work:
```markdown
## Review: Add user preferences
**Files**: 3 files, ~200 lines
**Context**: Users can now save display preferences
**Focus**: Data validation, storage approach
```
### Critical Review
For high-risk changes:
```markdown
## CRITICAL REVIEW: Authentication refactor
**Files**: 12 files, ~800 lines
**Risk**: HIGH - Authentication system changes
**Required reviewers**: Security team
**Focus**: Token handling, session management, encryption
```
---
## Best Practices
### Keep Reviews Focused
```markdown
BAD: "Review my last week of work"
GOOD: "Review the user verification feature (3 files)"
```
### Provide Runnable Context
```markdown
## To test locally
1. git checkout feature/email-verification
2. npm install
3. npm test -- --grep "email verification"
```
### Be Specific About Concerns
```markdown
BAD: "Let me know if anything looks wrong"
GOOD: "I'm unsure about the error handling in lines 45-60"
```
### Include Relevant Links
```markdown
Related:
- Ticket: PROJ-123
- Design doc: [link]
- Previous discussion: [link]
```
---
## After Submitting
### What to Expect
```markdown
Reviewer will return:
- Critical issues (must fix)
- Important issues (should fix)
- Minor issues (optional)
- Approval/rejection status
```
### How to Handle Feedback
See `receiving-code-review` skill for detailed guidance.
---
@@ -0,0 +1,230 @@
# Root Cause Tracing
## Description
Debugging technique for bugs that manifest deep in execution stacks. Systematically trace backward through the call chain to identify the original trigger, rather than fixing symptoms at the point of failure.
## When to Use
- Errors occur far from entry points
- Data corruption with unclear source
- Need to identify which code path triggers failures
- Stack traces show multiple levels of indirection
- "It was already wrong by the time it got here"
---
## Core Principle
**"Trace backward through the call chain until you find the original trigger, then fix at the source."**
The error location is rarely the bug location:
```
User Input → Validation → Service → Repository → Database
^ ^
| |
Bug HERE Error appears HERE
(bad input allowed) (constraint violation)
```
Fixing at the database layer treats the symptom. Fixing at validation prevents the bug.
---
## The Tracing Methodology
### Step 1: Identify Observable Error
Document exactly what you see:
```markdown
Error: "Cannot insert NULL into column 'user_id'"
Location: database-repository.ts:156
Stack trace: [full trace]
```
### Step 2: Locate Immediate Cause
Find the code directly responsible:
```typescript
// database-repository.ts:156
async function insertOrder(order: Order) {
await db.insert('orders', {
user_id: order.userId, // <- This is NULL
// ...
});
}
```
### Step 3: Trace One Level Up
Who called this function? What did they pass?
```typescript
// order-service.ts:89
async function createOrder(orderData: OrderData) {
const order = new Order(orderData);
await repository.insertOrder(order); // <- Called from here
}
```
### Step 4: Continue Tracing
Keep going up the call chain:
```typescript
// order-controller.ts:45
async function handleCreateOrder(req: Request) {
const orderData = req.body; // <- userId might be missing here
await orderService.createOrder(orderData);
}
```
### Step 5: Find Original Source
Reach the entry point where the problem originated:
```typescript
// The real bug: No validation at entry point
// req.body.userId was never validated
```
---
## Instrumentation Techniques
When manual analysis fails, add diagnostic logging:
### Strategic Console.error
```typescript
// Add before suspicious operations
console.error('[TRACE] order-service.createOrder input:', {
orderData,
hasUserId: !!orderData.userId,
stack: new Error().stack
});
```
### Stack Trace Capture
```typescript
// Capture where a value came from
function setUserId(id: string | null) {
if (id === null) {
console.error('[TRACE] userId set to null from:', new Error().stack);
}
this.userId = id;
}
```
### Boundary Logging
```typescript
// Log at every system boundary
async function callExternalApi(params) {
console.error('[TRACE] API request:', params);
const response = await fetch(url, params);
console.error('[TRACE] API response:', response.status, await response.text());
return response;
}
```
### Environment/Context Logging
```typescript
console.error('[TRACE] Context:', {
env: process.env.NODE_ENV,
timestamp: new Date().toISOString(),
requestId: context.requestId,
userId: context.user?.id
});
```
---
## Finding the Instrumentation Output
After adding logging:
```bash
# Run tests and grep for traces
npm test 2>&1 | grep "\[TRACE\]"
# Or run specific test
npm test -- --grep "failing test" 2>&1 | grep "\[TRACE\]"
```
---
## Common Root Cause Locations
| Where Error Appears | Where Bug Often Is |
|--------------------|--------------------|
| Database constraint | Input validation |
| Type error in service | Data transformation |
| Null reference | Optional field handling |
| API timeout | Connection pool config |
| Memory error | Resource cleanup |
---
## Defense-in-Depth Integration
After finding root cause, add validation at multiple layers:
```typescript
// Layer 1: Entry point
function handleRequest(req) {
if (!req.body.userId) {
throw new ValidationError('userId required');
}
}
// Layer 2: Service
function createOrder(data) {
assert(data.userId, 'userId must be provided to createOrder');
}
// Layer 3: Repository
function insertOrder(order) {
assert(order.userId, 'Cannot insert order without userId');
}
```
See `defense-in-depth` skill for comprehensive approach.
---
## Critical Warning
**"NEVER fix just where the error appears."**
Fixing at the error location:
- Treats symptom, not cause
- Leaves bug available to trigger from other paths
- Creates false confidence
- Guarantees the bug will return
Fixing at the source:
- Prevents the bug entirely
- Protects all code paths
- Creates robust system
- Actually solves the problem
---
## Tracing Checklist
- [ ] Error message and location documented
- [ ] Immediate cause identified
- [ ] Call chain traced backward
- [ ] Original source found
- [ ] Instrumentation added if needed
- [ ] Fix applied at source (not symptom)
- [ ] Defense-in-depth validation added
- [ ] Test proves fix works
---
@@ -0,0 +1,258 @@
# Systematic Debugging
## Description
Four-phase debugging methodology centered on finding root causes before implementing fixes. The foundational principle: **"NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST"**
## When to Use
- Bug reports with unclear cause
- Errors appearing in production
- Tests failing unexpectedly
- Intermittent/flaky issues
- Complex multi-component failures
---
## The Four Phases
### Phase 1: Root Cause Investigation
**Goal**: Understand what's happening before attempting to fix.
**Steps**:
1. **Read error messages carefully**
```markdown
- What is the exact error message?
- What is the stack trace?
- What line numbers are mentioned?
- What values are shown?
```
2. **Reproduce consistently**
```markdown
- Can you trigger the bug reliably?
- What exact steps reproduce it?
- What environment is required?
- Document the reproduction steps
```
3. **Track recent changes**
```markdown
- What changed recently?
- git log --oneline -20
- When did it last work?
- What was deployed?
```
4. **Gather evidence**
```markdown
- Collect logs
- Check monitoring/metrics
- Review related code
- Note any patterns
```
5. **Add instrumentation** (for multi-component systems)
```typescript
// Add diagnostic logging at each boundary
console.error('[DEBUG] Input received:', JSON.stringify(input));
console.error('[DEBUG] After validation:', JSON.stringify(validated));
console.error('[DEBUG] Before database call:', JSON.stringify(query));
console.error('[DEBUG] Database result:', JSON.stringify(result));
```
---
### Phase 2: Pattern Analysis
**Goal**: Find comparable working code to identify differences.
**Steps**:
1. **Find working code**
```markdown
- Is there similar functionality that works?
- What did this code look like before?
- Are there reference implementations?
```
2. **Study reference thoroughly**
```markdown
- How does the working version handle this case?
- What dependencies does it use?
- What assumptions does it make?
```
3. **Identify differences**
```markdown
- What's different between working and broken?
- Configuration differences?
- Data differences?
- Environment differences?
```
4. **Understand dependencies**
```markdown
- What does this code depend on?
- What depends on this code?
- Are dependencies behaving correctly?
```
---
### Phase 3: Hypothesis and Testing
**Goal**: Form and test a specific theory about the cause.
**Steps**:
1. **Form specific hypothesis**
```markdown
Write it down explicitly:
"The bug occurs because [X] causes [Y] when [Z]"
Example:
"The bug occurs because the cache returns stale data
when the user's session expires during an active request"
```
2. **Test with minimal changes**
```markdown
- Change ONE variable at a time
- Don't combine multiple fixes
- Verify results after each change
```
3. **Validate hypothesis**
```markdown
- Does the fix address the hypothesis?
- Can you explain WHY it works?
- Does it make the bug impossible, not just unlikely?
```
---
### Phase 4: Implementation
**Goal**: Fix properly with verification.
**Steps**:
1. **Write failing test first**
```typescript
it('should handle expired session during request', () => {
// Reproduce the bug scenario
const session = createExpiredSession();
const result = processRequest(session);
// This should fail before the fix
expect(result.error).toBe('SESSION_EXPIRED');
});
```
2. **Implement single targeted fix**
```typescript
// Fix addresses root cause, not symptom
function processRequest(session: Session) {
if (session.isExpired()) {
return { error: 'SESSION_EXPIRED' };
}
// ... rest of logic
}
```
3. **Verify fix works**
```bash
npm test -- --grep "expired session"
# Should pass
```
4. **Verify no regressions**
```bash
npm test
# All tests should pass
```
---
## The Three-Fix Rule
**If three or more fixes fail consecutively, STOP.**
This signals an architectural problem, not a simple bug:
```markdown
Fix attempt 1: Failed
Fix attempt 2: Failed
Fix attempt 3: Failed
STOP: This is not a bug - this is a design problem.
Action: Discuss with user/team before proceeding
- Explain what's been tried
- Explain why it's not working
- Propose architectural changes
```
---
## Key Principles
### Never Skip Error Details
```markdown
BAD: "There's an error somewhere"
GOOD: "TypeError: Cannot read property 'id' of undefined
at UserService.getUser (user-service.ts:42)"
```
### Reproduce Before Investigating
```markdown
BAD: "I think I know what's wrong" (starts coding)
GOOD: "Let me reproduce this first" (writes repro steps)
```
### Trace Backward to Origin
```markdown
BAD: Fix where error appears
GOOD: Trace data backward to find where it became invalid
```
### One Change Per Test
```markdown
BAD: "I changed A, B, and C - now it works!"
(Which one fixed it? Are the others safe?)
GOOD: "I changed A - still broken.
I reverted A and changed B - now it works.
B was the fix."
```
---
## Debugging Checklist
Before attempting any fix:
- [ ] Error message fully read and understood
- [ ] Bug reproduced consistently
- [ ] Recent changes reviewed
- [ ] Evidence gathered (logs, traces)
- [ ] Hypothesis written down
- [ ] Similar working code identified
- [ ] Root cause identified (not just symptom)
Before declaring fixed:
- [ ] Failing test written
- [ ] Fix implemented
- [ ] Test passes
- [ ] No regressions (full test suite passes)
- [ ] Fix explained (can articulate why it works)
---
@@ -0,0 +1,243 @@
# Test-Driven Development (TDD)
## Description
Strict test-driven development methodology requiring tests before implementation. The fundamental practice: "If you didn't watch the test fail, you don't know if it tests the right thing."
## When to Use
- New feature development
- Bug fixes (write test that reproduces bug first)
- Refactoring (ensure tests exist before changing)
- Any behavior change
## When NOT to Use (Requires Explicit Approval)
- Throwaway prototypes
- Generated/scaffolded code
- Pure configuration changes
---
## The Red-Green-Refactor Cycle
### 1. RED: Write Failing Test
Write a minimal test demonstrating the desired behavior:
```typescript
describe('calculateTotal', () => {
it('should sum item prices', () => {
const items = [{ price: 10 }, { price: 20 }];
expect(calculateTotal(items)).toBe(30);
});
});
```
### 2. VERIFY RED: Confirm Test Fails
Run the test and confirm it fails **for the right reason**:
```bash
npm test -- --grep "sum item prices"
# Expected: FAIL
# Reason: calculateTotal is not defined
```
**Critical**: The failure should be because the feature doesn't exist, not because of typos or syntax errors.
### 3. GREEN: Write Minimal Code
Write the simplest code that makes the test pass:
```typescript
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
```
**Don't over-engineer**. If the test passes with simple code, stop.
### 4. VERIFY GREEN: Confirm Test Passes
Run the test and confirm it passes:
```bash
npm test -- --grep "sum item prices"
# Expected: PASS
```
### 5. REFACTOR: Clean Up
With green tests, refactor safely:
- Extract functions
- Rename variables
- Remove duplication
- Run tests after each change
---
## The Non-Negotiable Rule
**NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST**
This is not a guideline. It's a rule.
### What If I Already Wrote Code?
Delete it. Completely.
```
WRONG: "I'll keep this code as reference while writing tests"
RIGHT: Delete the code, write test, rewrite implementation
```
### Why So Strict?
- Code written before tests wasn't driven by tests
- Keeping it as reference leads to rationalization
- Tests written after code often just verify what was written
- True TDD produces different (usually better) designs
---
## Test Quality Standards
### One Behavior Per Test
```typescript
// BAD: Multiple behaviors
it('should validate and save user', () => {
expect(validateUser(user)).toBe(true);
expect(saveUser(user)).toBe(1);
});
// GOOD: Single behavior
it('should validate user email format', () => {
expect(validateUser({ email: 'test@example.com' })).toBe(true);
});
it('should save valid user', () => {
const user = createValidUser();
expect(saveUser(user)).toBe(1);
});
```
### Clear Naming
Test names should describe the behavior:
```typescript
// BAD
it('test1', () => {});
it('calculateTotal', () => {});
// GOOD
it('should return 0 for empty cart', () => {});
it('should apply discount when coupon is valid', () => {});
```
### Real Code Over Mocks
Use real implementations when possible:
```typescript
// PREFER: Real database (test container)
const db = await startTestDatabase();
const result = await userRepo.save(user);
// AVOID: Excessive mocking
const mockDb = { save: jest.fn().mockResolvedValue(1) };
```
### Test Observable Behavior
Test what the code does, not how it does it:
```typescript
// BAD: Testing implementation
it('should call helper function', () => {
calculateTotal(items);
expect(helperFn).toHaveBeenCalled();
});
// GOOD: Testing behavior
it('should return correct total', () => {
expect(calculateTotal(items)).toBe(30);
});
```
---
## Common Rationalizations (Reject These)
### "I'll write tests after"
Tests written after code verify what was written, not what should happen. The test can't prove the code is correct if it was shaped to match existing code.
### "Manual testing is enough"
Ad-hoc testing is not systematic. It misses edge cases, isn't repeatable, and doesn't prevent regressions.
### "This code is too simple to test"
Simple code breaks too. A test takes seconds and provides permanent verification.
### "I don't have time"
TDD is faster in the medium term. Debugging time saved far exceeds test-writing time.
### "I already wrote it, might as well keep it"
Sunk cost fallacy. Delete and rewrite properly.
---
## Edge Cases to Test
Always include tests for:
- Empty inputs
- Null/undefined values
- Boundary conditions
- Error scenarios
- Large inputs
- Invalid inputs
```typescript
describe('calculateTotal', () => {
it('should return 0 for empty array', () => {
expect(calculateTotal([])).toBe(0);
});
it('should handle null items array', () => {
expect(() => calculateTotal(null)).toThrow();
});
it('should handle negative prices', () => {
const items = [{ price: -10 }, { price: 20 }];
expect(calculateTotal(items)).toBe(10);
});
});
```
---
## TDD Catches Bugs
The methodology catches bugs before commit:
- Writing test first forces you to think about edge cases
- Seeing test fail proves it can catch failures
- Green bar confirms the fix works
- Test prevents regression forever
This is faster than:
1. Write code
2. Manual test (miss edge case)
3. Ship
4. Bug reported
5. Debug
6. Fix
7. Ship again
---
@@ -0,0 +1,258 @@
# Testing Anti-Patterns
## Description
Common testing mistakes that create false confidence in test suites. Learn to recognize and avoid these patterns that make tests pass while failing to verify actual behavior.
## When to Use
- Writing new tests
- Reviewing test code
- Debugging flaky or unreliable tests
- When tests pass but bugs still ship
---
## The Five Anti-Patterns
### 1. Testing Mock Behavior Instead of Real Code
**The Problem**:
Tests verify mocks work, not that actual code works.
```typescript
// BAD: Testing the mock
it('should call the database', () => {
const mockDb = { save: jest.fn().mockResolvedValue({ id: 1 }) };
const service = new UserService(mockDb);
await service.createUser({ name: 'Test' });
expect(mockDb.save).toHaveBeenCalled(); // Only proves mock was called
});
```
**The Solution**:
Test actual behavior with real (or realistic) dependencies.
```typescript
// GOOD: Testing real behavior
it('should persist user to database', async () => {
const db = await createTestDatabase();
const service = new UserService(db);
const result = await service.createUser({ name: 'Test' });
const saved = await db.findById(result.id);
expect(saved.name).toBe('Test'); // Proves data was actually saved
});
```
**Key Principle**: "Test what the code does, not what the mocks do."
---
### 2. Polluting Production with Test-Only Methods
**The Problem**:
Adding methods to production code solely for test cleanup or access.
```typescript
// BAD: Production class with test-only method
class ConnectionPool {
private connections: Connection[] = [];
// This method exists only for tests
destroy(): void { // DON'T DO THIS
this.connections.forEach(c => c.close());
this.connections = [];
}
}
```
**The Solution**:
Handle cleanup in test utilities, not production code.
```typescript
// GOOD: Test utility handles cleanup
// test-utils/connection-pool.ts
export async function withTestPool(fn: (pool: ConnectionPool) => Promise<void>) {
const pool = new ConnectionPool();
try {
await fn(pool);
} finally {
// Cleanup handled by test infrastructure
await closeAllConnections(pool);
}
}
```
**Key Principle**: Production code should never know it's being tested.
---
### 3. Mocking Without Understanding Dependencies
**The Problem**:
Over-mocking to "be safe" removes behavior the test actually depends on.
```typescript
// BAD: Mocking everything blindly
it('should process order', () => {
jest.mock('./inventory'); // What does this mock?
jest.mock('./payment'); // Did we need to mock this?
jest.mock('./shipping'); // This might break the test logic
const result = processOrder(order);
expect(result.status).toBe('complete');
});
```
**The Solution**:
Understand what each dependency does before mocking it.
```typescript
// GOOD: Selective, understood mocking
it('should process order when payment succeeds', () => {
// Only mock external service (payment gateway)
// Keep inventory and shipping real for integration test
const paymentGateway = createMockPaymentGateway({
chargeResult: { success: true, transactionId: 'txn-123' }
});
const result = processOrder(order, { paymentGateway });
expect(result.status).toBe('complete');
expect(result.transactionId).toBe('txn-123');
});
```
**Key Principle**: Mock at boundaries, not internally.
---
### 4. Creating Incomplete Mocks
**The Problem**:
Partial mocks that only include known fields, hiding structural assumptions.
```typescript
// BAD: Incomplete mock
const mockApiResponse = {
data: { users: [] }
// Missing: status, headers, pagination, errors
};
it('should handle API response', () => {
fetchMock.mockResolvedValue(mockApiResponse);
const result = await getUsers();
expect(result).toEqual([]);
});
// Test passes, but production fails when accessing response.pagination
```
**The Solution**:
Create complete mocks that match real API responses.
```typescript
// GOOD: Complete mock matching real response structure
const mockApiResponse = {
status: 200,
headers: { 'content-type': 'application/json' },
data: {
users: [],
pagination: { page: 1, total: 0, hasMore: false },
errors: null
}
};
it('should handle empty API response', () => {
fetchMock.mockResolvedValue(mockApiResponse);
const result = await getUsers();
expect(result.users).toEqual([]);
expect(result.hasMore).toBe(false);
});
```
**Key Principle**: Mocks should be indistinguishable from real responses.
---
### 5. Writing Tests as Afterthoughts
**The Problem**:
Treating testing as optional follow-up work rather than integral to development.
```typescript
// BAD: Tests written after code, just verifying what exists
it('should do what the function does', () => {
// This test was written by looking at the implementation
// It tests the current behavior, not the intended behavior
const result = processData(input);
expect(result).toMatchSnapshot(); // "Whatever it does is correct"
});
```
**The Solution**:
Use TDD - tests define requirements before implementation.
```typescript
// GOOD: Test written first, defines requirement
it('should filter inactive users from report', () => {
const users = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false }
];
const report = generateReport(users);
expect(report.users).toHaveLength(1);
expect(report.users[0].name).toBe('Alice');
});
// Now implement generateReport to make this pass
```
**Key Principle**: TDD prevents all these anti-patterns naturally.
---
## Recognition Guide
| Symptom | Likely Anti-Pattern |
|---------|---------------------|
| Tests pass but bugs ship | #1 Testing mocks |
| `destroy()` or `reset()` in production | #2 Test pollution |
| "I mocked that to be safe" | #3 Blind mocking |
| TypeError in production, not tests | #4 Incomplete mocks |
| Tests feel like documentation | #5 Afterthought tests |
---
## Prevention Checklist
Before committing tests, verify:
- [ ] Tests use real dependencies where possible
- [ ] Mocks are for external boundaries only
- [ ] No production code exists solely for tests
- [ ] Mock structures match real API responses
- [ ] Tests were written before implementation (TDD)
- [ ] Tests verify behavior, not implementation details
---
## Core Principle
**"Mocks are tools to isolate, not things to test."**
Mocks help you:
- Isolate unit under test
- Control external dependencies
- Speed up slow operations (network, disk)
Mocks should never:
- Be the thing you're verifying
- Hide bugs in dependencies
- Create false confidence
---
@@ -0,0 +1,262 @@
# Verification Before Completion
## Description
Mandatory verification process before claiming any task is complete. This skill enforces evidence-based completion rather than assumption-based claims.
## When to Use
- Before claiming tests pass
- Before claiming build succeeds
- Before claiming bug is fixed
- Before marking any task complete
- Before declaring success to user
---
## The 5-Step Verification Process
### Step 1: IDENTIFY
Determine the command that proves your assertion:
```markdown
Claim: "Tests pass"
Verification command: npm test
Claim: "Build succeeds"
Verification command: npm run build
Claim: "Linting passes"
Verification command: npm run lint
```
### Step 2: EXECUTE
Run the command fully and freshly:
```bash
# Don't rely on cached results
# Don't assume previous run is still valid
npm test
```
### Step 3: READ
Read the complete output and exit codes:
```bash
# Check output carefully
# Don't skim - read every line
# Note exit code (0 = success)
```
### Step 4: VERIFY
Confirm the output matches your claim:
```markdown
Claim: "All tests pass"
Output shows: "42 passing, 0 failing"
Verification: ✓ Claim is accurate
```
### Step 5: CLAIM
Only now make the claim, with evidence:
```markdown
✓ All tests pass (42 passing, verified at 2024-01-15 14:30)
```
---
## Required Validations by Category
### Testing
```bash
# Run test command
npm test
# Verify in output:
# - Zero failures
# - Expected test count
# - No skipped tests (unless intentional)
```
**Not valid**: "Tests should pass" without running them
### Linting
```bash
# Run linter completely
npm run lint
# Verify in output:
# - Zero errors
# - Zero warnings (or acceptable known warnings)
```
**Not valid**: Using lint as proxy for build success
### Building
```bash
# Run build command
npm run build
# Verify:
# - Exit code 0
# - Build artifacts created
# - No errors in output
```
**Not valid**: Assuming lint passing means build passes
### Bug Fixes
```bash
# Step 1: Reproduce original bug
npm test -- --grep "failing test"
# Should fail
# Step 2: Apply fix
# Step 3: Verify fix works
npm test -- --grep "failing test"
# Should pass
```
**Not valid**: Claiming fix works without reproducing original failure
### Regression Tests
Complete red-green cycle required:
```bash
# 1. Write test, run it
npm test # Should PASS with new test
# 2. Revert the fix
git stash
# 3. Run test again
npm test # Should FAIL (proves test catches the bug)
# 4. Restore fix
git stash pop
# 5. Run test again
npm test # Should PASS
```
### Requirements Verification
```markdown
## Original Requirements
1. User can login with email
2. User can reset password
3. Session expires after 24 hours
## Verification Checklist
- [x] Requirement 1: Tested login flow manually + unit tests
- [x] Requirement 2: Tested reset flow manually + integration test
- [x] Requirement 3: Verified SESSION_TIMEOUT=86400 in config + test
```
### Agent Work Verification
Don't trust agent reports blindly:
```bash
# Agent claims: "Fixed the bug in user.ts"
# Verify independently:
git diff src/user.ts # Check actual changes
npm test # Verify tests pass
```
---
## Forbidden Language
Never use these phrases without verification:
| Forbidden | Why |
|-----------|-----|
| "should work" | Implies uncertainty |
| "probably fixed" | Not verified |
| "seems to pass" | Didn't read output |
| "I think it's done" | Guessing |
| "Great!" (before checking) | Premature celebration |
| "Done!" (before verification) | Unverified claim |
### Replace With
| Instead Say | After |
|-------------|-------|
| "Tests pass" | Running tests, seeing 0 failures |
| "Build succeeds" | Running build, exit code 0 |
| "Bug is fixed" | Reproducing bug, verifying fix |
---
## Anti-Patterns
### Partial Verification
```markdown
BAD: "I ran one test and it passed"
GOOD: "Full test suite passes (42/42)"
```
### Relying on Prior Runs
```markdown
BAD: "Tests passed earlier"
GOOD: "Tests pass now (just ran)"
```
### Skipping Verification
```markdown
BAD: "This is a small change, no need to verify"
GOOD: "Small change, but verified: tests pass, lint clean"
```
### Trusting Without Checking
```markdown
BAD: Agent said it's fixed, so it's fixed
GOOD: Agent said it's fixed, I verified by running tests
```
---
## Verification Checklist Template
Use before claiming completion:
```markdown
## Task: [Task Name]
### Verification Steps
- [ ] Tests run: `npm test`
- Result: [X passing, Y failing]
- [ ] Lint passes: `npm run lint`
- Result: [No errors]
- [ ] Build succeeds: `npm run build`
- Result: [Exit code 0]
- [ ] Requirements met:
- [ ] Requirement 1: [How verified]
- [ ] Requirement 2: [How verified]
### Evidence
[Paste relevant output or screenshots]
### Conclusion
✓ Task complete, all verifications passed
```
---
@@ -0,0 +1,277 @@
# Writing Plans
## Description
Generate comprehensive implementation plans with bite-sized tasks for engineers with minimal codebase familiarity. This skill bridges design completion and engineering execution with detailed, actionable steps.
## When to Use
- After brainstorming/design is complete
- Before starting implementation
- When handing off work to another developer
- For complex features requiring structured approach
---
## Plan Document Format
### Header Section
```markdown
# Plan: [Feature Name]
**Required Skill**: executing-plans
## Goal
[One sentence describing what will be built]
## Architecture Overview
[2-3 sentences describing the approach]
## Tech Stack
- [Technology 1]
- [Technology 2]
```
### Task Structure
Each numbered task contains:
```markdown
## Task [N]: [Task Name]
**Files**:
- Create: `path/to/new-file.ts`
- Modify: `path/to/existing-file.ts`
- Test: `path/to/test-file.test.ts`
**Steps**:
1. Write failing test
```typescript
// Exact test code
```
2. Verify test fails
```bash
npm test -- --grep "test name"
# Expected: 1 failing
```
3. Implement minimally
```typescript
// Exact implementation code
```
4. Verify test passes
```bash
npm test -- --grep "test name"
# Expected: 1 passing
```
5. Commit
```bash
git add .
git commit -m "feat: add [feature]"
```
```
---
## Task Granularity
### Bite-Sized Principle
Each task should be **2-5 minutes** of focused work:
- Write one test
- Implement one function
- Add one validation
### Why Small Tasks?
- Easier to verify correctness
- Natural commit points
- Reduces context switching
- Enables parallel work
- Clearer progress tracking
### Bad vs Good Task Breakdown
```
BAD: "Implement user authentication"
GOOD:
- Task 1: Create User model with email field
- Task 2: Add password hashing to User model
- Task 3: Create login endpoint
- Task 4: Add JWT token generation
- Task 5: Create auth middleware
- Task 6: Add token refresh endpoint
```
---
## Core Requirements
### Exact File Paths Always
Never use vague references:
```
BAD: "Update the user service"
GOOD: "Modify `src/services/user-service.ts`"
```
### Complete Code Samples
Include exact code, not descriptions:
```
BAD: "Add a function that validates email"
GOOD:
```typescript
export function validateEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
```
```
### Expected Output Specifications
Always specify expected command results:
```bash
npm test
# Expected output:
# PASS src/services/user.test.ts
# User validation
# ✓ validates correct email format (3ms)
# ✓ rejects invalid email format (1ms)
# 2 passing
```
---
## Guiding Principles
### DRY (Don't Repeat Yourself)
- Identify patterns before implementation
- Plan for reusable components
- Note shared utilities needed
### YAGNI (You Aren't Gonna Need It)
- Only plan what's required now
- Remove speculative features
- Add complexity when justified
### TDD (Test-Driven Development)
Every task follows:
1. Write failing test
2. Verify it fails
3. Implement minimally
4. Verify it passes
5. Refactor if needed
6. Commit
### Frequent Commits
- Commit after each task
- Clear, descriptive messages
- Atomic changes only
---
## Execution Handoff
After plan is complete, offer two implementation pathways:
### Option 1: Subagent-Driven (Current Session)
```
Use the `executing-plans` skill for automated execution with:
- Fresh agent per task
- Code review between tasks
- Quality gates
```
### Option 2: Parallel Session (Separate Worktree)
```
Developer executes in separate environment:
- Read plan file
- Follow tasks sequentially
- Commit after each task
```
---
## Example Plan Snippet
```markdown
# Plan: Add Email Verification
**Required Skill**: executing-plans
## Goal
Add email verification to user registration flow.
## Architecture Overview
Send verification email on registration, validate token on click,
mark user as verified in database.
## Tech Stack
- Node.js, TypeScript
- PostgreSQL
- SendGrid for email
---
## Task 1: Add verified flag to User model
**Files**:
- Modify: `src/models/user.ts`
- Create: `src/migrations/add-verified-flag.ts`
- Test: `src/models/user.test.ts`
**Steps**:
1. Write failing test
```typescript
describe('User model', () => {
it('should have verified flag defaulting to false', () => {
const user = new User({ email: 'test@example.com' });
expect(user.verified).toBe(false);
});
});
```
2. Verify test fails
```bash
npm test -- --grep "verified flag"
# Expected: 1 failing (verified is undefined)
```
3. Add verified field to User model
```typescript
// src/models/user.ts
export class User {
email: string;
verified: boolean = false; // Add this line
// ...
}
```
4. Verify test passes
```bash
npm test -- --grep "verified flag"
# Expected: 1 passing
```
5. Commit
```bash
git add src/models/user.ts src/models/user.test.ts
git commit -m "feat(user): add verified flag with false default"
```
```
---
+27 -2
View File
@@ -5,8 +5,9 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
## Features
- **20 Specialized Agents** - From planning to deployment
- **20+ Slash Commands** - Workflow automation
- **15+ Skills** - Framework and language expertise
- **22+ Slash Commands** - Workflow automation
- **28+ Skills** - Framework, language, and methodology expertise
- **13 Methodology Skills** - Superpowers development workflow
- **CI/CD, Security, and API Extensions** - Extended capabilities
## Quick Start
@@ -78,6 +79,9 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
### Documentation & Planning
```bash
/plan [task] # Create implementation plan
/plan --detailed [task] # Detailed plan (2-5 min tasks)
/brainstorm [topic] # Interactive design session
/execute-plan [file] # Subagent-driven execution
/doc [target] # Generate documentation
/research [topic] # Research technology
```
@@ -113,6 +117,21 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
### Testing
- pytest, vitest
### Methodology (Superpowers)
| Category | Skills |
|----------|--------|
| **Planning** | brainstorming, writing-plans, executing-plans |
| **Testing** | test-driven-development, verification-before-completion, testing-anti-patterns |
| **Debugging** | systematic-debugging, root-cause-tracing, defense-in-depth |
| **Collaboration** | dispatching-parallel-agents, requesting-code-review, receiving-code-review, finishing-development-branch |
Key methodology principles:
- **TDD Strict**: No production code without failing test first
- **Verification**: Evidence-based completion claims
- **Quality Gates**: Code review between every task
- **Bite-sized Tasks**: 2-5 minute increments with exact code
## Customization
### CLAUDE.md
@@ -188,6 +207,12 @@ Your patterns and examples here.
/ship → code-reviewer → tester → security-scan → git-manager
```
### Superpowers Workflow (Detailed)
```
/brainstorm → /plan --detailed → /execute-plan → /ship
```
Uses one-question-at-a-time design, 2-5 min tasks with exact code, subagent execution with code review gates.
## Requirements
- Claude Code 1.0+