diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index fb7a7d0..5b0d99a 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -6,38 +6,20 @@ This is a comprehensive Claude Kit for Claude Code, designed to accelerate devel ## Quick Reference -### Core Commands +### Key Skills (auto-triggered) -| Command | Description | -|---------|-------------| -| `/feature [desc]` | Full feature development workflow | -| `/fix [error]` | Smart debugging and bug fix | -| `/review [file]` | Comprehensive code review | -| `/test [scope]` | Generate tests | -| `/ship [msg]` | Commit + PR automation | -| `/plan [task]` | Task decomposition | -| `/doc [target]` | Documentation generation | -| `/deploy [env]` | Deployment workflow | - -### Enhanced Commands - -| Command | Description | -|---------|-------------| -| `/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 | -| `/research [topic]` | Technology research | - -### New Commands - -| Command | Description | -|---------|-------------| -| `/mode [name]` | Switch behavioral mode | -| `/index` | Generate project structure index | -| `/load [component]` | Load project context | -| `/checkpoint [action]` | Save/restore session state | -| `/spawn [task]` | Launch parallel background task | +| Skill | Triggers on | +|-------|------------| +| `feature-workflow` | "feature", "implement", "build", "add functionality" | +| `systematic-debugging` | "bug", "error", "failing", "broken", stack traces | +| `git-workflows` | "commit", "PR", "ship", "changelog" | +| `writing-plans` | "plan", "break down", "implementation steps" | +| `brainstorming` | "brainstorm", "design", "explore", "trade-offs" | +| `documentation` | "document", "docstring", "README", "API docs" | +| `refactoring` | "refactor", "clean up", "extract", "simplify" | +| `performance-optimization` | "slow", "performance", "profiling", "N+1" | +| `mode-switching` | "mode", "switch mode", "token-efficient" | +| `session-management` | "checkpoint", "index", "load context", "status" | ## Tech Stack @@ -184,96 +166,36 @@ Modes adjust communication style, output format, and problem-solving approach. ### Mode Activation -```bash -/mode brainstorm # Switch mode for session -/feature --mode=implementation # Override for single command -``` +Ask Claude to switch modes naturally: +- "switch to brainstorm mode" → creative exploration +- "use implementation mode" → code-focused, minimal prose +- "switch to token-efficient mode" → compressed output (30-70% savings) Mode files: `.claude/modes/` -## Command Flags - - - -All commands support combinable flags for flexible customization. - -### Universal Flags - -| Flag | Description | Values | -|------|-------------|--------| -| `--mode=[mode]` | Behavioral mode | default, brainstorm, token-efficient, etc. | -| `--depth=[1-5]` | Thoroughness level | 1=quick, 5=exhaustive | -| `--format=[fmt]` | Output format | concise, detailed, json | -| `--save=[path]` | Save output to file | File path | -| `--checkpoint` | Create state checkpoint | Boolean | - -### Persona Flags - -| Flag | Description | -|------|-------------| -| `--persona=security` | Security-focused analysis | -| `--persona=performance` | Performance-focused analysis | -| `--persona=architecture` | Architecture-focused analysis | - -### Examples - -```bash -/review --persona=security --depth=5 src/auth/ -/plan --mode=brainstorm --save=plans/design.md "feature" -/fix --format=concise "error message" -``` - ## Token Optimization Control output verbosity for cost optimization. -| Level | Flag | Savings | Description | -|-------|------|---------|-------------| +| Level | Activation | Savings | Description | +|-------|-----------|---------|-------------| | Standard | (default) | 0% | Full explanations | -| Concise | `--format=concise` | 30-40% | Reduced explanations | -| Ultra | `--format=ultra` | 60-70% | Code-only responses | - -### Session-Wide Optimization - -```bash -/mode token-efficient # Enable for entire session -``` +| Concise | "be concise" | 30-40% | Reduced explanations | +| Ultra | "code only" | 60-70% | Code-only responses | +| Session | "switch to token-efficient mode" | 30-70% | Compressed for session | Reference: `.claude/skills/writing-concisely/SKILL.md` ## Context Management -### Project Indexing +These features are provided by the `session-management` skill: -Generate and use project structure index for faster navigation: - -```bash -/index # Generate PROJECT_INDEX.md -/load api # Load API context -/load --all # Load full project context -``` - -### Session Checkpoints - -Save and restore conversation state: - -```bash -/checkpoint save "feature-x" # Save current state -/checkpoint list # List checkpoints -/checkpoint restore "feature-x" # Restore state -``` - -### Parallel Tasks - -Launch background tasks for concurrent work: - -```bash -/spawn "research auth patterns" -/spawn --list # Check status -/spawn --collect # Gather results -``` +- **Project Indexing** — "generate a project index" → scans and creates PROJECT_INDEX.md +- **Context Loading** — "load the API context" → reads relevant files into context +- **Checkpoints** — "save checkpoint feature-x" → git stash + metadata for session recovery +- **Status** — "what's the project status?" → git state, tasks, recent commits ## MCP Integrations @@ -304,7 +226,7 @@ Settings to control the integrated superpowers development methodology. | `standard` | 15-60 min | Quick planning, experienced team | | `detailed` | 2-5 min | Thorough plans with exact code | -To use detailed mode: `/plan --detailed [task]` +To use detailed mode: "plan this in detail" or "break this into 2-5 min tasks" ### Brainstorming Style @@ -313,7 +235,7 @@ To use detailed mode: `/plan --detailed [task]` | `standard` | All questions at once | | `interactive` | One question per message with validation | -To use interactive mode: `/brainstorm [topic]` +To use interactive mode: "let's brainstorm [topic]" ### Execution Mode @@ -322,12 +244,12 @@ To use interactive mode: `/brainstorm [topic]` | `manual` | Developer executes tasks from plan | | `subagent` | Automated execution with code review gates | -To use subagent mode: `/execute-plan [plan-file]` +To use subagent mode: "execute the plan" or "run the plan with subagents" ### TDD Strictness For strict TDD enforcement (no production code without failing test): -- Use `/tdd [feature]` command +- Auto-triggers on implementation tasks - Reference: `.claude/skills/test-driven-development/SKILL.md` ### Verification Requirements @@ -347,8 +269,10 @@ Enable mandatory verification before completion claims: | **Security** | owasp | | **API** | openapi | | **Testing** | testing (pytest, vitest, Jest), playwright | -| **Optimization** | writing-concisely | +| **Optimization** | writing-concisely, performance-optimization | | **Developer Patterns** | error-handling, state-management, logging, caching, api-client, authentication, background-jobs | +| **Workflows** | feature-workflow, git-workflows, documentation, refactoring | +| **Session** | mode-switching, session-management | | **Methodology - Planning** | brainstorming, writing-plans, executing-plans, writing-skills | | **Methodology - Testing** | test-driven-development, verification-before-completion, testing-anti-patterns | | **Methodology - Debugging** | systematic-debugging, root-cause-tracing, defense-in-depth | @@ -369,7 +293,7 @@ Each skill includes: For complex problems requiring step-by-step analysis: - Reference: `.claude/skills/sequential-thinking/SKILL.md` -- Activation: `/research --sequential [topic]` or use deep-research mode +- Activation: auto-triggers on complex reasoning tasks, or use deep-research mode ## Environment Configuration @@ -458,7 +382,6 @@ pnpm install - **Claude Kit Version**: 3.0.0 - **Last Updated**: 2026-04-18 - **Compatible with**: Claude Code 1.0+ -- **Total Skills**: 36 (with YAML frontmatter, bundled resources) -- **Total Commands**: 27+ +- **Total Skills**: 43 (with YAML frontmatter, bundled resources) - **Total Agents**: 20 - **Behavioral Modes**: 7 diff --git a/.claude/commands/api-gen.md b/.claude/commands/api-gen.md deleted file mode 100644 index 47a6b4c..0000000 --- a/.claude/commands/api-gen.md +++ /dev/null @@ -1,55 +0,0 @@ -# /api-gen - API Generation Command - -## Purpose - -Generate API endpoints, documentation, or client code from specifications. - -## Usage - -``` -/api-gen [resource name or OpenAPI spec path] -``` - ---- - -Generate API for: **$ARGUMENTS** - -## Workflow - -### Step 1: Define Resource - -1. Identify resource properties -2. Define relationships -3. Determine operations - -### Step 2: Generate - -1. Create model/schema -2. Create routes/endpoints -3. Add validation -4. Generate tests - -### Step 3: Document - -1. Create OpenAPI spec -2. Add examples -3. Document errors - -## Output - -```markdown -## API Generated - -### Endpoints -| Method | Path | Description | -|--------|------|-------------| -| GET | /resources | List all | -| POST | /resources | Create | -| GET | /resources/:id | Get one | - -### Files Created -- `src/models/resource.ts` -- `src/routes/resource.ts` -- `tests/resource.test.ts` -- `docs/api/resource.md` -``` diff --git a/.claude/commands/brainstorm.md b/.claude/commands/brainstorm.md deleted file mode 100644 index 24fdd38..0000000 --- a/.claude/commands/brainstorm.md +++ /dev/null @@ -1,219 +0,0 @@ -# /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/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 - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=brainstorm` | -| `--depth=[1-5]` | Exploration depth level | `--depth=4` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=detailed` | -| `--save=[path]` | Save design document to file | `--save=docs/design.md` | -| `--quick` | Shorter session, fewer questions | `--quick` | -| `--comprehensive` | Longer session, thorough exploration | `--comprehensive` | - -### Flag Usage Examples - -```bash -/brainstorm --comprehensive "authentication system design" -/brainstorm --save=docs/payment-design.md "payment integration" -/brainstorm --quick "simple file upload feature" -/brainstorm --depth=5 "microservices architecture" -``` - -### Session Depth - -| Level | Questions | Exploration | -|-------|-----------|-------------| -| 1 | 2-3 | Quick validation only | -| 2 | 4-5 | Standard session | -| 3 | 6-8 | Thorough exploration | -| 4 | 8-10 | Comprehensive | -| 5 | 10+ | Exhaustive, all angles | - -## MCP Integration - -This command leverages MCP servers for enhanced brainstorming: - -### Sequential Thinking - Structured Exploration (Primary) -``` -ALWAYS use Sequential Thinking for brainstorming: -- Explore design options systematically -- Track pros/cons for each approach -- Revise conclusions based on user feedback -- Build confidence in final design incrementally -``` - -### Memory - Design Persistence -``` -Store design decisions for continuity: -- Create entities for design concepts -- Store user preferences and constraints -- Recall previous design patterns -- Build knowledge graph of architecture decisions -``` - -### Context7 - Technology Options -``` -When exploring technology choices: -- Fetch current documentation for options -- Compare library capabilities accurately -- Understand trade-offs with real data -``` - -## 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. diff --git a/.claude/commands/changelog.md b/.claude/commands/changelog.md deleted file mode 100644 index fcdb95e..0000000 --- a/.claude/commands/changelog.md +++ /dev/null @@ -1,47 +0,0 @@ -# /changelog - Changelog Command - -## Purpose - -Generate changelog entries from recent commits. - -## Usage - -``` -/changelog [version or 'since:tag'] -``` - ---- - -Generate changelog for: **$ARGUMENTS** - -## Workflow - -1. **Analyze Commits** - ```bash - git log --oneline --since="last tag" - ``` - -2. **Categorize** - - Added - - Changed - - Fixed - - Removed - -3. **Generate** - - User-friendly descriptions - - Link to PRs/issues - -## Output - -```markdown -## [Version] - Date - -### Added -- Feature description (#123) - -### Changed -- Improvement description (#124) - -### Fixed -- Bug fix description (#125) -``` diff --git a/.claude/commands/checkpoint.md b/.claude/commands/checkpoint.md deleted file mode 100644 index e9ea41d..0000000 --- a/.claude/commands/checkpoint.md +++ /dev/null @@ -1,134 +0,0 @@ -# /checkpoint - -## Purpose - -Save and restore conversation context using git-based checkpoints. Enables session recovery and state preservation for complex, multi-session work. - ---- - -Manage checkpoints for the current work session. - -## Checkpoint Operations - -### Save Checkpoint - -Create a checkpoint of current state: - -```bash -/checkpoint save [name] -``` - -**Process:** -1. Create git stash with descriptive message -2. Record current context (files being worked on, task state) -3. Save checkpoint metadata to `.claude/checkpoints/[name].json` - -**Metadata Format:** -```json -{ - "name": "feature-auth", - "created": "2024-01-15T14:30:00Z", - "git_stash": "stash@{0}", - "files_in_context": ["src/auth/login.ts", "src/auth/token.ts"], - "current_task": "Implementing JWT refresh", - "notes": "User-provided notes" -} -``` - -### List Checkpoints - -Show available checkpoints: - -```bash -/checkpoint list -``` - -**Output:** -```markdown -## Available Checkpoints - -| Name | Created | Task | Stash | -|------|---------|------|-------| -| feature-auth | 2h ago | JWT refresh | stash@{0} | -| bugfix-login | 1d ago | Login timeout | stash@{1} | -``` - -### Restore Checkpoint - -Restore a previous checkpoint: - -```bash -/checkpoint restore [name] -``` - -**Process:** -1. Apply git stash -2. Load checkpoint metadata -3. Summarize restored context -4. Ready to continue work - -### Delete Checkpoint - -Remove a checkpoint: - -```bash -/checkpoint delete [name] -``` - -## Flags - -| Flag | Description | -|------|-------------| -| `--notes="[text]"` | Add notes to checkpoint | -| `--force` | Overwrite existing checkpoint | -| `--include-uncommitted` | Include uncommitted changes | -| `--dry-run` | Show what would be saved | - -## Usage Examples - -```bash -/checkpoint save auth-progress # Save current state -/checkpoint save auth --notes="WIP tokens" # Save with notes -/checkpoint list # Show checkpoints -/checkpoint restore auth-progress # Restore state -/checkpoint delete old-checkpoint # Remove checkpoint -``` - -## Arguments - -$ARGUMENTS - -Parse the operation (save/list/restore/delete) and checkpoint name. - ---- - -## Auto-Checkpoint - -For complex tasks, checkpoints are automatically suggested: -- Before major refactoring -- When switching contexts -- Before risky operations -- At natural breakpoints - -## Best Practices - -1. **Name Descriptively**: Use task-related names -2. **Add Notes**: Future you will thank present you -3. **Checkpoint Often**: Before context switches -4. **Clean Up**: Delete obsolete checkpoints - -## Recovery Workflow - -When resuming work: -``` -1. /checkpoint list # See available states -2. /checkpoint restore [name] # Restore context -3. Continue where you left off # Context is loaded -``` - -## Limitations - -- Checkpoints use git stash (requires git repo) -- Large uncommitted changes may be slow -- Metadata stored in `.claude/checkpoints/` -- Consider committing before checkpointing for safety diff --git a/.claude/commands/commit.md b/.claude/commands/commit.md deleted file mode 100644 index 0dae47b..0000000 --- a/.claude/commands/commit.md +++ /dev/null @@ -1,219 +0,0 @@ -# /commit - Smart Commit Command - -## Purpose - -Create a well-formatted commit with auto-generated message based on staged changes. - -## Usage - -``` -/commit [optional message hint] -``` - -## Arguments - -- `$ARGUMENTS`: Optional hint for commit message focus (e.g., "auth", "bugfix", "refactor") - ---- - -Create a commit for staged changes with hint: **$ARGUMENTS** - -## Workflow - -### Step 1: Analyze Changes - -1. **Check Status** - ```bash - git status - ``` - -2. **View Staged Changes** - ```bash - git diff --staged - ``` - -3. **Review Recent Commits** - ```bash - git log --oneline -5 - ``` - -### Step 2: Categorize Changes - -Determine commit type: -- `feat`: New feature -- `fix`: Bug fix -- `docs`: Documentation -- `style`: Formatting -- `refactor`: Code restructuring -- `test`: Adding tests -- `chore`: Maintenance - -### Step 3: Generate Message - -Follow conventional commit format: -``` -type(scope): subject - -body (optional) - -footer (optional) -``` - -### Step 4: Create Commit - -```bash -git commit -m "$(cat <<'EOF' -type(scope): subject - -- Change 1 -- Change 2 - -🤖 Generated with [Claude Code](https://claude.com/claude-code) - -Co-Authored-By: Claude -EOF -)" -``` - -## Commit Message Guidelines - -### Subject Line -- Max 50 characters -- Imperative mood ("Add" not "Added") -- No period at end -- Capitalize first letter - -### Body -- Wrap at 72 characters -- Explain what and why -- Use bullet points for multiple changes - -### Examples - -#### Feature -``` -feat(auth): add password reset functionality - -- Add reset token generation -- Implement email sending -- Add rate limiting for reset requests - -Closes #123 -``` - -#### Bug Fix -``` -fix(api): handle null user in profile endpoint - -The profile endpoint crashed when accessing deleted users. -Added null check and proper 404 response. - -Fixes #456 -``` - -#### Refactor -``` -refactor(database): extract query builders - -Split large database service into focused modules -for better maintainability and testing. -``` - -#### Documentation -``` -docs(readme): update installation instructions - -- Add prerequisites section -- Update configuration examples -- Fix broken links -``` - -#### Test -``` -test(auth): add missing login tests - -- Add test for invalid credentials -- Add test for locked account -- Add test for expired session -``` - -#### Chore -``` -chore(deps): update dependencies - -- Update React to 18.2 -- Update TypeScript to 5.3 -- Remove unused packages -``` - -## Output - -### Commit Created - -```markdown -## Commit Created - -**Hash**: `abc1234` -**Branch**: `feature/auth-improvements` - -### Message -``` -feat(auth): add OAuth2 login support - -- Implement Google OAuth provider -- Implement GitHub OAuth provider -- Add session token generation -- Update user model for OAuth data - -Closes #789 -``` - -### Files Changed -| Status | File | -|--------|------| -| M | src/auth/providers.ts | -| A | src/auth/oauth/google.ts | -| A | src/auth/oauth/github.ts | -| M | src/models/user.ts | -| A | tests/auth/oauth.test.ts | - -### Stats -- 5 files changed -- 234 insertions(+) -- 12 deletions(-) - -### Next Steps -```bash -# Push to remote -git push -u origin feature/auth-improvements - -# Create PR -gh pr create -``` -``` - -## Pre-Commit Checks - -Before committing: -- [ ] No secrets in staged files -- [ ] No debug statements -- [ ] No TODO comments (unless intentional) -- [ ] Code is formatted - -## Amending Commits - -If pre-commit hooks modify files: -```bash -# Stage modified files and amend -git add -A -git commit --amend --no-edit -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Commit message format -- Required sections -- Issue reference format -- Co-author settings diff --git a/.claude/commands/debug.md b/.claude/commands/debug.md deleted file mode 100644 index 56d5568..0000000 --- a/.claude/commands/debug.md +++ /dev/null @@ -1,53 +0,0 @@ -# /debug - Debug Command - -## Purpose - -Analyze and debug an error, exception, or unexpected behavior. - -## Usage - -``` -/debug [error message or description] -``` - ---- - -Debug issue: **$ARGUMENTS** - -## Workflow - -### Step 1: Analyze Error - -1. Parse error message and stack trace -2. Identify error location -3. Understand error type - -### Step 2: Investigate - -1. Trace execution path -2. Check related code -3. Form hypotheses - -### Step 3: Fix - -1. Implement minimal fix -2. Verify fix works -3. Add regression test - -## Output - -```markdown -## Debug Report - -### Error -[Error message] - -### Root Cause -[Explanation] - -### Fix -[Code changes] - -### Prevention -[Test added] -``` diff --git a/.claude/commands/deploy.md b/.claude/commands/deploy.md deleted file mode 100644 index 3b7f95e..0000000 --- a/.claude/commands/deploy.md +++ /dev/null @@ -1,72 +0,0 @@ -# /deploy - Deployment Command - -## Purpose - -Deploy the application to a specified environment with proper checks. - -## Usage - -``` -/deploy [environment: staging | production] -``` - ---- - -Deploy to: **$ARGUMENTS** - -## Workflow - -### Pre-Deploy Checks - -1. **Verify Build** - ```bash - pnpm build - ``` - -2. **Run Tests** - ```bash - pnpm test - ``` - -3. **Security Scan** - ```bash - npm audit --audit-level=high - ``` - -### Deploy - -1. **Staging** - ```bash - # Deploy to staging environment - ``` - -2. **Production** (requires confirmation) - ```bash - # Deploy to production environment - ``` - -### Post-Deploy - -1. **Verify Deployment** - - Health checks - - Smoke tests - -2. **Monitor** - - Check logs - - Watch metrics - -## Output - -```markdown -## Deployment Complete - -**Environment**: staging -**Version**: v1.2.3 -**URL**: https://staging.example.com - -### Checks -- [x] Build successful -- [x] Tests passing -- [x] Security scan clean -- [x] Health check passed -``` diff --git a/.claude/commands/doc.md b/.claude/commands/doc.md deleted file mode 100644 index 129856e..0000000 --- a/.claude/commands/doc.md +++ /dev/null @@ -1,243 +0,0 @@ -# /doc - Documentation Command - -## Purpose - -Generate or update documentation including API docs, README files, code comments, and technical specifications. - -## Usage - -``` -/doc [target | 'api' | 'readme' | 'changelog'] -``` - -## Arguments - -- `$ARGUMENTS`: - - File/function path: Document specific code - - `api`: Generate API documentation - - `readme`: Update README file - - `changelog`: Generate changelog from commits - ---- - -Generate documentation for: **$ARGUMENTS** - -## Workflow - -### For Code Documentation - -1. **Analyze Code** - - Read the code thoroughly - - Understand purpose and behavior - - Identify inputs and outputs - - Note side effects - -2. **Generate Documentation** - - Add docstrings/JSDoc - - Include examples - - Document edge cases - - Add type annotations - -### For API Documentation - -1. **Find All Endpoints** - - Scan route definitions - - Identify HTTP methods - - Note authentication requirements - -2. **Document Each Endpoint** - - Request format - - Response format - - Error responses - - Examples - -### For README - -1. **Analyze Project** - - Purpose and features - - Installation steps - - Usage examples - - Configuration - -2. **Generate/Update** - - Clear structure - - Working examples - - Up-to-date info - -### For Changelog - -1. **Analyze Commits** - ```bash - git log --oneline --since="last release" - ``` - -2. **Categorize Changes** - - Added - - Changed - - Fixed - - Removed - -## Templates - -### Python Docstring -```python -def calculate_discount(price: float, percentage: float) -> float: - """ - Calculate discounted price. - - Args: - price: Original price in dollars. - percentage: Discount percentage (0-100). - - Returns: - The discounted price. - - Raises: - ValueError: If percentage is not between 0 and 100. - - Example: - >>> calculate_discount(100.0, 20) - 80.0 - """ -``` - -### TypeScript JSDoc -```typescript -/** - * Calculate discounted price. - * - * @param price - Original price in dollars - * @param percentage - Discount percentage (0-100) - * @returns The discounted price - * @throws {RangeError} If percentage is not between 0 and 100 - * - * @example - * calculateDiscount(100, 20); // returns 80 - */ -``` - -### API Endpoint -```markdown -## POST /api/orders - -Create a new order. - -### Authentication -Requires Bearer token. - -### Request Body -```json -{ - "items": [ - { "productId": "123", "quantity": 2 } - ], - "shippingAddress": { - "street": "123 Main St", - "city": "New York", - "zip": "10001" - } -} -``` - -### Response (201 Created) -```json -{ - "id": "order_456", - "status": "pending", - "total": 99.99, - "createdAt": "2024-01-15T10:00:00Z" -} -``` - -### Errors -| Status | Code | Description | -|--------|------|-------------| -| 400 | INVALID_ITEMS | Items array is empty | -| 401 | UNAUTHORIZED | Invalid or missing token | -| 422 | OUT_OF_STOCK | Item not available | -``` - -### README Section -```markdown -## Installation - -```bash -npm install my-package -``` - -## Quick Start - -```typescript -import { Client } from 'my-package'; - -const client = new Client({ apiKey: 'your-key' }); -const result = await client.fetch(); -``` - -## Configuration - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| `apiKey` | string | required | Your API key | -| `timeout` | number | 5000 | Request timeout in ms | -``` - -### Changelog Entry -```markdown -## [1.2.0] - 2024-01-15 - -### Added -- Password reset functionality (#123) -- Email verification for new accounts - -### Changed -- Improved error messages for validation failures -- Updated dependencies to latest versions - -### Fixed -- Race condition in session handling (#456) -- Incorrect timezone in date displays -``` - -## Output - -### Documentation Report - -```markdown -## Documentation Updated - -### Files Modified -- `src/services/auth.ts` - Added JSDoc comments -- `docs/api/auth.md` - New API documentation -- `README.md` - Updated configuration section - -### Documentation Added - -#### Code Comments -- `AuthService.login()` - Full JSDoc with examples -- `AuthService.logout()` - Parameter documentation -- `validateToken()` - Return type and exceptions - -#### API Documentation -- POST /api/auth/login -- POST /api/auth/logout -- POST /api/auth/refresh - -### Coverage -- Functions documented: 15/18 (83%) -- Endpoints documented: 12/12 (100%) - -### Next Steps -1. Add examples to remaining functions -2. Create getting started guide -3. Add architecture diagram -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Documentation format -- Required sections -- Example requirements -- API documentation tool diff --git a/.claude/commands/execute-plan.md b/.claude/commands/execute-plan.md deleted file mode 100644 index 0a42076..0000000 --- a/.claude/commands/execute-plan.md +++ /dev/null @@ -1,221 +0,0 @@ -# /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/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-a-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 diff --git a/.claude/commands/feature.md b/.claude/commands/feature.md deleted file mode 100644 index bfaa4b9..0000000 --- a/.claude/commands/feature.md +++ /dev/null @@ -1,251 +0,0 @@ -# /feature - Feature Development Workflow - -## Purpose - -End-to-end feature development workflow that orchestrates planning, implementation guidance, testing, and code review. - -## Usage - -``` -/feature [feature description or issue reference] -``` - -## Arguments - -- `$ARGUMENTS`: Feature description, issue number, or requirement specification - ---- - -Implement a complete feature development workflow for: **$ARGUMENTS** - -## Workflow - -### Phase 1: Planning - -First, analyze the feature request and create an implementation plan: - -1. **Understand Requirements** - - Parse the feature description thoroughly - - Identify acceptance criteria - - List assumptions that need validation - - Clarify any ambiguous requirements with the user - -2. **Explore Codebase** - - Find related existing implementations - - Identify patterns and conventions to follow - - Locate integration points - - Note dependencies - -3. **Create Task Breakdown** - - Decompose into atomic, verifiable tasks - - Order tasks by dependencies - - Include testing requirements - - Estimate complexity (S/M/L) - -4. **Use TodoWrite** to track all tasks - -### Phase 2: Research (If Needed) - -If the feature involves unfamiliar technology: - -1. Research best practices and patterns -2. Find examples in the codebase or documentation -3. Identify potential pitfalls -4. Document key decisions - -### Phase 3: Implementation Guidance - -For each implementation task: - -1. **Identify Target Files** - - Existing files to modify - - New files to create - - Tests to add/update - -2. **Provide Implementation Direction** - - Code structure recommendations - - Patterns to follow - - Edge cases to handle - - Error handling approach - -3. **Review Progress** - - Mark tasks complete as you go - - Identify blockers early - - Adjust plan if needed - -### Phase 4: Testing - -After implementation: - -1. **Generate Tests** - - Unit tests for new functions - - Integration tests for workflows - - Edge case coverage - -2. **Run Test Suite** - ```bash - # Python - pytest -v --cov=src - - # TypeScript - pnpm test - ``` - -3. **Verify Coverage** - - Ensure new code is tested - - Coverage should not decrease - -### Phase 5: Code Review - -Before completion: - -1. **Self-Review Checklist** - - [ ] Code follows project conventions - - [ ] No security vulnerabilities - - [ ] Error handling is complete - - [ ] Documentation updated - - [ ] Tests are passing - -2. **Review Staged Changes** - ```bash - git diff --staged - ``` - -3. **Address Any Issues** - - Fix critical issues immediately - - Note recommendations for future - -### Phase 6: Completion - -1. **Verify All Tasks Complete** - - All TodoWrite items done - - All tests passing - - Documentation updated - -2. **Prepare for Commit** - - Stage appropriate files - - Generate commit message - - Create PR if requested - -## Output - -### Deliverables - -1. **Implementation Plan** - Structured task breakdown -2. **Code Changes** - Feature implementation -3. **Tests** - Comprehensive test coverage -4. **Documentation** - Updated docs if needed -5. **Commit/PR** - Ready for merge - -### Summary Format - -```markdown -## Feature Implementation Complete - -### Feature -[Feature description] - -### Changes Made -- `path/to/file.ts` - [What was added/modified] -- `path/to/file.test.ts` - [Tests added] - -### Tests -- [x] Unit tests passing -- [x] Integration tests passing -- [x] Coverage: XX% - -### Documentation -- [x] Code comments added -- [x] README updated (if applicable) - -### Ready for Review -```bash -git status -git diff --staged -``` - -### Next Steps -1. Review changes -2. Run full test suite -3. Create PR -``` - -## Example - -**Input**: `/feature Add password reset functionality with email verification` - -**Output**: -1. Plan with 8 tasks covering model, service, routes, email, tests -2. Implementation of password reset flow -3. Tests for happy path and error cases -4. Updated API documentation -5. Commit message and PR description - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=implementation` | -| `--depth=[1-5]` | Planning thoroughness level | `--depth=3` | -| `--checkpoint` | Create checkpoint before starting | `--checkpoint` | -| `--skip-tests` | Skip test generation phase | `--skip-tests` | -| `--skip-review` | Skip code review phase | `--skip-review` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | - -### Flag Usage Examples - -```bash -/feature --mode=implementation "add user profile page" -/feature --depth=5 --checkpoint "implement payment flow" -/feature --format=concise "add logging utility" -``` - -## MCP Integration - -This command leverages MCP servers for enhanced capabilities: - -### Context7 - Library Documentation -When researching unfamiliar libraries or frameworks: -``` -Use Context7's resolve-library-id and get-library-docs tools to fetch -current documentation for any libraries involved in the feature. -``` - -### Sequential Thinking - Structured Planning -For complex feature breakdowns: -``` -Use Sequential Thinking's sequentialthinking tool for step-by-step -analysis when decomposing requirements or designing architecture. -``` - -### Memory - Context Persistence -Store and recall project context: -``` -- Store architectural decisions made during planning -- Recall user preferences from previous sessions -- Remember patterns used in similar features -``` - -### Filesystem - File Operations -For creating and modifying files: -``` -- Use directory_tree to understand project structure -- Use search_files to find related implementations -- Use read_file and write_file for file operations -``` - -### Playwright - E2E Testing -For features with UI components: -``` -Use Playwright for browser-based E2E testing of the implemented feature. -Validate user flows and interactions in real browser environment. -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Set minimum test coverage requirements -- Define required documentation updates -- Configure branch naming conventions -- Set PR template requirements diff --git a/.claude/commands/fix.md b/.claude/commands/fix.md deleted file mode 100644 index ecfa01a..0000000 --- a/.claude/commands/fix.md +++ /dev/null @@ -1,319 +0,0 @@ -# /fix - Bug Fix Workflow - -## Purpose - -Smart debugging and bug fixing workflow that analyzes errors, identifies root causes, implements fixes, and adds regression tests. - -## Usage - -``` -/fix [error message, bug description, or issue reference] -``` - -## Arguments - -- `$ARGUMENTS`: Error message, stack trace, bug description, or issue number - ---- - -Analyze and fix the following issue: **$ARGUMENTS** - -## Workflow - -### Phase 1: Error Analysis - -1. **Parse Error Information** - - Extract error type and message - - Parse stack trace if available - - Identify the failing location - -2. **Gather Context** - - When does this error occur? - - What triggers it? - - Is it reproducible? - - When did it start happening? - -3. **Check for Known Patterns** - - Common error patterns - - Similar issues in codebase - - Recent changes that might have caused it - -### Phase 2: Root Cause Investigation - -1. **Trace Execution** - - Follow the code path to the error - - Identify state at each step - - Find where expectations diverge - -2. **Form Hypotheses** - - List possible causes ranked by likelihood - - Identify minimal tests to validate each - -3. **Validate Hypothesis** - - Test the most likely cause first - - Confirm root cause before fixing - - Don't fix symptoms only - -### Phase 3: Search Related Code - -1. **Find Similar Code** - - Search for similar patterns - - Check if same bug exists elsewhere - - Identify shared code that might be affected - -2. **Review Recent Changes** - ```bash - git log --oneline -20 - git blame [file] - ``` - -### Phase 4: Implement Fix - -1. **Develop Minimal Fix** - - Fix the root cause, not symptoms - - Keep changes minimal and focused - - Consider edge cases - -2. **Add Defensive Code** (if appropriate) - - Input validation - - Null checks - - Error handling - -3. **Update Related Code** (if needed) - - Fix same issue in similar code - - Update shared utilities - -### Phase 5: Verification - -1. **Test the Fix** - - Verify original error is resolved - - Check related functionality - - Run existing test suite - -2. **Add Regression Test** - - Write test that would have caught this bug - - Include edge cases discovered - - Ensure test fails without fix - -3. **Run Full Test Suite** - ```bash - # Python - pytest -v - - # TypeScript - pnpm test - ``` - -### Phase 6: Documentation - -1. **Document the Fix** - - What was the issue - - What caused it - - How it was fixed - -2. **Update Comments** (if needed) - - Add clarifying comments - - Document non-obvious behavior - -## Output - -### Bug Fix Summary - -```markdown -## Bug Fix Complete - -### Issue -[Original error/bug description] - -### Root Cause -[Explanation of what caused the bug] - -### Location -`path/to/file.ts:42` - [function/method name] - -### Fix Applied - -**Before:** -```[language] -// Problematic code -``` - -**After:** -```[language] -// Fixed code -``` - -### Explanation -[Why this fix resolves the issue] - -### Regression Test Added -`path/to/test.ts` - `test_[scenario]` - -### Verification -- [x] Original error no longer occurs -- [x] Existing tests pass -- [x] New regression test passes -- [x] No new issues introduced - -### Related Areas Checked -- [x] `path/to/similar.ts` - No similar issue - -### Commands to Verify -```bash -pytest tests/test_file.py -v -# or -pnpm test path/to/file.test.ts -``` -``` - -## Common Fix Patterns - -### Null/Undefined Access - -```typescript -// Before -const name = user.profile.name; - -// After -const name = user?.profile?.name ?? 'Unknown'; -``` - -### Missing Error Handling - -```python -# Before -data = json.loads(response.text) - -# After -try: - data = json.loads(response.text) -except json.JSONDecodeError as e: - logger.error(f"Invalid JSON response: {e}") - raise InvalidResponseError("Failed to parse response") -``` - -### Race Condition - -```typescript -// Before -const data = await fetchData(); -setState(data); // May be unmounted - -// After -useEffect(() => { - let cancelled = false; - fetchData().then(data => { - if (!cancelled) setState(data); - }); - return () => { cancelled = true; }; -}, []); -``` - -### Off-by-One Error - -```python -# Before -for i in range(len(items) + 1): # IndexError - process(items[i]) - -# After -for i in range(len(items)): - process(items[i]) -# or -for item in items: - process(item) -``` - -## Example - -**Input**: `/fix TypeError: Cannot read property 'email' of undefined in UserService.ts:45` - -**Output**: -1. Analysis: User object is undefined when accessed -2. Root cause: async fetch didn't await, user not loaded yet -3. Fix: Add null check and proper async handling -4. Regression test: Test for case when user is not loaded - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=deep-research` | -| `--persona=[type]` | Apply persona expertise | `--persona=security` | -| `--depth=[1-5]` | Investigation thoroughness | `--depth=4` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | -| `--skip-regression` | Skip regression test creation | `--skip-regression` | -| `--checkpoint` | Create checkpoint before fixing | `--checkpoint` | - -### Flag Usage Examples - -```bash -/fix --mode=deep-research "intermittent timeout error" -/fix --persona=security "SQL injection vulnerability" -/fix --depth=5 "race condition in auth flow" -/fix --format=concise "typo in error message" -``` - -### Persona Options - -| Persona | Focus Area | -|---------|------------| -| `security` | Security vulnerabilities, OWASP | -| `performance` | Speed, memory, efficiency | -| `reliability` | Error handling, edge cases | - -## MCP Integration - -This command leverages MCP servers for enhanced debugging: - -### Sequential Thinking - Root Cause Analysis (Primary) -``` -ALWAYS use Sequential Thinking for debugging: -- Trace execution path step-by-step -- Form and test hypotheses systematically -- Track confidence in each potential cause -- Revise understanding as evidence emerges -``` - -### Memory - Bug Context -``` -Store and recall debugging context: -- Remember similar bugs from previous sessions -- Recall fix patterns that worked before -- Store root cause analysis for future reference -- Create relations between bugs and affected components -``` - -### Playwright - Browser Testing -``` -For UI/frontend bugs: -- Reproduce the bug in browser environment -- Test fix across different browsers -- Verify visual regressions are resolved -- Automate regression test for the fix -``` - -### Context7 - Library Issues -``` -When debugging library-related issues: -- Fetch current documentation for correct usage -- Check for known issues or breaking changes -- Find correct patterns and examples -``` - -### Filesystem - Code Search -``` -For tracing bug across codebase: -- Use search_files to find related code -- Use read_file to examine suspicious areas -- Track changes with file history -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Set required test coverage for fixes -- Define severity levels for bugs -- Configure error reporting format -- Set required review process diff --git a/.claude/commands/help.md b/.claude/commands/help.md deleted file mode 100644 index 8ab7b54..0000000 --- a/.claude/commands/help.md +++ /dev/null @@ -1,59 +0,0 @@ -# /help - Help Command - -## Purpose - -Display available commands and their usage. - -## Usage - -``` -/help [command name] -``` - ---- - -Show help for: **$ARGUMENTS** - -## Available Commands - -### Development Workflow -| Command | Description | -|---------|-------------| -| `/feature` | Full feature development workflow | -| `/fix` | Debug and fix bugs | -| `/review` | Code review | -| `/test` | Generate tests | -| `/tdd` | Test-driven development | -| `/refactor` | Improve code structure | - -### Git & Deployment -| Command | Description | -|---------|-------------| -| `/commit` | Create commit with message | -| `/ship` | Commit + PR workflow | -| `/pr` | Create pull request | -| `/deploy` | Deploy to environment | - -### Documentation -| Command | Description | -|---------|-------------| -| `/doc` | Generate documentation | -| `/plan` | Create implementation plan | - -### Security & Quality -| Command | Description | -|---------|-------------| -| `/security-scan` | Scan for vulnerabilities | -| `/api-gen` | Generate API code | - -## Getting Help - -For detailed help on a specific command: -``` -/help [command-name] -``` - -For general Claude Code help: -``` -/help -``` diff --git a/.claude/commands/index.md b/.claude/commands/index.md deleted file mode 100644 index d8763c8..0000000 --- a/.claude/commands/index.md +++ /dev/null @@ -1,144 +0,0 @@ -# /index - -## Purpose - -Generate a comprehensive project structure index for faster navigation and context loading. Creates a `PROJECT_INDEX.md` file mapping the codebase structure. - ---- - -Analyze the current project and generate a comprehensive index. - -## Index Generation - -### Step 1: Scan Project Structure - -Scan the entire project directory structure, excluding: -- `node_modules/` -- `.git/` -- `__pycache__/` -- `dist/`, `build/`, `.next/` -- `venv/`, `.venv/` -- Coverage and cache directories - -### Step 2: Identify Key Components - -Categorize files by type: -- **Entry Points**: Main files, index files, app entry -- **API/Routes**: Endpoint definitions -- **Models/Types**: Data structures, schemas -- **Services**: Business logic -- **Utilities**: Helper functions -- **Tests**: Test files -- **Configuration**: Config files, env templates -- **Documentation**: README, docs - -### Step 3: Map Dependencies - -Identify: -- Package managers and dependencies (package.json, requirements.txt, etc.) -- Internal import relationships between key files -- External service integrations - -### Step 4: Generate Index - -Create `PROJECT_INDEX.md` with this structure: - -```markdown -# Project Index: [Project Name] - -Generated: [timestamp] - -## Quick Navigation - -| Category | Key Files | -|----------|-----------| -| Entry Points | [list] | -| API Routes | [list] | -| Core Services | [list] | -| Models | [list] | - -## Directory Structure - -``` -[tree view] -``` - -## Key Files - -### Entry Points -- `[path]` - [description] - -### API/Routes -- `[path]` - [description] - -### Services -- `[path]` - [description] - -### Models/Types -- `[path]` - [description] - -## Dependencies - -### External -- [package]: [purpose] - -### Internal -- [module] → [depends on] - -## Architecture Notes -[Brief description of patterns observed] -``` - -## Flags - -| Flag | Description | -|------|-------------| -| `--depth=[N]` | Limit directory depth (default: 5) | -| `--include=[pattern]` | Include additional patterns | -| `--exclude=[pattern]` | Exclude additional patterns | -| `--output=[path]` | Custom output path | - -## Usage Examples - -```bash -/index # Standard index -/index --depth=3 # Shallow index -/index --include="*.graphql" # Include GraphQL files -/index --output=docs/INDEX.md # Custom output location -``` - -## Arguments - -$ARGUMENTS - -If no arguments provided, generate standard index with default settings. - ---- - -After generating the index, inform the user: -1. Index file location -2. Number of files indexed -3. Key components discovered -4. Suggest using `/load` to load specific components into context - -## MCP Integration - -This command leverages MCP servers for enhanced indexing: - -### Filesystem - Project Scanning (Primary) -``` -ALWAYS use Filesystem for project scanning: -- Use directory_tree for full structure view -- Use list_directory for targeted exploration -- Use search_files to find specific patterns -- Use get_file_info for file metadata -``` - -### Memory - Project Knowledge -``` -Store project structure in knowledge graph: -- Create entities for key modules -- Store component relationships -- Recall structure in future sessions -- Build project understanding over time -``` diff --git a/.claude/commands/load.md b/.claude/commands/load.md deleted file mode 100644 index 22e1548..0000000 --- a/.claude/commands/load.md +++ /dev/null @@ -1,108 +0,0 @@ -# /load - -## Purpose - -Load specific project components into context for focused work. Uses the project index to efficiently load relevant files. - ---- - -Load the requested component(s) into context. - -## Loading Process - -### Step 1: Check for Index - -First, check if `PROJECT_INDEX.md` exists: -- If exists: Use index for efficient loading -- If not: Suggest running `/index` first, or do quick scan - -### Step 2: Identify Component - -Parse the requested component: - -| Request Type | Action | -|--------------|--------| -| Category name | Load all files in category | -| File path | Load specific file | -| Pattern | Load matching files | -| `--all` | Load key files from all categories | - -### Step 3: Load Files - -Read the identified files and summarize: -- File purposes -- Key exports/functions -- Dependencies -- Current state - -### Step 4: Context Summary - -Provide a brief summary: -```markdown -## Loaded Context - -### Files Loaded (N) -- `path/to/file1.ts` - [purpose] -- `path/to/file2.ts` - [purpose] - -### Key Components -- [Component]: [description] - -### Ready For -- [Suggested actions based on loaded context] -``` - -## Component Categories - -| Category | What It Loads | -|----------|---------------| -| `api` | API routes and endpoints | -| `models` | Data models and types | -| `services` | Business logic services | -| `utils` | Utility functions | -| `tests` | Test files | -| `config` | Configuration files | -| `auth` | Authentication related | -| `db` | Database related | - -## Flags - -| Flag | Description | -|------|-------------| -| `--all` | Load all key components | -| `--shallow` | Load only file summaries | -| `--deep` | Load full file contents | -| `--related` | Include related files | - -## Usage Examples - -```bash -/load api # Load all API routes -/load models # Load all data models -/load src/services/user.ts # Load specific file -/load auth --related # Load auth + related files -/load --all # Load all key components -/load --all --shallow # Quick overview of everything -``` - -## Arguments - -$ARGUMENTS - -If no arguments, show available components from index. - ---- - -## Best Practices - -1. **Start Narrow**: Load specific components first -2. **Expand as Needed**: Use `--related` when you need more context -3. **Check Index**: Run `/index` if loading seems slow -4. **Use Categories**: Category names are faster than patterns - -## After Loading - -Suggest next actions: -- "Ready to work on [component]. What would you like to do?" -- "I see [patterns/issues]. Want me to address them?" -- "Related files that might be relevant: [list]" diff --git a/.claude/commands/mode.md b/.claude/commands/mode.md deleted file mode 100644 index ae790c2..0000000 --- a/.claude/commands/mode.md +++ /dev/null @@ -1,166 +0,0 @@ -# /mode - -## Purpose - -Switch between behavioral modes to optimize responses for different task types. Modes adjust communication style, output format, and problem-solving approach. - ---- - -Switch to the specified behavioral mode. - -## Available Modes - -| Mode | Description | Best For | -|------|-------------|----------| -| `default` | Balanced standard behavior | General tasks | -| `brainstorm` | Creative exploration, more questions | Design, ideation | -| `writing-concisely` | Compressed, concise output | High-volume, cost savings | -| `deep-research` | Thorough analysis, citations | Investigation, audits | -| `implementation` | Code-focused, minimal prose | Executing plans | -| `review` | Critical analysis, finding issues | Code review, QA | -| `orchestration` | Multi-task coordination | Complex parallel work | - -## Mode Switching - -### Activate Mode -```bash -/mode [mode-name] -``` - -### Check Current Mode -```bash -/mode -``` -(Shows current active mode) - -### Reset to Default -```bash -/mode default -``` - -## Mode Details - -### Default Mode -- Standard balanced responses -- Mix of explanation and code -- Normal verification steps - -### Brainstorm Mode -- Ask more clarifying questions -- Present multiple alternatives -- Explore trade-offs explicitly -- Delay convergence on solutions - -### Token-Efficient Mode -- Minimal explanations -- Code-only responses where possible -- Skip obvious context -- 30-70% token savings - -### Deep-Research Mode -- Thorough investigation -- Evidence and citations -- Confidence levels stated -- Comprehensive analysis - -### Implementation Mode -- Jump straight to code -- Progress indicators -- Minimal discussion -- Execute don't deliberate - -### Review Mode -- Look for issues first -- Categorized findings -- Severity levels -- Actionable feedback - -### Orchestration Mode -- Task breakdown -- Parallel execution planning -- Result aggregation -- Coordination focus - -## Flags - -| Flag | Description | -|------|-------------| -| `--info` | Show detailed mode description | -| `--list` | List all available modes | - -## Usage Examples - -```bash -/mode brainstorm # Switch to brainstorm mode -/mode token-efficient # Switch to efficient mode -/mode # Show current mode -/mode --list # List all modes -/mode default # Reset to default -``` - -## Arguments - -$ARGUMENTS - -If mode name provided: switch to that mode -If no arguments: show current mode -If `--list`: show all modes - ---- - -## Mode Persistence - -- Modes persist for the session -- Explicitly switch when task type changes -- Mode affects all subsequent responses -- Can be overridden per-command with flags - -## Command Flag Override - -Override mode for single command: -```bash -/feature --mode=implementation [desc] -/review --mode=deep-research [file] -/plan --mode=brainstorm [task] -``` - -## Recommended Workflows - -### Feature Development -``` -/mode brainstorm # Explore approaches -[discuss design] -/mode implementation # Execute plan -[write code] -/mode review # Check quality -[review code] -``` - -### Bug Investigation -``` -/mode deep-research # Investigate thoroughly -[analyze bug] -/mode implementation # Apply fix -[fix bug] -/mode default # Return to normal -``` - -### Cost-Conscious Session -``` -/mode token-efficient # Set for session -[work on multiple tasks] -/mode default # Reset when done -``` - -## Mode Files - -Mode definitions are in `.claude/modes/`: -- `default.md` -- `brainstorm.md` -- `token-efficient.md` -- `deep-research.md` -- `implementation.md` -- `review.md` -- `orchestration.md` - -Customize modes by editing these files. diff --git a/.claude/commands/optimize.md b/.claude/commands/optimize.md deleted file mode 100644 index 8536e5a..0000000 --- a/.claude/commands/optimize.md +++ /dev/null @@ -1,49 +0,0 @@ -# /optimize - Performance Optimization Command - -## Purpose - -Analyze and optimize code performance. - -## Usage - -``` -/optimize [file or function] -``` - ---- - -Optimize: **$ARGUMENTS** - -## Workflow - -1. **Analyze Current Performance** - - Identify bottlenecks - - Check complexity - - Profile if possible - -2. **Identify Opportunities** - - Algorithm improvements - - Caching opportunities - - Async optimizations - -3. **Implement Optimizations** - - Make targeted changes - - Verify improvements - - Ensure correctness - -## Output - -```markdown -## Optimization Report - -### Before -- Time complexity: O(n²) -- Estimated time: 500ms - -### After -- Time complexity: O(n log n) -- Estimated time: 50ms - -### Changes Made -- [Description of optimizations] -``` diff --git a/.claude/commands/plan.md b/.claude/commands/plan.md deleted file mode 100644 index f4de36b..0000000 --- a/.claude/commands/plan.md +++ /dev/null @@ -1,333 +0,0 @@ -# /plan - Task Planning Command - -## Purpose - -Create structured implementation plans with task breakdown, dependencies, and time estimates for complex work. - -## Usage - -``` -/plan [task description or feature request] -``` - -## Arguments - -- `$ARGUMENTS`: Description of the task, feature, or work to plan - ---- - -Create a detailed implementation plan for: **$ARGUMENTS** - -## Workflow - -### Phase 1: Understanding - -1. **Parse Requirements** - - Identify core functionality needed - - List explicit requirements - - Note implicit requirements - - Identify acceptance criteria - -2. **Clarify Ambiguities** - - Ask questions if unclear - - List assumptions made - - Note dependencies on decisions - -### Phase 2: Research - -1. **Explore Codebase** - - Find related implementations - - Identify patterns to follow - - Locate integration points - - Note conventions - -2. **Technical Research** (if needed) - - Research unfamiliar technologies - - Find best practices - - Identify potential pitfalls - -### Phase 3: Task Breakdown - -1. **Decompose Work** - - Break into atomic tasks - - Each task: 15-60 minutes - - Clear completion criteria - -2. **Order by Dependencies** - - What blocks what - - Parallel opportunities - - Critical path - -3. **Add Estimates** - - S: <30 min - - M: 30-60 min - - L: 1-2 hours - - XL: 2-4 hours - -### Phase 4: Documentation - -1. **Create Plan Document** - - Summary - - Task list - - Files to modify - - Risks - -2. **Track with TodoWrite** - - Add all tasks - - Set initial status - -## Output - -### Implementation Plan - -```markdown -## Plan: [Feature/Task Name] - -### Summary -[2-3 sentence overview of what will be built] - -### Scope - -**In Scope** -- [What will be done] - -**Out of Scope** -- [What won't be done] - -**Assumptions** -- [Key assumptions made] - ---- - -### Tasks - -#### Phase 1: Setup [Total: Xh] -| # | Task | Size | Depends On | -|---|------|------|------------| -| 1 | Create data model | M | - | -| 2 | Set up database migration | S | 1 | -| 3 | Add model tests | M | 1 | - -#### Phase 2: Core Implementation [Total: Xh] -| # | Task | Size | Depends On | -|---|------|------|------------| -| 4 | Implement service layer | L | 1 | -| 5 | Add business logic | M | 4 | -| 6 | Write service tests | M | 5 | - -#### Phase 3: API Layer [Total: Xh] -| # | Task | Size | Depends On | -|---|------|------|------------| -| 7 | Create API endpoints | M | 5 | -| 8 | Add validation | S | 7 | -| 9 | Write API tests | M | 8 | - -#### Phase 4: Integration [Total: Xh] -| # | Task | Size | Depends On | -|---|------|------|------------| -| 10 | Integrate with frontend | M | 7 | -| 11 | End-to-end testing | M | 10 | -| 12 | Update documentation | S | 11 | - ---- - -### Files to Create/Modify - -**Create** -- `src/models/feature.py` - Data model -- `src/services/feature.py` - Business logic -- `src/api/feature.py` - API endpoints -- `tests/test_feature.py` - Tests - -**Modify** -- `src/api/__init__.py` - Register routes -- `docs/api.md` - API documentation - ---- - -### Dependencies - -**External** -- [Package X] - For [purpose] - -**Internal** -- Requires [existing feature] to be complete - ---- - -### Risks - -| Risk | Impact | Mitigation | -|------|--------|------------| -| [Risk 1] | High | [How to mitigate] | -| [Risk 2] | Medium | [How to mitigate] | - ---- - -### Questions for Stakeholders -1. [Question about requirement] -2. [Question about edge case] - ---- - -### Success Criteria -- [ ] All tasks completed -- [ ] Tests passing with 80%+ coverage -- [ ] API documentation updated -- [ ] Code reviewed and approved -``` - -## Plan Templates - -### Feature Plan -For new functionality - -### Bug Fix Plan -For debugging and fixing issues - -### Refactor Plan -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/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/executing-plans/SKILL.md` - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=brainstorm` | -| `--detailed` | Use superpowers methodology (2-5 min tasks) | `--detailed` | -| `--depth=[1-5]` | Planning thoroughness level | `--depth=4` | -| `--format=[fmt]` | Output format (concise/detailed/json) | `--format=detailed` | -| `--save=[path]` | Save plan to file | `--save=plans/auth.md` | -| `--checkpoint` | Create checkpoint after planning | `--checkpoint` | - -### Flag Usage Examples - -```bash -/plan --detailed "implement user authentication" -/plan --mode=brainstorm "redesign checkout flow" -/plan --depth=5 --save=plans/migration.md "database migration" -/plan --format=json "api endpoint structure" -``` - -### Mode Recommendations - -| Mode | Best For | -|------|----------| -| `default` | Standard planning | -| `brainstorm` | Exploratory planning, multiple approaches | -| `deep-research` | Complex features needing investigation | -| `implementation` | Quick plans for clear tasks | - -## MCP Integration - -This command leverages MCP servers for enhanced planning: - -### Sequential Thinking - Structured Planning (Primary) -``` -ALWAYS use Sequential Thinking for task decomposition: -- Break complex tasks into logical thought sequences -- Track dependencies between steps -- Revise plan as understanding deepens -- Use for risk identification and mitigation planning -``` - -### Memory - Decision Persistence -``` -Store and recall planning context: -- Remember decisions from previous planning sessions -- Recall user preferences for task sizing -- Store architectural patterns for reuse -- Create entities for major features/components -``` - -### Context7 - Technology Research -``` -When planning involves unfamiliar technologies: -- Fetch current documentation for accurate estimates -- Understand API patterns before estimating complexity -- Identify potential integration challenges -``` - -### Filesystem - Codebase Analysis -``` -For accurate file identification: -- Use directory_tree to understand project structure -- Use search_files to find existing patterns -- Identify files to create vs modify -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Task size definitions (standard: 15-60 min, detailed: 2-5 min) -- Required plan sections -- Estimation approach -- Risk assessment criteria diff --git a/.claude/commands/pr.md b/.claude/commands/pr.md deleted file mode 100644 index 2d987d9..0000000 --- a/.claude/commands/pr.md +++ /dev/null @@ -1,70 +0,0 @@ -# /pr - Create Pull Request - -## Purpose - -Create a well-documented pull request with proper description and checks. - -## Usage - -``` -/pr [title or 'auto'] -``` - ---- - -Create a pull request: **$ARGUMENTS** - -## Workflow - -### Step 1: Prepare Changes - -```bash -git status -git diff main...HEAD -``` - -### Step 2: Verify Ready - -- [ ] All tests passing -- [ ] Code reviewed -- [ ] No merge conflicts -- [ ] Branch pushed - -### Step 3: Create PR - -```bash -gh pr create --title "type(scope): description" --body "$(cat <<'EOF' -## Summary -- [Change 1] -- [Change 2] - -## Test Plan -- [ ] Unit tests -- [ ] Manual testing - -## Screenshots -[If applicable] - -## Checklist -- [ ] Tests added/updated -- [ ] Documentation updated -- [ ] No breaking changes - -🤖 Generated with [Claude Code](https://claude.com/claude-code) -EOF -)" -``` - -## Output - -```markdown -## Pull Request Created - -**URL**: https://github.com/org/repo/pull/123 -**Title**: feat(auth): add OAuth support -**Base**: main ← feature/oauth - -### Changes -- 5 files changed -- +234 -12 lines -``` diff --git a/.claude/commands/refactor.md b/.claude/commands/refactor.md deleted file mode 100644 index 418b7b0..0000000 --- a/.claude/commands/refactor.md +++ /dev/null @@ -1,59 +0,0 @@ -# /refactor - Refactoring Command - -## Purpose - -Improve code structure, readability, or performance without changing behavior. - -## Usage - -``` -/refactor [file or function] [goal: clean | extract | simplify | optimize] -``` - ---- - -Refactor: **$ARGUMENTS** - -## Workflow - -### Step 1: Understand Current Code - -1. Read the code thoroughly -2. Identify what it does -3. Note existing tests - -### Step 2: Plan Refactoring - -1. Identify improvement opportunities -2. Ensure tests exist -3. Plan incremental changes - -### Step 3: Execute - -1. Make small, focused changes -2. Run tests after each change -3. Commit incrementally - -## Refactoring Types - -- **Extract**: Pull out reusable functions -- **Simplify**: Reduce complexity -- **Rename**: Improve clarity -- **Clean**: Remove dead code - -## Output - -```markdown -## Refactoring Complete - -### Changes Made -- Extracted `validateInput()` function -- Simplified conditional logic -- Renamed `x` to `userCount` - -### Before/After -[Code comparison] - -### Tests -All passing -``` diff --git a/.claude/commands/research.md b/.claude/commands/research.md deleted file mode 100644 index 181f4af..0000000 --- a/.claude/commands/research.md +++ /dev/null @@ -1,112 +0,0 @@ -# /research - Research Command - -## Purpose - -Research a technology, library, or approach with comprehensive analysis. - -## Usage - -``` -/research [topic or technology] -``` - ---- - -Research: **$ARGUMENTS** - -## Workflow - -1. **Gather Information** - - Official documentation - - Community resources - - Comparisons - -2. **Analyze** - - Pros and cons - - Best practices - - Alternatives - -3. **Recommend** - - Summary - - Recommendation - - Next steps - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=deep-research` | -| `--depth=[1-5]` | Research thoroughness level | `--depth=5` | -| `--format=[fmt]` | Output format (concise/detailed/json) | `--format=detailed` | -| `--save=[path]` | Save research to file | `--save=docs/research.md` | -| `--compare` | Focus on comparing alternatives | `--compare` | -| `--sequential` | Use sequential thinking methodology | `--sequential` | - -### Flag Usage Examples - -```bash -/research --depth=5 "authentication libraries for Node.js" -/research --compare "React vs Vue vs Svelte" -/research --sequential "root cause of memory leak" -/research --save=docs/orm-research.md "ORM comparison" -``` - -### Depth Levels - -| Level | Behavior | -|-------|----------| -| 1 | Quick overview, key points only | -| 2 | Standard analysis | -| 3 | Thorough with examples | -| 4 | Comprehensive with trade-offs | -| 5 | Exhaustive with citations | - -## MCP Integration - -This command leverages MCP servers for enhanced research: - -### Context7 - Library Documentation (Primary) -``` -ALWAYS use Context7 for library/framework research: -1. Use resolve-library-id to find the library ID -2. Use get-library-docs with topic parameter for focused docs -3. Use mode='code' for API references, mode='info' for concepts -``` - -### Sequential Thinking - Structured Analysis -``` -For complex research requiring step-by-step reasoning: -- Use sequentialthinking tool to break down analysis -- Track confidence scores for each finding -- Revise conclusions as new information emerges -``` - -### Memory - Persistent Research -``` -Store research findings for future reference: -- Create entities for researched technologies -- Add observations with pros/cons/recommendations -- Link related technologies with relations -``` - -## Output - -```markdown -## Research: [Topic] - -### Summary -[Overview] - -### Pros -- [Pro 1] -- [Pro 2] - -### Cons -- [Con 1] - -### Alternatives -[Comparison table] - -### Recommendation -[Clear recommendation] -``` diff --git a/.claude/commands/review.md b/.claude/commands/review.md deleted file mode 100644 index 85f1ba1..0000000 --- a/.claude/commands/review.md +++ /dev/null @@ -1,340 +0,0 @@ -# /review - Code Review Command - -## Purpose - -Comprehensive code review with focus on quality, security, performance, and maintainability. - -## Usage - -``` -/review [file path | 'staged' | 'pr' | PR number] -``` - -## Arguments - -- `$ARGUMENTS`: - - File path: Review specific file(s) - - `staged`: Review all staged changes - - `pr`: Review current branch changes vs main - - PR number: Review specific pull request - ---- - -Perform a comprehensive code review for: **$ARGUMENTS** - -## Workflow - -### Phase 1: Identify Review Scope - -1. **Determine What to Review** - - Single file: Read the specified file - - `staged`: Get staged changes with `git diff --staged` - - `pr`: Get branch diff with `git diff main...HEAD` - - PR number: Fetch PR details with `gh pr view` - -2. **Gather Context** - - Understand the purpose of changes - - Check related tests - - Review CLAUDE.md for project standards - -### Phase 2: Code Quality Review - -Check each file for: - -1. **Correctness** - - Logic errors and bugs - - Edge case handling - - Null/undefined safety - - Type correctness - -2. **Clarity** - - Clear naming (variables, functions, classes) - - Readable structure - - Appropriate comments - - Self-documenting code - -3. **Consistency** - - Follows project conventions - - Matches existing patterns - - Style guide compliance - -4. **Complexity** - - Function length (prefer <30 lines) - - Cyclomatic complexity - - Nesting depth - -### Phase 3: Security Review - -Check for security issues: - -1. **Input Validation** - - User input sanitization - - Type validation - - Size/length limits - -2. **Authentication/Authorization** - - Proper auth checks - - Role-based access control - - Session management - -3. **Data Protection** - - Sensitive data handling - - Encryption where needed - - PII protection - -4. **Injection Prevention** - - SQL injection - - XSS vulnerabilities - - Command injection - -5. **Secrets** - - No hardcoded credentials - - No API keys in code - - Proper env var usage - -### Phase 4: Performance Review - -Check for performance issues: - -1. **Algorithmic Efficiency** - - Time complexity - - Unnecessary loops - - Redundant operations - -2. **Memory Usage** - - Large object creation - - Memory leaks - - Unbounded caches - -3. **Database** - - N+1 queries - - Missing indexes - - Large result sets - -4. **Async Operations** - - Proper async/await - - Parallel where possible - - Timeout handling - -### Phase 5: Maintainability Review - -Check for maintainability: - -1. **SOLID Principles** - - Single responsibility - - Open/closed - - Dependency injection - -2. **DRY** - - Code duplication - - Opportunity for reuse - -3. **Testing** - - Test coverage - - Test quality - - Edge case tests - -4. **Documentation** - - API documentation - - Complex logic explanation - - Usage examples - -## Output Format - -```markdown -## Code Review: [Target] - -**Reviewed**: [files/changes] -**Verdict**: [Approve | Request Changes | Needs Discussion] - ---- - -### Critical Issues (Must Fix) - -#### 1. [Security] SQL Injection Risk -**File**: `src/api/users.ts:42` -**Severity**: Critical - -```typescript -// Current code -const query = `SELECT * FROM users WHERE id = ${userId}`; -``` - -**Issue**: User input directly interpolated into SQL query. - -**Fix**: -```typescript -const query = 'SELECT * FROM users WHERE id = $1'; -const result = await db.query(query, [userId]); -``` - ---- - -### Recommendations (Should Fix) - -#### 1. Missing Error Handling -**File**: `src/services/auth.ts:78` - -```typescript -// Current -const user = await db.findUser(email); -return user.password; // May throw if user is null -``` - -**Suggestion**: -```typescript -const user = await db.findUser(email); -if (!user) { - throw new NotFoundError('User not found'); -} -return user.password; -``` - ---- - -### Suggestions (Nice to Have) - -1. Consider extracting the validation logic in `src/utils/validate.ts:23` into a separate function for reusability. - -2. The constant `MAX_RETRIES` in `src/api/client.ts` could be moved to configuration. - ---- - -### What's Good - -- Clean separation of concerns between controller and service layers -- Comprehensive error handling in the authentication flow -- Good test coverage for edge cases in `auth.test.ts` - ---- - -### Summary - -Found **1 critical issue** (security), **2 recommendations**, and **2 suggestions**. - -**Priority Actions**: -1. Fix SQL injection vulnerability immediately -2. Add null check for user lookup - -**Ready for merge**: No - Critical issues must be addressed first -``` - -## Review Checklist - -### Security -- [ ] No hardcoded secrets -- [ ] Input validation present -- [ ] Output encoding for rendered content -- [ ] SQL parameterization -- [ ] Proper auth checks -- [ ] No eval() or dynamic code execution - -### Quality -- [ ] Clear naming conventions -- [ ] Functions are focused (single responsibility) -- [ ] Error handling is complete -- [ ] No commented-out code -- [ ] No debug statements left - -### Testing -- [ ] New code has tests -- [ ] Edge cases covered -- [ ] Tests are deterministic - -### Documentation -- [ ] Public APIs documented -- [ ] Complex logic explained -- [ ] Breaking changes noted - -## Example - -**Input**: `/review staged` - -**Output**: Complete review of all staged changes with security scan, code quality assessment, and actionable feedback organized by severity. - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--mode=[mode]` | Use specific behavioral mode | `--mode=review` | -| `--persona=[type]` | Apply persona expertise | `--persona=security` | -| `--depth=[1-5]` | Review thoroughness level | `--depth=5` | -| `--format=[fmt]` | Output format (concise/detailed/json) | `--format=detailed` | -| `--focus=[area]` | Focus on specific area | `--focus=performance` | -| `--save` | Save review to file | `--save` | - -### Flag Usage Examples - -```bash -/review --persona=security src/auth/ -/review --depth=5 --format=detailed staged -/review --focus=performance src/services/heavy-computation.ts -/review --mode=deep-research --save pr -``` - -### Persona Options - -| Persona | Focus Area | -|---------|------------| -| `security` | Vulnerabilities, auth, data protection | -| `performance` | Efficiency, queries, caching | -| `architecture` | Patterns, coupling, SOLID | -| `testing` | Coverage, test quality | -| `accessibility` | A11y compliance | - -### Focus Areas - -| Focus | Checks | -|-------|--------| -| `security` | OWASP top 10, auth, input validation | -| `performance` | N+1, complexity, memory | -| `quality` | Readability, maintainability | -| `testing` | Coverage, test patterns | - -## MCP Integration - -This command leverages MCP servers for enhanced code review: - -### Playwright - Visual/UI Review -``` -For reviewing UI changes: -- Render and screenshot components -- Compare visual changes across browsers -- Verify responsive behavior -- Check accessibility in real browser -``` - -### Memory - Review Context -``` -Store and recall review context: -- Remember past review decisions -- Recall user's coding standards -- Store patterns approved/rejected previously -- Track recurring issues across reviews -``` - -### Sequential Thinking - Systematic Analysis -``` -For thorough code analysis: -- Step through complex logic systematically -- Track multiple concerns in parallel -- Build comprehensive issue list -- Revise severity as context emerges -``` - -### Filesystem - Code Access -``` -For reviewing file changes: -- Use read_file to examine code -- Use search_files to find related patterns -- Check for similar issues across codebase -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Set required review checklist items -- Define severity levels -- Configure approval criteria -- Set documentation requirements diff --git a/.claude/commands/security-scan.md b/.claude/commands/security-scan.md deleted file mode 100644 index fe8cb7a..0000000 --- a/.claude/commands/security-scan.md +++ /dev/null @@ -1,52 +0,0 @@ -# /security-scan - Security Scanning Command - -## Purpose - -Scan code and dependencies for security vulnerabilities. - -## Usage - -``` -/security-scan [scope: deps | code | secrets | all] -``` - ---- - -Run security scan: **$ARGUMENTS** - -## Workflow - -### Dependency Scan - -```bash -npm audit -pip-audit -``` - -### Code Scan - -- SQL injection patterns -- XSS vulnerabilities -- Command injection - -### Secret Detection - -- API keys -- Passwords -- Tokens - -## Output - -```markdown -## Security Scan Results - -### Summary -| Type | Critical | High | Medium | -|------|----------|------|--------| -| Dependencies | 0 | 2 | 5 | -| Code | 0 | 1 | 3 | -| Secrets | 0 | 0 | 0 | - -### Findings -[Detailed findings with remediation] -``` diff --git a/.claude/commands/ship.md b/.claude/commands/ship.md deleted file mode 100644 index 273ed37..0000000 --- a/.claude/commands/ship.md +++ /dev/null @@ -1,217 +0,0 @@ -# /ship - Ship Code Command - -## Purpose - -Complete workflow to commit changes, run reviews, execute tests, and create a pull request ready for merge. - -## Usage - -``` -/ship [commit message or 'quick'] -``` - -## Arguments - -- `$ARGUMENTS`: - - Commit message: Use as commit subject - - `quick`: Auto-generate message, skip review - ---- - -Ship the current changes with: **$ARGUMENTS** - -## Workflow - -### Phase 1: Pre-Ship Checks - -1. **Check Repository Status** - ```bash - git status - git diff --staged - ``` - -2. **Identify Changes** - - Files modified - - Files added - - Files deleted - -3. **Quick Validation** - - No secrets in changes - - No debug statements - - No commented-out code - -### Phase 2: Code Review (unless 'quick') - -1. **Run Self-Review** - - Check code quality - - Verify style compliance - - Identify security issues - -2. **Address Critical Issues** - - Fix any critical problems - - Note recommendations - -### Phase 3: Run Tests - -1. **Execute Test Suite** - ```bash - # Python - pytest -v - - # TypeScript - pnpm test - ``` - -2. **Verify All Pass** - - No failing tests - - No new warnings - -3. **Check Coverage** - - Coverage not decreased - - New code is tested - -### Phase 4: Create Commit - -1. **Stage Changes** - ```bash - git add -A - ``` - -2. **Generate Commit Message** - - Follow conventional commit format - - Reference issues if applicable - -3. **Create Commit** - ```bash - git commit -m "$(cat <<'EOF' - type(scope): subject - - body - - 🤖 Generated with [Claude Code](https://claude.com/claude-code) - - Co-Authored-By: Claude - EOF - )" - ``` - -### Phase 5: Push and Create PR - -1. **Push to Remote** - ```bash - git push -u origin [branch-name] - ``` - -2. **Create Pull Request** - ```bash - gh pr create --title "type(scope): description" --body "$(cat <<'EOF' - ## Summary - - Change 1 - - Change 2 - - ## Test Plan - - [ ] Tests pass - - [ ] Manual testing - - 🤖 Generated with [Claude Code](https://claude.com/claude-code) - EOF - )" - ``` - -## Output - -### Ship Report - -```markdown -## Ship Complete - -### Commit -**Hash**: `abc1234` -**Message**: `feat(auth): add password reset functionality` - -### Changes -| File | Change | -|------|--------| -| `src/auth/reset.ts` | Added | -| `src/auth/routes.ts` | Modified | -| `tests/auth/reset.test.ts` | Added | - -### Checks -- [x] Code review passed -- [x] Tests passing (42 tests) -- [x] Coverage: 85% (+3%) -- [x] No security issues - -### Pull Request -**URL**: https://github.com/org/repo/pull/123 -**Title**: feat(auth): add password reset functionality -**Base**: main -**Status**: Ready for review - -### Next Steps -1. Request review from team -2. Address any feedback -3. Merge when approved -``` - -## Quick Ship Mode - -When using `/ship quick`: -- Skip detailed code review -- Auto-generate commit message -- Minimal output - -```bash -# Quick ship for small changes -/ship quick -``` - -## Commit Message Generation - -Based on changes, generate appropriate message: - -### Feature -``` -feat(scope): add [feature] - -- Added [component/function] -- Implemented [functionality] -- Added tests for [scenarios] -``` - -### Bug Fix -``` -fix(scope): resolve [issue] - -- Fixed [bug description] -- Added null check for [case] -- Updated tests -``` - -### Refactor -``` -refactor(scope): improve [area] - -- Extracted [logic] to [location] -- Renamed [old] to [new] -- Simplified [complex code] -``` - -## Pre-Ship Checklist - -- [ ] All changes staged -- [ ] No unintended files included -- [ ] Tests pass -- [ ] No secrets in code -- [ ] No debug statements -- [ ] Commit message is descriptive -- [ ] PR description is complete - - -## Variations - -Modify behavior via CLAUDE.md: -- Required checks before ship -- Commit message format -- PR template requirements -- Auto-merge settings diff --git a/.claude/commands/spawn.md b/.claude/commands/spawn.md deleted file mode 100644 index e738c27..0000000 --- a/.claude/commands/spawn.md +++ /dev/null @@ -1,173 +0,0 @@ -# /spawn - -## Purpose - -Launch background tasks for parallel execution. Enables concurrent work on independent tasks with result aggregation. - ---- - -Launch a background task or manage running tasks. - -## Spawn Operations - -### Launch Task - -Start a new background task: - -```bash -/spawn "[task description]" -``` - -**Process:** -1. Analyze task for parallelizability -2. Launch subagent with task -3. Return task ID for tracking -4. Continue main conversation - -**Output:** -```markdown -Spawned: Task #1 -- Description: Research authentication patterns -- Status: Running -- Agent: researcher - -Continue working. Use `/spawn --list` to check status. -``` - -### List Tasks - -Show running and completed tasks: - -```bash -/spawn --list -``` - -**Output:** -```markdown -## Active Tasks - -| ID | Description | Status | Duration | -|----|-------------|--------|----------| -| #1 | Research auth patterns | Running | 2m | -| #2 | Analyze security | Complete | 5m | - -## Completed Tasks (last hour) -| #2 | Analyze security | ✅ Complete | Results ready | -``` - -### Collect Results - -Gather results from completed tasks: - -```bash -/spawn --collect -``` - -**Output:** -```markdown -## Collected Results - -### Task #1: Research auth patterns -**Status**: Complete -**Findings**: -- Pattern A: JWT with refresh tokens -- Pattern B: Session-based with Redis -- Recommendation: JWT for stateless API - -### Task #2: Analyze security -**Status**: Complete -**Findings**: -- 2 high-priority issues found -- See detailed report below -``` - -### Cancel Task - -Stop a running task: - -```bash -/spawn --cancel [id] -``` - -## Task Types - -| Type | Best For | Agent Used | -|------|----------|------------| -| Research | Information gathering | researcher | -| Analysis | Code analysis | scout | -| Review | Code review | code-reviewer | -| Test | Test generation | tester | -| Scan | Security scanning | security-auditor | - -## Flags - -| Flag | Description | -|------|-------------| -| `--list` | Show all tasks | -| `--collect` | Gather completed results | -| `--cancel [id]` | Cancel running task | -| `--wait` | Wait for all tasks to complete | -| `--agent=[type]` | Specify agent type | -| `--priority=[high\|normal]` | Task priority | - -## Usage Examples - -```bash -/spawn "Research OAuth2 best practices" -/spawn "Analyze user service for performance issues" -/spawn "Review security of auth module" --agent=security-auditor -/spawn --list -/spawn --collect -/spawn --wait # Block until all complete -``` - -## Arguments - -$ARGUMENTS - -If quoted text: spawn that task -If flag: execute that operation - ---- - -## Parallel Workflow - -### Pattern: Research Phase -```bash -/spawn "Research authentication approaches" -/spawn "Analyze current auth implementation" -/spawn "Review competitor auth patterns" -# Continue other work... -/spawn --wait -/spawn --collect -# Synthesize findings -``` - -### Pattern: Multi-File Review -```bash -/spawn "Review src/auth/ for security" -/spawn "Review src/api/ for performance" -/spawn "Review src/db/ for SQL injection" -/spawn --collect -# Address findings -``` - -## Best Practices - -1. **Independent Tasks**: Only spawn truly independent work -2. **Clear Descriptions**: Specific task descriptions get better results -3. **Regular Collection**: Don't let results pile up -4. **Resource Awareness**: Don't spawn too many concurrent tasks - -## Limitations - -- Tasks cannot communicate with each other -- Results are collected, not streamed -- Heavy tasks may take time -- Some tasks benefit from sequential execution - -## Combines With - -- Orchestration mode: Manages multiple spawned tasks -- `/plan`: Plan tasks, then spawn parallel execution -- `/execute-plan`: Orchestrated task execution diff --git a/.claude/commands/status.md b/.claude/commands/status.md deleted file mode 100644 index 1397d3e..0000000 --- a/.claude/commands/status.md +++ /dev/null @@ -1,55 +0,0 @@ -# /status - Project Status Command - -## Purpose - -Get current project status including tasks, git state, and recent activity. - -## Usage - -``` -/status -``` - ---- - -Show current project status. - -## Workflow - -1. **Check Git Status** - ```bash - git status - git log --oneline -5 - ``` - -2. **Review Todos** - - In progress - - Pending - - Completed today - -3. **Recent Activity** - - Recent commits - - Open PRs - - Open issues - -## Output - -```markdown -## Project Status - -### Git -- Branch: `feature/xyz` -- Status: Clean / X modified files - -### Tasks -- In Progress: X -- Pending: Y -- Completed: Z - -### Recent Commits -1. [commit message] -2. [commit message] - -### Open PRs -- #123: [title] -``` diff --git a/.claude/commands/tdd.md b/.claude/commands/tdd.md deleted file mode 100644 index a454375..0000000 --- a/.claude/commands/tdd.md +++ /dev/null @@ -1,135 +0,0 @@ -# /tdd - Test-Driven Development Workflow - -## Purpose - -Start a TDD workflow: write failing tests first, then implement to make them pass. - -## Usage - -``` -/tdd [feature or function description] -``` - ---- - -Start TDD workflow for: **$ARGUMENTS** - -## Workflow - -### Phase 1: Red - Write Failing Tests - -1. **Understand Requirements** - - What should the code do? - - What are the inputs/outputs? - - What edge cases exist? - -2. **Write Tests First** - ```python - def test_feature_does_expected_thing(): - result = feature("input") - assert result == "expected" - ``` - -3. **Run Tests (Expect Failure)** - ```bash - pytest -v # Should fail - ``` - -### Phase 2: Green - Make Tests Pass - -1. **Implement Minimal Code** - - Just enough to pass tests - - No premature optimization - -2. **Run Tests (Expect Success)** - ```bash - pytest -v # Should pass - ``` - -### Phase 3: Refactor - -1. **Improve Code Quality** - - Clean up implementation - - Remove duplication - - Improve naming - -2. **Run Tests (Ensure Still Passing)** - ```bash - pytest -v # Should still pass - ``` - -### Phase 4: Repeat - -Add more test cases and repeat the cycle. - -## TDD Best Practices - -- Write one test at a time -- Tests should be specific and focused -- Keep the red-green-refactor cycle short -- Commit after each green phase - -## Superpowers TDD Methodology - -**Reference**: `.claude/skills/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/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/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 -## TDD Session: [Feature] - -### Tests Written -1. `test_basic_functionality` - [description] -2. `test_edge_case` - [description] - -### Implementation -`src/feature.py` - [description] - -### Cycle Summary -- Red: 3 tests written -- Green: All passing -- Refactor: Extracted helper function -``` diff --git a/.claude/commands/test.md b/.claude/commands/test.md deleted file mode 100644 index 35169e3..0000000 --- a/.claude/commands/test.md +++ /dev/null @@ -1,336 +0,0 @@ -# /test - Test Generation Command - -## Purpose - -Generate comprehensive tests for specified code including unit tests, integration tests, and edge cases. - -## Usage - -``` -/test [file path | function name | 'coverage' | 'all'] -``` - -## Arguments - -- `$ARGUMENTS`: - - File path: Generate tests for specific file - - Function name: Generate tests for specific function - - `coverage`: Analyze and improve test coverage - - `all`: Run all tests and report results - ---- - -Generate comprehensive tests for: **$ARGUMENTS** - -## Workflow - -### For File/Function Testing - -1. **Analyze Target Code** - - Read the code to understand functionality - - Identify inputs, outputs, and side effects - - Note dependencies to mock - - Find existing tests for patterns - -2. **Design Test Cases** - - **Happy Path**: Normal operation with valid inputs - - **Edge Cases**: Boundary values, empty inputs, limits - - **Error Cases**: Invalid inputs, exceptions - - **Integration Points**: External dependencies - -3. **Generate Tests** - - Follow project testing conventions - - Use appropriate mocking strategies - - Write clear, descriptive test names - - Include setup and teardown - -4. **Run and Verify** - ```bash - # Python - pytest [test_file] -v - - # TypeScript - pnpm test [test_file] - ``` - -### For Coverage Analysis - -1. **Run Coverage Report** - ```bash - # Python - pytest --cov=src --cov-report=term-missing - - # TypeScript - pnpm test --coverage - ``` - -2. **Identify Gaps** - - Find untested functions - - Identify untested branches - - Note missing edge cases - -3. **Generate Missing Tests** - - Prioritize by risk - - Focus on critical paths - - Add edge case coverage - -## Test Templates - -### Python (pytest) - -```python -import pytest -from unittest.mock import Mock, patch -from src.module import function_under_test - -class TestFunctionUnderTest: - """Tests for function_under_test.""" - - def test_with_valid_input_returns_expected(self): - """Test that valid input produces expected output.""" - result = function_under_test("valid_input") - assert result == "expected_output" - - def test_with_empty_input_returns_default(self): - """Test that empty input returns default value.""" - result = function_under_test("") - assert result == "default" - - def test_with_invalid_input_raises_error(self): - """Test that invalid input raises ValueError.""" - with pytest.raises(ValueError, match="Invalid input"): - function_under_test(None) - - @pytest.mark.parametrize("input_val,expected", [ - ("a", "result_a"), - ("b", "result_b"), - ("c", "result_c"), - ]) - def test_parametrized_inputs(self, input_val, expected): - """Test multiple input variations.""" - assert function_under_test(input_val) == expected - - @patch('src.module.external_service') - def test_with_mocked_dependency(self, mock_service): - """Test with mocked external dependency.""" - mock_service.call.return_value = "mocked_result" - result = function_under_test("input") - assert result == "expected_with_mock" - mock_service.call.assert_called_once_with("input") -``` - -### TypeScript (vitest) - -```typescript -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { functionUnderTest } from './module'; - -describe('functionUnderTest', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it('should return expected output for valid input', () => { - const result = functionUnderTest('valid_input'); - expect(result).toBe('expected_output'); - }); - - it('should return default for empty input', () => { - const result = functionUnderTest(''); - expect(result).toBe('default'); - }); - - it('should throw error for invalid input', () => { - expect(() => functionUnderTest(null)).toThrow('Invalid input'); - }); - - it.each([ - ['a', 'result_a'], - ['b', 'result_b'], - ['c', 'result_c'], - ])('should handle input %s correctly', (input, expected) => { - expect(functionUnderTest(input)).toBe(expected); - }); - - it('should work with mocked dependency', async () => { - vi.mock('./external-service', () => ({ - call: vi.fn().mockResolvedValue('mocked_result'), - })); - - const result = await functionUnderTest('input'); - expect(result).toBe('expected_with_mock'); - }); -}); -``` - -### React Component (Testing Library) - -```typescript -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; -import { UserForm } from './UserForm'; - -describe('UserForm', () => { - it('should render form fields', () => { - render(); - - expect(screen.getByLabelText(/name/i)).toBeInTheDocument(); - expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument(); - }); - - it('should call onSubmit with form data', async () => { - const onSubmit = vi.fn(); - render(); - - fireEvent.change(screen.getByLabelText(/name/i), { - target: { value: 'John' }, - }); - fireEvent.change(screen.getByLabelText(/email/i), { - target: { value: 'john@example.com' }, - }); - fireEvent.click(screen.getByRole('button', { name: /submit/i })); - - await waitFor(() => { - expect(onSubmit).toHaveBeenCalledWith({ - name: 'John', - email: 'john@example.com', - }); - }); - }); - - it('should show validation error for invalid email', async () => { - render(); - - fireEvent.change(screen.getByLabelText(/email/i), { - target: { value: 'invalid' }, - }); - fireEvent.blur(screen.getByLabelText(/email/i)); - - expect(await screen.findByText(/invalid email/i)).toBeInTheDocument(); - }); -}); -``` - -## Output - -### Test Generation Report - -```markdown -## Tests Generated - -### Target -`src/services/auth.ts` - AuthService class - -### Tests Created -- `tests/services/auth.test.ts` - -### Test Cases -1. `login_with_valid_credentials_returns_token` - Happy path -2. `login_with_invalid_password_throws_error` - Error case -3. `login_with_nonexistent_user_throws_error` - Error case -4. `refresh_token_with_valid_token_returns_new_token` - Happy path -5. `refresh_token_with_expired_token_throws_error` - Edge case -6. `logout_invalidates_session` - Happy path - -### Coverage Impact -- Before: 65% -- After: 88% -- New lines covered: 42 - -### Run Tests -```bash -pytest tests/services/auth.test.ts -v -``` - -### Notes -- Mocked database calls using pytest-mock -- Added edge case for token expiration -- Consider adding integration tests for full auth flow -``` - -## Flags - -| Flag | Description | Example | -|------|-------------|---------| -| `--coverage` | Generate coverage-focused tests | `--coverage` | -| `--type=[type]` | Test type to generate | `--type=integration` | -| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` | -| `--framework=[fw]` | Specify test framework | `--framework=vitest` | -| `--tdd` | Generate TDD-style with failing tests first | `--tdd` | -| `--edge-cases` | Focus on edge case coverage | `--edge-cases` | - -### Flag Usage Examples - -```bash -/test --coverage src/services/ -/test --type=integration src/api/users.ts -/test --tdd src/utils/validator.ts -/test --edge-cases --framework=pytest src/models/user.py -``` - -### Test Types - -| Type | Description | -|------|-------------| -| `unit` | Isolated function tests (default) | -| `integration` | Multi-component tests | -| `e2e` | End-to-end workflow tests | -| `snapshot` | Snapshot tests for UI | -| `property` | Property-based testing | - -### Framework Options - -| Framework | Language | -|-----------|----------| -| `pytest` | Python | -| `vitest` | TypeScript/JavaScript | -| `jest` | JavaScript | -| `playwright` | E2E (any) | - -## MCP Integration - -This command leverages MCP servers for enhanced testing: - -### Playwright - E2E Testing (Primary for UI) -``` -For E2E and browser tests: -- Use Playwright for cross-browser testing -- Automate user flow verification -- Capture screenshots for visual testing -- Test on different device emulations -``` - -### Filesystem - Test File Management -``` -For test file operations: -- Use directory_tree to find test directories -- Use search_files to find existing tests -- Use read_file to check test patterns -- Use write_file to create new test files -``` - -### Context7 - Testing Best Practices -``` -For framework-specific testing: -- Fetch current testing library docs -- Get latest assertions and matchers -- Find recommended testing patterns -``` - -### Memory - Test Patterns -``` -Recall testing context: -- Remember project testing conventions -- Recall mock patterns used previously -- Store common test fixtures -``` - - -## Variations - -Modify behavior via CLAUDE.md: -- Preferred test framework -- Minimum coverage targets -- Test naming conventions -- Required test categories diff --git a/.claude/skills/brainstorming/SKILL.md b/.claude/skills/brainstorming/SKILL.md index b844e59..ced2f65 100644 --- a/.claude/skills/brainstorming/SKILL.md +++ b/.claude/skills/brainstorming/SKILL.md @@ -1,5 +1,6 @@ --- name: brainstorming +argument-hint: "[topic]" description: > Use when the user wants to design, explore, or ideate on ANY new feature, architecture decision, or unclear requirement. Activate for keywords like "brainstorm", "design", "explore", "what if", "how should we", "options for", "trade-offs", or any open-ended question about implementation approach. Also trigger when requirements are vague, ambiguous, or when multiple valid solutions exist -- err on the side of brainstorming before jumping into code. --- diff --git a/.claude/skills/condition-based-waiting/SKILL.md b/.claude/skills/condition-based-waiting/SKILL.md index 56cd7b2..4964871 100644 --- a/.claude/skills/condition-based-waiting/SKILL.md +++ b/.claude/skills/condition-based-waiting/SKILL.md @@ -1,5 +1,6 @@ --- name: condition-based-waiting +user-invocable: false description: > Use when waiting on external conditions like CI pipeline runs, deployments, long builds, database migrations, or test suites. Trigger for keywords like "wait for", "check status", "poll", "monitor", "is it done", "build running", "deploy in progress", or when a background process needs to complete before the next step. Also activate when using run_in_background or Monitor tools in Claude Code. --- diff --git a/.claude/skills/defense-in-depth/SKILL.md b/.claude/skills/defense-in-depth/SKILL.md index 6c9fb18..8a20b35 100644 --- a/.claude/skills/defense-in-depth/SKILL.md +++ b/.claude/skills/defense-in-depth/SKILL.md @@ -1,5 +1,6 @@ --- name: defense-in-depth +user-invocable: false description: > Use when fixing any data-related bug, when building validation for critical data paths, or when a single validation point has already failed in production. Also activate whenever you hear "it slipped through," "the check was bypassed," or "it worked in tests but not production." Apply aggressively to any scenario involving data integrity, input validation across layers, or preventing bug recurrence through structural guarantees rather than single-point fixes. --- diff --git a/.claude/skills/devops/SKILL.md b/.claude/skills/devops/SKILL.md index 964b422..47fc77e 100644 --- a/.claude/skills/devops/SKILL.md +++ b/.claude/skills/devops/SKILL.md @@ -1,7 +1,7 @@ --- name: devops description: > - Use when containerizing applications, configuring CI/CD pipelines, or deploying to edge — including Docker, Dockerfile, docker-compose, multi-stage builds, GitHub Actions, workflow YAML, matrix builds, workflow_dispatch, Cloudflare Workers, Pages, R2, D1, KV, wrangler, or container registries. + Use when containerizing applications, configuring CI/CD pipelines, deploying to environments, or deploying to edge — including Docker, Dockerfile, docker-compose, multi-stage builds, GitHub Actions, workflow YAML, matrix builds, workflow_dispatch, Cloudflare Workers, Pages, R2, D1, KV, wrangler, container registries, or deployment workflows (staging, production, health checks, smoke tests). --- # DevOps @@ -11,6 +11,8 @@ description: > - Containerizing applications with Docker or Docker Compose - Setting up CI/CD pipelines with GitHub Actions - Deploying to Cloudflare Workers, Pages, R2, D1, or KV +- Deploying applications to staging or production environments +- Running pre-deploy checks (build, tests, security audit) - Optimizing container images, build caching, or deployment workflows - Configuring wrangler.toml, Durable Objects, or Cloudflare Queues diff --git a/.claude/skills/dispatching-parallel-agents/SKILL.md b/.claude/skills/dispatching-parallel-agents/SKILL.md index ef23278..20176d0 100644 --- a/.claude/skills/dispatching-parallel-agents/SKILL.md +++ b/.claude/skills/dispatching-parallel-agents/SKILL.md @@ -1,7 +1,7 @@ --- name: dispatching-parallel-agents description: > - Use when facing 3 or more independent failures across different domains, when multiple subsystems are broken with no shared state, or when test failures span unrelated modules. Also activate whenever you see independent bugs in auth, cart, user, or other separate domains that can be fixed concurrently. Activate aggressively for any scenario where parallel work would reduce total resolution time without creating merge conflicts. + Use when facing 3 or more independent failures across different domains, when multiple subsystems are broken with no shared state, or when test failures span unrelated modules. Also activate whenever you see independent bugs in auth, cart, user, or other separate domains that can be fixed concurrently. Use for launching parallel background tasks like research, analysis, or code review across independent areas. Activate aggressively for any scenario where parallel work would reduce total resolution time without creating merge conflicts. --- # Dispatching Parallel Agents diff --git a/.claude/skills/documentation/SKILL.md b/.claude/skills/documentation/SKILL.md new file mode 100644 index 0000000..10f3a4c --- /dev/null +++ b/.claude/skills/documentation/SKILL.md @@ -0,0 +1,82 @@ +--- +name: documentation +argument-hint: "[file or api/readme]" +description: > + Use when generating or updating documentation — including code comments, docstrings, JSDoc, API docs, README files, or technical specifications. Trigger for keywords like "document", "docstring", "JSDoc", "README", "API docs", "explain this code", "add comments", or any request to improve code documentation. Also activate when generating project documentation or updating existing docs after code changes. +--- + +# Documentation + +## When to Use + +- Adding docstrings or JSDoc to functions/classes +- Generating or updating README files +- Documenting API endpoints +- Writing technical specifications +- Adding inline comments to complex logic + +## When NOT to Use + +- Generating changelogs from commits — use `git-workflows` +- Writing OpenAPI specs — use `openapi` +- Architecture design documentation — use `brainstorming` + `writing-plans` + +--- + +## Quick Reference + +| Topic | Reference | Key content | +|-------|-----------|-------------| +| Code documentation | `references/code-docs.md` | Python docstrings, TypeScript JSDoc, inline comments | +| API documentation | `references/api-docs.md` | Endpoint docs, request/response examples | +| Project documentation | `references/project-docs.md` | README, CONTRIBUTING, architecture docs | + +--- + +## Documentation Workflow + +### For Code + +1. Read the code thoroughly — understand purpose and behavior +2. Identify inputs, outputs, side effects, and edge cases +3. Add docstrings/JSDoc with examples +4. Add type annotations if missing + +### For APIs + +1. Scan route definitions and identify endpoints +2. Document request format, response format, error responses +3. Add authentication requirements +4. Include working examples + +### For Projects + +1. Analyze project purpose, features, and setup +2. Write clear installation and usage instructions +3. Include working code examples +4. Keep configuration tables up to date + +--- + +## Best Practices + +1. **Document the why, not the what** — code shows what; comments explain why. +2. **Include examples** — one working example beats three paragraphs of description. +3. **Document edge cases** — what happens with null, empty, or invalid input? +4. **Keep docs adjacent to code** — docstrings over separate doc files. +5. **Update docs with code** — stale docs are worse than no docs. + +## Common Pitfalls + +1. **Restating the code** — `# increment i by 1` adds no value. +2. **Missing error documentation** — not documenting what exceptions a function raises. +3. **Outdated examples** — code examples that no longer compile. +4. **Over-documenting internal code** — public APIs need docs; private helpers often don't. + +--- + +## Related Skills + +- `openapi` — OpenAPI spec generation for REST APIs +- `git-workflows` — Changelog generation from commits +- `backend-frameworks` — Framework-specific documentation patterns diff --git a/.claude/skills/documentation/references/api-docs.md b/.claude/skills/documentation/references/api-docs.md new file mode 100644 index 0000000..55a24c9 --- /dev/null +++ b/.claude/skills/documentation/references/api-docs.md @@ -0,0 +1,44 @@ +# API Documentation Patterns + +## Endpoint Documentation Template + +```markdown +## POST /api/orders + +Create a new order. + +### Authentication +Requires Bearer token. + +### Request Body +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| items | array | yes | Order items | +| shippingAddress | object | yes | Delivery address | + +### Response (201 Created) +```json +{ + "id": "order_456", + "status": "pending", + "total": 99.99, + "createdAt": "2024-01-15T10:00:00Z" +} +``` + +### Errors +| Status | Code | Description | +|--------|------|-------------| +| 400 | INVALID_ITEMS | Items array is empty | +| 401 | UNAUTHORIZED | Invalid or missing token | +| 422 | OUT_OF_STOCK | Item not available | +``` + +## Discovery Process + +1. Scan route definitions (`@app.get`, `router.post`, `@Controller`) +2. Identify HTTP methods and paths +3. Note authentication requirements +4. Document request/response schemas +5. List all error responses with codes +6. Add working curl/httpx examples diff --git a/.claude/skills/documentation/references/code-docs.md b/.claude/skills/documentation/references/code-docs.md new file mode 100644 index 0000000..fad5190 --- /dev/null +++ b/.claude/skills/documentation/references/code-docs.md @@ -0,0 +1,52 @@ +# Code Documentation Patterns + +## Python Docstrings (Google Style) + +```python +def calculate_discount(price: float, percentage: float) -> float: + """Calculate discounted price. + + Args: + price: Original price in dollars. + percentage: Discount percentage (0-100). + + Returns: + The discounted price. + + Raises: + ValueError: If percentage is not between 0 and 100. + + Example: + >>> calculate_discount(100.0, 20) + 80.0 + """ +``` + +## TypeScript JSDoc + +```typescript +/** + * Calculate discounted price. + * + * @param price - Original price in dollars + * @param percentage - Discount percentage (0-100) + * @returns The discounted price + * @throws {RangeError} If percentage is not between 0 and 100 + * + * @example + * calculateDiscount(100, 20); // returns 80 + */ +``` + +## When to Add Inline Comments + +- Explain **why**, not what — `# Retry 3x because upstream API is flaky` +- Document workarounds — `// Safari doesn't support this API, fallback to...` +- Clarify non-obvious logic — `# O(1) amortized via lazy deletion` +- Mark TODOs with context — `# TODO(#123): remove after migration complete` + +## When NOT to Comment + +- Restating the code: `i += 1 # increment i by 1` +- Obvious function names: `def get_user_by_id` needs no docstring explaining it gets a user by ID +- Commented-out code — delete it, git has history diff --git a/.claude/skills/documentation/references/project-docs.md b/.claude/skills/documentation/references/project-docs.md new file mode 100644 index 0000000..f07a360 --- /dev/null +++ b/.claude/skills/documentation/references/project-docs.md @@ -0,0 +1,43 @@ +# Project Documentation Patterns + +## README Structure + +```markdown +## Installation + +```bash +npm install my-package +``` + +## Quick Start + +```typescript +import { Client } from 'my-package'; +const client = new Client({ apiKey: 'your-key' }); +const result = await client.fetch(); +``` + +## Configuration + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `apiKey` | string | required | Your API key | +| `timeout` | number | 5000 | Request timeout in ms | +``` + +## Key Sections + +1. **Title + one-liner** — what this project does +2. **Installation** — copy-pasteable setup commands +3. **Quick Start** — working example in < 10 lines +4. **Configuration** — table of options with types and defaults +5. **API Reference** — link to detailed docs +6. **Contributing** — how to contribute +7. **License** — MIT, Apache, etc. + +## Documentation Coverage Report + +After documenting, summarize: +- Functions documented: X/Y (Z%) +- Endpoints documented: X/Y (Z%) +- Missing: [list of undocumented items] diff --git a/.claude/skills/feature-workflow/SKILL.md b/.claude/skills/feature-workflow/SKILL.md new file mode 100644 index 0000000..37bbf9f --- /dev/null +++ b/.claude/skills/feature-workflow/SKILL.md @@ -0,0 +1,135 @@ +--- +name: feature-workflow +argument-hint: "[feature description or issue]" +description: > + Use when implementing a complete feature end-to-end — from requirements analysis through planning, implementation, testing, and review. Trigger for keywords like "feature", "implement", "build", "add functionality", "end-to-end", or any task that spans planning through delivery. Also activate when the user provides a feature description, issue reference, or requirement spec that needs a structured development workflow. +--- + +# Feature Workflow + +## When to Use + +- Implementing a complete feature from requirements to delivery +- When given a feature description, issue number, or requirement spec +- Multi-phase work that needs planning, implementation, testing, and review +- Any task that benefits from a structured development workflow + +## When NOT to Use + +- Simple bug fixes — use `systematic-debugging` +- Pure refactoring — use `refactoring` +- Writing tests for existing code — use `testing` +- Already have a plan to execute — use `executing-plans` + +--- + +## Workflow Phases + +### Phase 1: Understanding + +1. Parse the feature request thoroughly +2. Identify acceptance criteria +3. List assumptions that need validation +4. Clarify ambiguous requirements with the user + +### Phase 2: Planning + +1. Explore codebase for related implementations and patterns +2. Identify integration points and dependencies +3. Decompose into atomic, verifiable tasks +4. Order tasks by dependencies +5. Track all tasks with TodoWrite + +### Phase 3: Research (if needed) + +If the feature involves unfamiliar technology: +1. Research best practices and patterns +2. Find examples in the codebase or documentation +3. Identify potential pitfalls + +### Phase 4: Implementation + +For each task: +1. Write failing test first (TDD) +2. Implement minimally to pass the test +3. Refactor if needed +4. Mark task complete immediately + +### Phase 5: Testing + +1. Run full test suite — no regressions +2. Verify coverage — should not decrease +3. Test edge cases and error scenarios + +```bash +# Python +pytest -v --cov=src + +# TypeScript +pnpm test +``` + +### Phase 6: Review + +Self-review checklist: +- [ ] Code follows project conventions +- [ ] No security vulnerabilities +- [ ] Error handling is complete +- [ ] Tests are passing +- [ ] No debug statements or TODOs + +### Phase 7: Completion + +1. Verify all tasks complete +2. Stage appropriate files +3. Generate commit message +4. Create PR if requested + +--- + +## Output Format + +```markdown +## Feature Implementation Complete + +### Feature +[Feature description] + +### Changes Made +- `path/to/file.ts` — [What was added/modified] +- `path/to/file.test.ts` — [Tests added] + +### Tests +- [x] Unit tests passing +- [x] Integration tests passing +- [x] Coverage: XX% + +### Ready for Review +``` + +--- + +## Best Practices + +1. **Break down aggressively** — smaller tasks are easier to verify and commit. +2. **Test first** — every task starts with a failing test. +3. **Commit incrementally** — commit after each task, not at the end. +4. **Clarify before building** — ambiguous requirements lead to rework. +5. **Check existing patterns** — follow conventions already in the codebase. + +## Common Pitfalls + +1. **Starting without understanding** — jumping to code before clarifying requirements. +2. **Monolithic implementation** — implementing everything in one pass without incremental verification. +3. **Ignoring existing patterns** — building something inconsistent with the rest of the codebase. +4. **Skipping tests** — "I'll add tests later" means no tests. + +--- + +## Related Skills + +- `brainstorming` — Use before this skill when requirements are unclear or need exploration +- `writing-plans` — Use for detailed task breakdown when the feature is complex +- `test-driven-development` — The TDD discipline applied during Phase 4 +- `git-workflows` — Committing and shipping the completed feature +- `requesting-code-review` — Getting feedback before merging diff --git a/.claude/skills/git-workflows/SKILL.md b/.claude/skills/git-workflows/SKILL.md new file mode 100644 index 0000000..d9b0e3e --- /dev/null +++ b/.claude/skills/git-workflows/SKILL.md @@ -0,0 +1,119 @@ +--- +name: git-workflows +argument-hint: "[commit/ship/pr/changelog]" +description: > + Use when committing code, creating pull requests, shipping changes, or generating changelogs. Trigger for keywords like "commit", "push", "PR", "pull request", "ship", "merge", "changelog", "release notes", "conventional commits", or any git workflow beyond basic status/diff. Also activate when preparing code for review or automating the commit-to-PR pipeline. +--- + +# Git Workflows + +## When to Use + +- Creating commits with conventional commit messages +- Shipping code (commit + review + push + PR) +- Creating pull requests with proper descriptions +- Generating changelogs from commit history +- Preparing code for review or merge + +## When NOT to Use + +- Basic git operations (status, diff, log) — just run them directly +- Branch management strategy — use `using-git-worktrees` +- Code review content — use `requesting-code-review` + +--- + +## Quick Reference + +| Workflow | Reference | Key content | +|----------|-----------|-------------| +| Committing | `references/committing.md` | Conventional commits, message format, pre-commit checks | +| Shipping | `references/shipping.md` | Full ship workflow: review → test → commit → push → PR | +| Pull Requests | `references/pull-requests.md` | PR creation, description templates, gh CLI patterns | +| Changelogs | `references/changelogs.md` | Changelog generation from commits, Keep a Changelog format | + +--- + +## Conventional Commit Format + +``` +type(scope): subject + +body (optional) + +footer (optional) +``` + +| Type | When | +|------|------| +| `feat` | New feature | +| `fix` | Bug fix | +| `docs` | Documentation only | +| `refactor` | Code restructuring, no behavior change | +| `test` | Adding or fixing tests | +| `chore` | Maintenance, dependencies, CI | +| `style` | Formatting, whitespace | + +### Subject Line Rules + +- Max 50 characters, imperative mood ("Add" not "Added"), no trailing period + +--- + +## Ship Workflow + +``` +1. Pre-ship checks (secrets, debug statements) +2. Self-review (code quality, style) +3. Run tests (full suite, coverage check) +4. Create commit (conventional format) +5. Push to remote +6. Create PR (summary, test plan, checklist) +``` + +--- + +## PR Description Template + +```markdown +## Summary +- [Change 1] +- [Change 2] + +## Test Plan +- [ ] Unit tests pass +- [ ] Manual testing done + +## Checklist +- [ ] No breaking changes +- [ ] Tests added/updated +- [ ] Documentation updated +``` + +--- + +## Best Practices + +1. **Atomic commits** — one logical change per commit, not one file per commit. +2. **Explain why, not what** — the diff shows what changed; the message explains why. +3. **Stage specific files** — prefer `git add ` over `git add -A` to avoid committing secrets or unrelated changes. +4. **Reference issues** — include `Closes #123` or `Fixes #456` in footers. +5. **Pre-commit checks** — verify no secrets, debug statements, or commented-out code before committing. +6. **PR descriptions matter** — reviewers read the description before the diff; make it count. + +## Common Pitfalls + +1. **Committing secrets** — `.env` files, API keys, tokens in staged changes. +2. **Vague commit messages** — "fix stuff", "updates", "WIP" provide no context. +3. **Giant PRs** — 500+ line PRs get rubber-stamped; split into focused chunks. +4. **Amending published commits** — rewriting history others have pulled causes conflicts. +5. **Skipping pre-commit hooks** — `--no-verify` hides real issues. +6. **Force pushing to shared branches** — can destroy teammates' work. + +--- + +## Related Skills + +- `requesting-code-review` — Preparing changes for reviewer feedback +- `finishing-a-development-branch` — End-of-branch workflow decisions +- `using-git-worktrees` — Isolated branch management diff --git a/.claude/skills/git-workflows/references/changelogs.md b/.claude/skills/git-workflows/references/changelogs.md new file mode 100644 index 0000000..baa4c36 --- /dev/null +++ b/.claude/skills/git-workflows/references/changelogs.md @@ -0,0 +1,59 @@ +# Changelog Generation + +## Keep a Changelog Format + +Based on [keepachangelog.com](https://keepachangelog.com): + +```markdown +## [1.2.0] - 2026-04-19 + +### Added +- Password reset functionality (#123) +- Email verification for new accounts + +### Changed +- Improved error messages for validation failures +- Updated dependencies to latest versions + +### Fixed +- Race condition in session handling (#456) +- Incorrect timezone in date displays + +### Removed +- Legacy v1 API endpoints (deprecated since 1.0) +``` + +## Generating from Commits + +```bash +# Get commits since last tag +git log --oneline $(git describe --tags --abbrev=0)..HEAD + +# Group by type +git log --oneline --grep="^feat" $(git describe --tags --abbrev=0)..HEAD +git log --oneline --grep="^fix" $(git describe --tags --abbrev=0)..HEAD +``` + +## Category Mapping + +| Commit Type | Changelog Category | +|-------------|-------------------| +| `feat` | Added | +| `fix` | Fixed | +| `refactor`, `perf` | Changed | +| removal commits | Removed | +| `docs` | Usually omitted | +| `chore`, `test`, `style` | Usually omitted | + +## User-Friendly Descriptions + +Transform commit messages into user-facing descriptions: + +``` +BAD: feat(auth): add pwd reset (#123) +GOOD: Password reset functionality — users can now reset their password via email (#123) +``` + +- Write for users, not developers +- Include PR/issue references +- Explain the user-visible impact diff --git a/.claude/skills/git-workflows/references/committing.md b/.claude/skills/git-workflows/references/committing.md new file mode 100644 index 0000000..80a6d6d --- /dev/null +++ b/.claude/skills/git-workflows/references/committing.md @@ -0,0 +1,90 @@ +# Committing Patterns + +## Pre-Commit Checklist + +Before staging: +- [ ] No secrets (`.env`, API keys, tokens) +- [ ] No debug statements (`console.log`, `print()`, `debugger`) +- [ ] No commented-out code blocks +- [ ] Code is formatted (prettier/ruff) + +## Conventional Commit Format + +``` +type(scope): subject + +body (optional - explain why, not what) + +footer (optional - references, breaking changes) +``` + +### Types + +| Type | When | Example | +|------|------|---------| +| `feat` | New feature | `feat(auth): add OAuth2 login` | +| `fix` | Bug fix | `fix(api): handle null user in profile` | +| `docs` | Documentation | `docs(readme): update install steps` | +| `refactor` | Restructure, no behavior change | `refactor(db): extract query builders` | +| `test` | Add/fix tests | `test(auth): add login edge cases` | +| `chore` | Maintenance | `chore(deps): update React to 19` | +| `style` | Formatting | `style: apply prettier` | +| `perf` | Performance | `perf(query): add index on user_id` | + +### Subject Line Rules + +- Max 50 characters +- Imperative mood: "Add" not "Added" or "Adds" +- No trailing period +- Capitalize first letter + +### Body Rules + +- Wrap at 72 characters +- Explain **why**, not what (the diff shows what) +- Use bullet points for multiple changes + +### Footer Patterns + +``` +Closes #123 +Fixes #456 +BREAKING CHANGE: removed legacy auth endpoint +Co-Authored-By: Claude +``` + +## Staging Best Practices + +```bash +# Prefer specific files over blanket add +git add src/auth/login.ts src/auth/login.test.ts + +# Review what you're committing +git diff --staged + +# Never commit these +# .env, credentials.json, *.pem, *.key +``` + +## Commit Command Pattern + +```bash +git commit -m "$(cat <<'EOF' +feat(auth): add password reset flow + +- Add reset token generation with 1h expiry +- Implement email sending via SendGrid +- Add rate limiting (3 requests/hour) + +Closes #123 + +Co-Authored-By: Claude +EOF +)" +``` + +## Amending vs New Commit + +- **Amend**: Only for unpushed commits, only when fixing the same logical change +- **New commit**: Always for pushed commits, or when adding distinct changes +- **Never amend after pre-commit hook failure** — the commit didn't happen, so amend would modify the previous commit diff --git a/.claude/skills/git-workflows/references/pull-requests.md b/.claude/skills/git-workflows/references/pull-requests.md new file mode 100644 index 0000000..a15f2b0 --- /dev/null +++ b/.claude/skills/git-workflows/references/pull-requests.md @@ -0,0 +1,77 @@ +# Pull Request Patterns + +## Pre-PR Checklist + +- [ ] All tests passing +- [ ] Code self-reviewed +- [ ] No merge conflicts with base branch +- [ ] Branch pushed to remote +- [ ] Commit history is clean (no "WIP" or "fix typo" noise) + +## Creating a PR + +```bash +# Check current state +git status +git diff main...HEAD +git log --oneline main..HEAD + +# Push if needed +git push -u origin $(git branch --show-current) + +# Create PR +gh pr create --title "feat(scope): description" --body "$(cat <<'EOF' +## Summary +- [Change 1] +- [Change 2] + +## Test Plan +- [ ] Unit tests added +- [ ] Manual testing done +- [ ] Edge cases covered + +## Checklist +- [ ] No breaking changes +- [ ] Tests added/updated +- [ ] Documentation updated + +🤖 Generated with [Claude Code](https://claude.com/claude-code) +EOF +)" +``` + +## PR Title Format + +Follow conventional commits: `type(scope): description` + +- Max 70 characters +- Use description/body for details, not the title + +## PR Size Guidelines + +| Size | Lines Changed | Review Time | +|------|--------------|-------------| +| Small | < 100 | Quick review | +| Medium | 100-300 | Thorough review | +| Large | 300-500 | Split if possible | +| Too Large | > 500 | Must split | + +## Viewing PR Comments + +```bash +# View PR comments +gh api repos/owner/repo/pulls/123/comments + +# View PR review comments +gh pr view 123 --comments +``` + +## Draft PRs + +```bash +# Create as draft for early feedback +gh pr create --draft --title "WIP: feature" --body "Early draft for feedback" + +# Mark ready when done +gh pr ready 123 +``` diff --git a/.claude/skills/git-workflows/references/shipping.md b/.claude/skills/git-workflows/references/shipping.md new file mode 100644 index 0000000..c54e01a --- /dev/null +++ b/.claude/skills/git-workflows/references/shipping.md @@ -0,0 +1,101 @@ +# Ship Workflow + +Complete workflow: review → test → commit → push → PR. + +## Phase 1: Pre-Ship Checks + +```bash +git status +git diff --staged +``` + +Verify: +- [ ] No secrets in staged files +- [ ] No debug statements +- [ ] No commented-out code +- [ ] No unintended files + +## Phase 2: Self-Review + +- Check code quality and style compliance +- Verify security (no hardcoded secrets, proper input validation) +- Address critical issues before proceeding + +## Phase 3: Run Tests + +```bash +# Python +pytest -v + +# TypeScript +pnpm test +``` + +- All tests must pass +- Coverage should not decrease +- No new warnings + +## Phase 4: Create Commit + +```bash +# Stage specific files +git add src/feature.ts src/feature.test.ts + +# Commit with conventional format +git commit -m "$(cat <<'EOF' +feat(scope): description + +- Change 1 +- Change 2 + +Co-Authored-By: Claude +EOF +)" +``` + +## Phase 5: Push and Create PR + +```bash +# Push with upstream tracking +git push -u origin feature/my-feature + +# Create PR +gh pr create --title "feat(scope): description" --body "$(cat <<'EOF' +## Summary +- Change 1 +- Change 2 + +## Test Plan +- [ ] Unit tests pass +- [ ] Manual testing done + +Co-Authored-By: Claude +EOF +)" +``` + +## Quick Ship Mode + +For small, low-risk changes: +1. Skip detailed self-review +2. Auto-generate commit message from diff +3. Minimal PR description + +## Ship Report Format + +```markdown +## Ship Complete + +### Commit +**Hash**: `abc1234` +**Message**: `feat(auth): add password reset` + +### Checks +- [x] Tests passing (42 tests) +- [x] Coverage: 85% (+3%) +- [x] No security issues + +### Pull Request +**URL**: https://github.com/org/repo/pull/123 +**Status**: Ready for review +``` diff --git a/.claude/skills/mode-switching/SKILL.md b/.claude/skills/mode-switching/SKILL.md new file mode 100644 index 0000000..4c69c45 --- /dev/null +++ b/.claude/skills/mode-switching/SKILL.md @@ -0,0 +1,91 @@ +--- +name: mode-switching +argument-hint: "[mode name]" +description: > + Use when the user wants to switch behavioral modes for the session — adjusting communication style, output format, and problem-solving approach. Trigger for keywords like "mode", "switch mode", "brainstorm mode", "token-efficient", "deep-research mode", "implementation mode", "review mode", "orchestration mode", or any request to change how Claude responds for the remainder of the session. +--- + +# Mode Switching + +## When to Use + +- User wants to change response style for the session +- Switching between exploration and execution phases +- Optimizing for token efficiency during high-volume work +- Entering focused review or deep-research mode + +## When NOT to Use + +- One-off format requests ("give me a shorter answer") — just comply directly +- Switching tools or skills — modes affect style, not capabilities + +--- + +## Available Modes + +| Mode | Description | Best For | +|------|-------------|----------| +| `default` | Balanced responses, mix of explanation and code | General tasks | +| `brainstorm` | More questions, multiple alternatives, explore trade-offs | Design, ideation | +| `token-efficient` | Minimal explanations, code-only where possible | High-volume, cost savings | +| `deep-research` | Thorough analysis, citations, confidence levels | Investigation, audits | +| `implementation` | Jump straight to code, progress indicators | Executing plans | +| `review` | Look for issues first, severity levels, actionable feedback | Code review, QA | +| `orchestration` | Task breakdown, parallel execution, result aggregation | Complex parallel work | + +## Mode Activation + +``` +/mode brainstorm # Switch for session +/mode # Show current mode +/mode default # Reset +``` + +## Per-Command Override + +Modes can be overridden for a single command without changing the session mode: + +``` +/feature --mode=implementation "add user profiles" +/review --mode=deep-research src/auth/ +/plan --mode=brainstorm "design payment flow" +``` + +## Recommended Workflows + +### Feature Development + +``` +brainstorm → implementation → review → default +``` + +### Bug Investigation + +``` +deep-research → implementation → default +``` + +### Cost-Conscious Session + +``` +token-efficient → [work on tasks] → default +``` + +--- + +## Mode Files + +Mode definitions: `.claude/modes/` + +Customize modes by editing these files. Each mode adjusts: +- Communication style and verbosity +- Output format preferences +- Problem-solving approach +- When to ask questions vs proceed + +--- + +## Related Skills + +- `writing-concisely` — The token-efficient mode activates this skill's patterns +- `brainstorming` — The brainstorm mode uses this skill's questioning approach diff --git a/.claude/skills/openapi/SKILL.md b/.claude/skills/openapi/SKILL.md index a98b4f6..168e661 100644 --- a/.claude/skills/openapi/SKILL.md +++ b/.claude/skills/openapi/SKILL.md @@ -13,6 +13,7 @@ A design-first reference for REST APIs developers want to use. Standardizes on * - Designing or documenting a new REST API - Generating clients/servers from a spec (FastAPI, Express, NestJS, etc.) - Establishing error, pagination, versioning, or auth conventions for a service +- Generating API endpoints, models, and tests from a resource specification - Migrating a spec from OpenAPI 3.0 → 3.1 - Setting up lint/governance in CI diff --git a/.claude/skills/owasp/SKILL.md b/.claude/skills/owasp/SKILL.md index b9fe8a9..385ff6e 100644 --- a/.claude/skills/owasp/SKILL.md +++ b/.claude/skills/owasp/SKILL.md @@ -1,7 +1,7 @@ --- name: owasp description: > - Use when reviewing code for security vulnerabilities, implementing authentication or authorization flows, handling user input validation, or building web endpoints exposed to untrusted data. Trigger on keywords like XSS, SQL injection, CSRF, input sanitization, password hashing, and security headers. Also apply when auditing existing code for OWASP Top 10 compliance or conducting security-focused code reviews. + Use when reviewing code for security vulnerabilities, implementing authentication or authorization flows, handling user input validation, or building web endpoints exposed to untrusted data. Trigger on keywords like XSS, SQL injection, CSRF, input sanitization, password hashing, security headers, "security scan", "vulnerability scan", "npm audit", or "pip-audit". Also apply when auditing existing code for OWASP Top 10 compliance, scanning dependencies for known vulnerabilities, detecting hardcoded secrets, or conducting security-focused code reviews. --- # OWASP Security Patterns @@ -14,6 +14,8 @@ description: > - Preventing XSS, SQL injection, CSRF, or SSRF - Auditing authentication or authorization flows - Building endpoints that handle untrusted data +- Scanning dependencies for known vulnerabilities (`npm audit`, `pip-audit`) +- Detecting hardcoded secrets, API keys, or tokens in code ## When NOT to Use diff --git a/.claude/skills/performance-optimization/SKILL.md b/.claude/skills/performance-optimization/SKILL.md new file mode 100644 index 0000000..8311232 --- /dev/null +++ b/.claude/skills/performance-optimization/SKILL.md @@ -0,0 +1,116 @@ +--- +name: performance-optimization +argument-hint: "[file or function]" +description: > + Use when analyzing or optimizing code performance — including profiling, benchmarking, fixing N+1 queries, reducing bundle size, eliminating memory leaks, or improving algorithm complexity. Trigger for keywords like "slow", "performance", "optimize", "profiling", "memory leak", "bundle size", "N+1", "re-render", "benchmark", "latency", "throughput", or any request to make code faster. Also activate when investigating production performance issues or when code review flags performance concerns. +--- + +# Performance Optimization + +## When to Use + +- Profiling slow code to find bottlenecks +- Fixing N+1 query problems +- Reducing JavaScript bundle size +- Eliminating memory leaks +- Improving algorithm complexity +- Benchmarking before/after optimization +- Investigating production latency issues + +## When NOT to Use + +- Premature optimization — profile first, optimize second +- Caching strategy design — use `caching` +- Database schema/index design — use `databases` +- Code structure improvement — use `refactoring` + +--- + +## Quick Reference + +| Topic | Reference | Key content | +|-------|-----------|-------------| +| Profiling tools | `references/profiling.md` | Python (cProfile, py-spy, Scalene) and JS/TS (DevTools, Lighthouse, clinic.js) | +| Anti-patterns | `references/anti-patterns.md` | N+1 queries, unnecessary re-renders, event loop blocking, memory leaks | + +--- + +## Optimization Workflow + +1. **Measure first** — profile to find the actual bottleneck +2. **Set a target** — "reduce p95 latency from 500ms to 100ms" +3. **Optimize the hot path** — fix the #1 bottleneck, not everything +4. **Benchmark before/after** — prove the improvement with numbers +5. **Check for regressions** — ensure correctness wasn't sacrificed + +--- + +## Profiling Quick Start + +### Python + +```bash +# CPU profiling +python -m cProfile -o output.prof script.py +# Visualize: pip install snakeviz && snakeviz output.prof + +# Live profiling (attach to running process) +py-spy top --pid 12345 + +# Line-by-line profiling +kernprof -lv script.py # requires @profile decorator +``` + +### JavaScript/TypeScript + +```bash +# Bundle analysis +npx webpack-bundle-analyzer stats.json +# or: ANALYZE=true next build + +# Node.js profiling +node --prof app.js +clinic doctor -- node app.js + +# Benchmarking +npx vitest bench +``` + +--- + +## Common Anti-Patterns + +| Anti-Pattern | Detection | Fix | +|-------------|-----------|-----| +| N+1 queries | `django-debug-toolbar`, `prisma.$on('query')` | `select_related`/`joinedload`/`include` | +| Unnecessary re-renders | React DevTools Profiler | `useMemo`, `useCallback`, `React.memo` | +| Blocking event loop | `clinic doctor`, high event loop lag | `worker_threads`, async variants | +| Memory leaks | Heap snapshots, growing `process.memoryUsage()` | Remove listeners, clear refs, bound caches | +| Unbounded lists | No pagination, full table scans | Cursor pagination, `LIMIT` | +| Heavy imports | Bundle analyzer showing large deps | Tree-shaking, `import { x }`, code splitting | + +--- + +## Best Practices + +1. **Profile before optimizing** — intuition about bottlenecks is often wrong. +2. **Optimize the hot path** — 80% of time is spent in 20% of code. +3. **Measure, don't guess** — use benchmarks with statistical significance. +4. **Set clear targets** — "faster" is not measurable; "p95 < 100ms" is. +5. **Avoid premature optimization** — correctness and readability come first. + +## Common Pitfalls + +1. **Optimizing cold paths** — spending time on code that runs once. +2. **Micro-benchmarking without context** — 10ns vs 20ns doesn't matter if the DB call takes 50ms. +3. **Sacrificing readability** — an unreadable optimization is a future bug. +4. **Caching without invalidation** — stale data is worse than slow data. +5. **Ignoring algorithmic complexity** — no amount of micro-optimization fixes O(n^2) on large inputs. + +--- + +## Related Skills + +- `caching` — Caching strategies (memoization, HTTP, Redis, CDN) +- `databases` — Query optimization, indexing, connection pooling +- `frontend` — React rendering optimization patterns diff --git a/.claude/skills/performance-optimization/references/anti-patterns.md b/.claude/skills/performance-optimization/references/anti-patterns.md new file mode 100644 index 0000000..ca69a74 --- /dev/null +++ b/.claude/skills/performance-optimization/references/anti-patterns.md @@ -0,0 +1,115 @@ +# Performance Anti-Patterns + +## N+1 Queries + +**Signal**: Many small queries instead of one batch query. + +### SQLAlchemy (Python) +```python +# BAD: N+1 — each user triggers a query for posts +users = session.query(User).all() +for user in users: + print(user.posts) # lazy load, 1 query per user + +# GOOD: eager loading +from sqlalchemy.orm import joinedload, selectinload +users = session.query(User).options(selectinload(User.posts)).all() +``` + +### Prisma (TypeScript) +```typescript +// BAD: N+1 +const users = await prisma.user.findMany(); +for (const user of users) { + const posts = await prisma.post.findMany({ where: { authorId: user.id } }); +} + +// GOOD: include +const users = await prisma.user.findMany({ include: { posts: true } }); +``` + +### Django +```python +# BAD +for order in Order.objects.all(): + print(order.customer.name) # N+1 + +# GOOD +for order in Order.objects.select_related('customer').all(): + print(order.customer.name) # 1 query with JOIN +``` + +## Unnecessary Re-renders (React) + +**Signal**: Components re-rendering when their data hasn't changed. + +```typescript +// BAD: new object created every render + + +// GOOD: stable reference +const style = useMemo(() => ({ color: 'red' }), []); + + +// BAD: new function every render +